# Question
Title: Resource Files creation and quick parsing
I'm having to come up with the format of my Resource File and I'd like to ask about the ways they're made, for example, if I'm using the code:

```
ifstream fileReader;
fileReader.open("Test.fbx");

if(fileReader.is_open())
{
    char buffer[256];
    while(fileReader.eof())
    {
        fileReader >> buffer;
        //Here
    }
}

```

When parsing .OBJ or .ASE files from 3DS Max, I could simply check for a...

```
if(strcmp("VERTEX:", buffer) == 0)
{
    //Whatever I want to do with vertexes
}

```

...because each vertex value was separated by an empty space, but when parsing a .FBX there's no spaces until the end of the line, and thus I had to:

```
int lineLength = strlen(buffer);
for(int i = 0; i < lineLength; i++)
{
    //buffer[i] has my current char
}

```

And get the values together by counting how many ',' I went through, etc. I think the 2nd way is much worse due complexity, but I don't know how it affects performance-wise.

What are the best practices for the creation of asset files? I plan on having all of them in a single file, but separated by something like "IMG:" (all image data defined by IDs) "OBJ:" (all model data) "WAV:" (all audio) etc.

**Edit:** I'm asking if there's any "best practices" when developing your own resource file, and it'd be binary of course, and I didn't meant to use the original resource files at all. Something like this:

```
Resource.dat (in ASCII)
IMG:
1 MyPicture.jpg [binary data composing only what I need from a .jpg file] ;
2 AnotherPicture.bmp [binary data composing only what I need from a .bmp file] ;
OBJ:
3 MyModel.fbx [fbx binary data] ;

```

etc I won't save all the file headers for example, and I probably won't have more than one format for my resources, I'll be converting them all to just the data I need into my resource, such as the imageWidth, imageHeight, and 4 values per pixel for a image resource. I have another code which parses these original files (.jpg, .fbx) and I'm going to save them into a new resource file (in a bloated .dat, organized by object index) to be used in the game engine, but I'd like to know any best practices while creating such a format so I don't code everything just to figure out after *"Ops, I should've also saved \[data\] because I need it now"*

# Answer
'What are the best practices for the creation of asset files' is a huge, huge question, but as a fundamental, the sort of text-based parsing your question starts with is slow, unwieldy and clunky for anything more than trivial data. For example, how do you hope to include WAV data in a text file, since it is binary?

As a basic starting point, split your consideration into two parts. The first is knowing what format you need your individual assets to be in. Do your images need to be compressed textures, PNGs, BMPs? Is all of your audio going to be WAV format? Each format requires its own loader, and each format is going to be almost entirely different from every other format, with its own parser, its own versioning and its own way of working. More to the point, most pre-existing formats are massively complicated, which is why you generally re-use the loader/parsers other people have implemented. There's a reason why they are complicated, because they have to handle a lot of cases! You will burn an awful lot of time trying to re-invent those wheels, so you should ask yourself whether you really need or want to.

The second is how you manage the structure of your assets. Composite files (collections of individual assets) are a useful tool, but they need proper indexing (the ability to find individual assets given only a name or unique ID). Generally you build a composite file system to be completely ignorant about the content of the individual assets - they are stored with some metadata (filename, type, unique ID, contents hash and perhaps some additional type-specific tags), but the contents are treated as an opaque binary blob, to be loaded into memory and passed to a parser appropriate to the asset type. Nothing in the composite file format needs to know anything about how to parse the assets it contains - it's rather more like a ZIP file. In fact, ZIP files are a pretty common form of composite file, since you already have libraries to load and handle them, and pre-written tools to generate them. But have you asked yourself why you need or want composite files? Have you asked how you intend to reference and arrange those files? How would you tell your code to look for 'shark.png' when 'shark.png' is actually an asset in 'fish.pak'. Does all of the code simply assume one single composite file? What happens when that file gets too large? What happens when you get naming collisions in the file because you've got two textures with the same name? Do you support subdirectories in the file? You'll find yourself needing to re-implement your own file system unless you are careful.

As a general rule, you want to be storing your assets in as near to their final form as possible, so that loading involves nothing more than getting them off disk and into memory, and then telling the system that they are their. Parsing OBJ files at runtime is going to be terribly slow, as they are generally intended as an **intermediate** form for your assets. Generally you would have a tool which reads .OBJ files that your modelling tool has exported, and it spits out a binary version of the asset in just the right format for your engine to load with a minimal amount of work. Worrying about whether your string parsing code is the most efficient sort of string parsing code is very much like re-arranging deck-chairs on the Titanic - even the best text asset parsing code is going to be horribly slow if you have to do it at run-time.
> 1 votes

# Answer
Things like OBJ files should be used only as *intermediates*. Your production game should use custom binary formats for models and anims that directly represent how models are stored in your game's memory/VBOs

You should have a separate build step that converts your tool created intermediate files into your game files. It should also convert things like PNGs and such into efficient-for-GPU formats like DDS, convert all audio into a single compressed format like OGG Vorbis, and pack all your assets into bundles (Zip works ok, and you can use physicsfs to read it).

Custom text formats have little use in production. Sometimes they're useful as an intermediate format for custom data, though JSON/XML work fine (you should make a nice tool for the custom data, not expect users to edit the files directly).
> 0 votes

---
Tags: c++, assets, asset-creation
---


title: UI of a city-building game

text:
# Question
Title: UI of a city-building game
I'm completely new to gamedev and want to learn how to design good UI for a city-building game (like SimCity).

What books and other materials can I read in order to learn it?

# Answer
> 7 votes
The first step is to have design goals. Figure out what kind of features your game will have, so you know where to focus your efforts and what designs to look out for. Will it be graph heavy? Will it be minimal and have panels upon panels hidden away? Will most of the action take place in the UI or in the game world? Will it be animated? Does it have a theme (industrial, sci-fi, etc.)?

Once you have your requirements you can start your research.

The nice thing about user interfaces is they're visible, so it's easy to see other designs without digging into source code. I think your best bet is to study the UIs of popular city building games. Buy a few of them on Steam, check out the design, see what you like and what you don't. Build up the ideas you started forming when deciding on your requirements.

Finally, play testing. Test a lot. Have other people test. Have people unfamiliar with those types of games test. Give them tasks that are common to the regular game play, like "Increase the taxes on industry by 4%", see if they can do it, see how long it takes them. Don't watch. People never perform the same way when they're being watched.

I think visual design is something that is difficult to learn with books. It's best to learn with practice.

# Answer
> 2 votes
As a supplement to Byte56's answer, I can give you list city-building (or similar) games that I think have a GUI worth mentioning (at least parts of it):

* Simcity series, Anno series, Settlers series (obviously)
* Castle story (still in development)
* Dungeon Keeper 2 (rather simple)
* Evil Genius
* Forge of Empires (many other online empire-builders may qualify, they're mostly similar)
    + EDIT: Screw it, they're not all similar, GoodGame Empire is way more awesome in terms of UI - accesability, reports, tutorials, everything
* Gnomoria (negative example)
* Knights of Honor
* Stronghold
* Tropico, especially 3 and 4
* Children of the Nile
* Theme Hospital, possibly other "Theme" games (haven't played any)

---
Tags: strategy, ui-design
---


# Question
Title: Figuring out which direction my object is facing on a 2D plane?
My friend and I were messing around in XNA 4.0 making a 2D racing game. Kind of like this one: Ivan “Ironman” Stewart’s Super Off Road. The problem we are having is knowing which direction the car is facing to move it appropriately. We could track the direction by a enum value North, South, East, West but we don't want to do that for a number of reasons.

We were wondering if there was a way to accomplish this via math. Maybe by having an anchor point designated at the hood of the car and having the car always move towards that spot and then move that anchor point. We aren't sure. Or maybe there is a way using a 2D Vector.

I figured since we hit a hard spot, we should ask the coding community for help!

Just to be clear. I'm not looking for code; I just want to discuss some concepts of 2D movement in all directions without having to track a direction enum. I know that can't be the only way to do it.

# Answer
Vector :

Vectors describe the magnitude and direction. If you just want the direction you simply normalize it. This causes the vector to shrink to fit into the unit circle. Meaning that it has magnitude/length of 1.

From rotation angles:

To get the x and y components for your direction:

```
//(pi/180) - > degrees to radians. (180/pi) - > radians to degrees
x = cos(angle*(pi/180));
y = sin(angle*(pi/180));

```

This is similar to a vector after being normalized.

You simple multiply these values/vectors to change your velocity ( or whatever that requires the direction) with a speed. So that the x and y components extend to the right length respectively.
> 6 votes

---
Tags: xna, c#, 2d, movement, racing
---


title: Rotating and pitching a turret

text:
# Question
Title: Rotating and pitching a turret
I am new to game development and I was trying to build a turret model, and control it through lua script in shiva3d. I can rotate it around the y axis which is no problem, but when it comes to pitching, I am not sure how to do that in a way which is independent of the Y rotation, for example,

in the default position, rotating with a positive value around X aims upwards, which is what I expect.

when I rotate it by 180 degrees around Y, the positive rotation around X aims downwards towards the ground instead of upwards.

on the other hand, if I rotate by 90 degrees, the turret rotates around it self as if its rolling...

I am not sure what to look for in order to understand how rotation in a 3d world should happen, so any pointers on that would be much appreciated

# Answer
It sounds like you're doing the rotations in the wrong order. The pitch rotation should be applied first, then the yaw rotation. That way, the turret is always in "default position" when pitch is applied, so the pitch rotation will do the right thing. Then you apply the yaw rotation to get it pointing the right horizontal direction.
> 1 votes

# Answer
A good pneumonic when performing 3D matrix operations is ISROT. This gives you the order of operations to follow when working with matrices.

Identity Scale Rotation Orbit Translation
> 1 votes

---
Tags: rotation, lua
---


# Question
Title: What are some ways I can create random but consistent levels with an increase in difficulty
So I am relatively new to gaming, however, I am working on a breakout style game and I am not sure how to generate levels. In theory I would like some approach that will let me generate tons of levels with slightly increasing difficulty. After these are generated I would like them to be the same for every user every time. That last part got me thinking about maybe using some sort of noise to generate the maps.

Does anyone have experience in this area? Are there some best practices? It would be great if the answer was "broader" than Breakout, but I can live with just Breakout.

# Answer
Generally speaking, you want to look for the *variables* that make levels difficult. So, to use Breakout as an example:

1. Number of *walls* \- the number of things the player must break to complete the level.
2. Wall *durability* \- the number of hits each wall takes before it breaks.
3. Power-ups - the number of power ups hidden in the walls, and the ease they can be reached.

and so on. There are other x-factors to consider (are there power-downs? do some blocks behave differently?), but this should be enough to get you on the right path.

As for they layout of the walls, I suggest looking up cellular automata. You can get regular-looking patterns by combining a few simple rules that way. So you might look through some of the results they give you and choose different pattern rules based on how often they put walls close to the paddle and up against the walls.

Games that take place in interior environments would have to use other methods for generating their layouts, of course.
> 4 votes

---
Tags: level-design
---


# Question
Title: Is there a way to squash/stretch a sprite based on an angle?
I have a ball that can move along any angle, and I want to squash and stretch it based on this angle. To be clear, if you dropped the ball down at a -90 angle, the squash would be all along the y, and the stretch on the x. This wouldn't work however for a 0 degree angle, where the squash is on the x, and the stretch on the right.

Is there a way to generalise this into an equation?

# Answer
> 3 votes
It is not possible to deduce X and Y stretch factors to reach your goal, they simply do not exist.

One solution is to first rotate your object so that its main axes coincide with the main X and Y axes, then apply the squash/stretch transformation, then rotate the object back to its original orientation.

In terms of matrices, this would be the matrices involved, where `SQ ≤ 1` is the squash factor, `ST ≥ 1` is the stretch factor, and `vx` and `vy` are the normalised directions of motion (*ie.* you can get `vx` and `vy` by normalising your direction vector):

```
| vx  -vy |    | SQ   0 |    |  vx  vy |
| vy   vx |    |  0  ST |    | -vy  vx |

```

The product of these matrices is:

```
| SQ*vx²+ST*vy²  (SQ-ST)*vx*vy |
| (SQ-ST)*vx*vy  SQ*vy²+ST*vx² |

```

It is not a trivial matrix but you can probably inject it into your framework. Otherwise, you can still apply the three transformations (inverse rotation - scale - rotation) separately.

# Answer
> 0 votes
If your ball is actually a circle, you can just draw it as an ellipse, rather than a circle, with one axis aligned along the direction of travel. When the ball hits a surface, transition from being stretched along the direction of travel to being squashed perpendicular to the surface, and stretched parallel. Then as the ball leaves the surface, do the opposite, ending up stretched in the new direction of travel. This means that the directional axis will essentially rotate around the point of impact, which is what I think you want.

If you're transforming a bitmap, then some combination of rotation in the direction of travel and/or shear & scale transforms should do it. Draw out a few "keyframes" of the squash effect to see what works.

# Answer
> 0 votes
If you want to generalize it to an equation you'll need to be able to stretch and squish the image on things other than the x and y axis (A diagonal drop requires squishing the corners together and apart) An easier solution could be as simple as making your sprite sheet have a nicely animated squish in one direction then rotate the ball such that "down" on the sprite is the direction of the collision.

If you are not able to do so for whatever reason, and do have the ability to squish/stretch in any direction, there are math solutions available to you. You can get some simple directions of the stretch/squish by finding the perpendicular/parallel lines to the collision vector (center of ball to point of impact).

You can also tell how much something should squish along a specific axis (say if you only have x and y to deal with and you're fine with it) by checking the dot product of the collision vector normal against the stretch direction. 1 means that you should be doing maximum squish and 0 means you should be doing maximum stretch along whatever direction you specify.

---
Tags: animation, actionscript-3
---


# Question
Title: Level design algorithm/pattern for Linerunner etc
I am wondering: how does someone make levels for a game like Linerunner or any other game that uses similar patterns?

**About Linerunner (game)**
You are a stick man running, you have to jump or crawl without hitting boxes. Google Play is very illustrative.

**The algorithm I am looking for**
How does the game engine know that if it places a box here and here and here, the user will be able to make it without hitting any of the boxes? Two possible solutions came to mind, but neither of them seem very good.

1. Design the entire level.
2. Create an array of small patterns the user can win in and then join the patterns to create a level.

I hope someone understands what I am talking about, otherwise I am willing to explain in depth what I want to accomplish.

# Answer
Your ideas are good, but I think with a little bit of math and empirical testing, you can figure out how to make these levels dynamically. You have a few factors that effect the placement of the blocks:

* How fast the character is running
* How long does it take to reach the minimum height to clear a box?
* How long does the character remain above the minimum height to clear a box?
* How long does it take for the character to touch the ground again and be ready to jump after one jump? This shouldn't be affected by the horizontal speed
* How long does it take to get below the minimum height to get under a box?)

With that information, you can figure out the following measurements:

A: How far apart two "paired" ground boxes can be placed. These are the boxes where the user is expected to jump late enough to clear *two* boxes. Calculated using the time above the minimum height to clear a box and the speed of the character.

B: How close together two ground boxes can be placed. Calculated using the speed of the character and the time it takes for a jump.

C: How close together a ground box -\> air box pair can be. Where the character needs to jump over a box, then duck under the next box. Calculated by the time it takes to reach the minimum height to clear a box (because it'll be the same as the time it takes to clear a box and hit the ground) and the speed of the character.

D: How close together a air box -\> ground box pair can be. Where the character needs to duck, then jump.

E: (Not pictured because I forgot) How close together two sky boxes can be. Calculated using the speed of the character and the time it takes to duck.

There will be some room for setting the difficulty here. You can make the jumps tight or loose depending on the difficulty. A tight jump would just barely clear the edges:

Where a loose jump would have much more play on either side of the boxes. That's where the empirical part comes in, you need to test and see how reasonable it is to get those jumps in with the input device you're using.
> 2 votes

---
Tags: algorithm, level-design, patterns
---


# Question
Title: Actors with multiple Textures - class Hierarchy?
In my 2D side-scroller game I have a bunch of actors being drawn, each of which has a single, non-animated `Texture` (a png image). These actors all inherit from a base `GameActor` class.

I want to add some more NPC's (e.g. tanks or cannons) that have one texture that doesn't move (the base) and another that rotates to shoot at things (the gun / barrel). How should I structure my Actor class hierarchy so as to allow for this? Should I refactor my base Actor class to allow for N textures? Or should I create a brand new sort of Actor for things that need \> 1 texture (and then have to manage these actors separately from 'regular' actors)? Or is there a better approach I can't see?

Thus far I've been opting to keep things as simple as possible (KISS, right?), but am not sure how to proceed.

Any pointers greatly appreciated.

# Answer
> 5 votes
I've actually read a good article on this (Deep hierarchies vs composition in game coding), unfortunately I can't find it. At any rate, the guy there advocated composition over inheritance whenever in doubt. I'll try to give you the gist of it as applied to your situation.

I honestly think that composition is the way to go (and not inheritance) when it comes to game coding. Usually, the case is you have some basic thing on which you want to put various behaviors in various combinations, rather than make it have one behavior and ALL other behaviors derived from that. I.E. your GameObject base class might support translation and rotation as all game elements should be able to do that. Further more only SOME of your game objects also need collision detection, and more-over some of them might need to emit particles. Now obviously, collision detection ability doesn't automatically imply "ability to emmit particles as well" nor does the other way around make sense. So rather than having CollidingGameObject extends GameObject and then ParticleEmittingGameObject extends CollidingGameObject (in order to be able to also have game objects that support collisions and particle emissions), it's much better to make a base Component class, extend from it a CollisionDetectionComponent (which can work with a GameObejct instance) and a ParticleEmitting component, then have your base GameObject class support multiple components (via composition, like a list of components field), and adding and removing of components. Sure, at the beginning it will be more tedious to code, but once you have all your major components implemented and the component-applying mechanism in place for the GameObejct class, it will be a lot easier to modify/refactor things later, plus your code will be more performant. This is how Unity have coded their engine.

So in your case, I'd make two Texture components, one for static and one for animated one, and then add them as needed on the GameObject base class (i.e. some GameObjects will only have 1 Static texture component, some will have 1 Static and 1 animated, and then later on if your fancy strikes you to make a dual turret tank, you can just add 1 Static and 2 Animated and you're good to go).

# Answer
> 1 votes
For your situation, it would probably be better to avoid modifying your Actor class hierarchy for this problem. Re-factoring your base Actor class to accommodate multiple textures will probably cause a ripple effect that will require you to re-code how your derived Actor classes use textures (which could be a hassle if you have a lot of derived Actor classes). On the other hand, creating a new kind of Actor class in your hierarchy just for multiple textures will make your code less flexible and more difficult to change if you decide to change how your textures are used or displayed. It's better to use inheritance for "is-a" relationships rather than "has-a" relationships.

Therefore, I suggest you instead use a hierarchy for your textures. You could create a `DualTexture` class that inherits from your `Texture` class. Then, you could have this class contain two separate images. Any Actor that uses this kind of texture can modify the rotation of one or both of the images through the public methods of `DualTexture`. Thus, your NPCs could use this kind of texture and handle the game logic to rotate the "cannon" part of the texture without modifying the "base" part of the texture.

Alternatively, if you might be later adding actors made up of more than 2 textures, you can instead make a `MultiTexture` class for your texture hierarchy. This texture class could contain N images in a list. As a result, any actor using this texture class would be able to have as many textures as it needs.

# Answer
> 1 votes
I think the best design to add some sort of constraints or parenting to your Actors, and make the Turret another Actor which is a child (or location constrained to) the base. That way the rest of the engine can still treat Actors as simple, single part objects but you can build up more complicated structures like a tank.

---
Tags: architecture
---


# Question
Title: How can I get started making textures for 3D games?
Just wondering where to find good tutorials on making textures for 3D games?

Also, is it common practice to take photographs and convert them into game textures or do designers draw the textures themselves?

**UPDATE:**

To make the situation more specific, I am trying to make a simple game where the game character is in a small building so I would be making textures for computers, tables, chairs, doors, windows, walls, etc... What is outside the building is mostly irrelevant. I don't have any experience in 3D modeling though I'm thinking of using Blender.

# Answer
> 5 votes
How you should create the textures depends a lot on the visual style of the game.

A lot of texture assets I see from more photorealistic games, (or fantastical games with realistic structures) are indeed retouched photographs. It is mostly just with the diffuse colors that photographs are used. Usually, entire textures for props and smaller details are used, but for entire walls and facades it's not uncommon to combine elements from different photographs of buildings to create an entirely new one for fictional settings. Sky textures are likely going to be taken as photographs too.

Games that have more of a stylized look tend to use more hand-drawn textures from scratch, especially if you're going for a cartoon-like look. In this case you'll need some decent drawing skills to pull off good depth and lighting effects. In last-gen games where normal mapping was much less common, such features had to be drawn in by the artist. It is still useful, though, to use real photographs as a reference.

If you're not very artistically inclined, use existing photos as a base. CG Textures has a large collection of photographs of realistic materials. The best way to start out is picking a texture and in a program like Photoshop, start adding in additional layers or adjustment layers to enhance the colors or shading of the photo.

Gamasutra also has a great article on how to use the high pass filter in Photoshop to improve the look of tiled textures. This filter gives you a finer control over the details of a photograph.

# Answer
> 2 votes
> I don't have any experience in 3D modeling though I'm thinking of using Blender.

Just a warning: 3D modelling is hard. That being said, blenderguru is an excellent source of tutorials. Also, blendernation has links to some useful resources as well.

Regarding textures: Using Blender you can bake a high-poly model (including lighting/occlusion/normals) onto a low poly model. You can get really nice results this way without a lot of artistic skills.

Regarding photos: Using a lot of texture stock is common. Experiment with combining textures, clone-painting textures onto your own work etc. Look up tips for seam removal.

# Answer
> 1 votes
I really recommend "Blender" because it integrates Blender Game Engine and can export to WebGL games in the future.

There some good tutorials you can learn on making textures, they aren't saying it is for 3d games but it looks is definetly possible because they don't have high poly may be ideal for 3d games.

http://cgcookie.com/blender/2011/07/12/creating-a-grungy-brick-wall/

http://cgcookie.com/blender/2011/04/21/tip-symmetrical-texture-painting/

# Answer
> 1 votes
Texture can be obtained in countless ways: there are websites which sells or give free textures for various kind of materials. You can use own photos, stock photos, google images, deviant art, hand drawing, possibilities are endless.

If you want to use good tools, learn using tools used by pros, eventually become a pro, I would advise you against Blender.

For modelling and a lot of 3D manipulations I would suggest to try 3DS Max, Maya or Softimage. You can use them for free if you are a student. : http://students.autodesk.com/?nd=download\_center

For modelling/sculpting I would suggest Zbrush, it is a wonderful tool, but it's not very cheap. So instead try Autodesk Mudbox (free if you are a student) or Nevercenter Silo.

For 2D I would suggest Photoshop.

You can also use Cinema 4 D and Lightwave but I don't know the price and beside that, Max, Maya and Softimage are the most used pro tools.

You can find a lot of good tutorials online about working with 3D modelers, you just need some patience, work and inspiration.

Good luck!

Giving it a second thought if you are trying to make a simple game, you can use various resources already found on net. It's not a good idea to start learning many things on same time, it can be overwhelming. I think you better focus at one task at a time. So I'd say it's better to start learn making games and use the free resources you can find and worry about 3D modelling later when you are more experienced.

# Answer
> 0 votes
I am an intermediate level game designer and I've been learning whatever I can over the past two years. From my experience to answer your question logically versus saying no you can or can't unlike alot of others out there that seem to dodge this rhetorical question is there is no easy way to do this. You can go about it in several ways. Your first step is to decide what kind of game you will be creating and then the artstyle and coloring involved. Next you will need to create your 3d models and Props. Following this would then be a good point to become more involved in texturing and you're best bet is through research and trial and error. I have yet to see a perfect answer from any single person on this that would be purely beneficial or instructive other than actual photoshop tutorials that I have come across. The trickiest part of it all is removing the seam so that it doesn't tile across the map and creates the illusion that it's one big texture and this too takes time and practice. With this though you have to take into mind how dense you want your game to be so the scaling for it of X by X size will determine if your game is HD or not because the less you use the higher the chances of pixelization that occur but this is also dependant upon the engine that you use so you will want to make sure that it supports this as some are easily scalable so that there is no need to worry about it.

In Addition to what i've mentioned just search for " How to Make Game Textures in Photoshop " and follow that. Some other stuff that can help is these links -

(1) http://www.katsbits.com/tutorials/textures/make-better-textures-correct-size-and-power-of-two.php

(2) http://www.sandboxgamemaker.com/wiki/index.php?title=How\_to\_make\_new\_textures

I hope this helps and feel free to visit my website at GameGroove Dot Ucoz Dot Net to get ahold of me quicker if you need more help.

* Deygus

---
Tags: 3d, textures, art
---


# Question
Title: Music and SFX Question on Memory Efficiency
What should I recommend: MP3 or WAV for the SFX? Also, what should I do to handle the memory in music or SFX?

# Answer
> 2 votes
Both type of sound file, **WAV** and **MP3**, are okay but make sure you know how to stop the music through coding and you know LibGDX, right? Make sure that you can afford it depending on the device you're testing.

---
Tags: libgdx, music, memory-efficiency, sound-effects, extension
---


# Question
Title: Saving and Loading the Game (Automatically or Manually) via Internal Storage Only (Tablet PC Issues)
Here is my question. When making a game app for Android, I considered first the device. It's no problem to save progress everything (from levels to records) on a smartphone because it has an SD Card slot. Exception to this, the tablet PC, it can really nothing but on internal only storage.

For example, I'm using this tutorial for audio spectrum (*see http://www.youtube.com/watch?v=5cN1VzZXcdo*) that involves copying from internal to external in order to detect frequency. It works on the desktop but not on the Android device (Tablets only \[i.e. *Google Nexus Tablet*\]).

Is there a way to optimize save/load game problems due to internal/external device issues? Plus, additionally, what's the reason why my device won't work on tablets, except the desktop, while testing the audio spectrum code and why? Also, is it the same with saving/loading game?

# Answer
I finally understand about **Preferences**. Here's the example and observe the comments. Take note that this is sample from my previous projects.

```
public class Temporary_Database
{
    //TODO __________[ Field data ]__________
    public Preferences pref_1;
    public Preferences pref_2;
    public String male_name;
    public String female_name;

    //TODO __________[ Temporary Database's Constructor ]__________
    public Temporary_Database()
    {
        pref_1 = Gdx.app.getPreferences("male-identity"); // You can use any String ID written within the parameter.
        pref_2 = Gdx.app.getPreferences("female-identity");
    }

    //TODO __________[ Loading Methods ]__________
    public void Load_Name_of_Male(String male_name)
    {
        male_name = pref_1.getString("Male's Name", male_name); // "male_name", for example, is the String object and this is where you recall the value itself through loading it.
        this.male_name = male_name;
    }

    public void Load_Name_of_Female(String female_name)
    {
        female_name = pref_2.getString("Male's Name", female_name);
        this.female_name = female_name;
    }

//TODO __________[ Saving Methods ]__________
public void Save_Name_of_Male(String male_name)
{
    pref_1.putString("Male's Name", male_name); // "male_name" is the String object and this is where you change the value itself through loading it.
    pref_1.flush(); // Flush to save changes.
}

public void Save_Name_of_Female(String female_name)
{
    pref_2.putString("Male's Name", female_name);
    pref_2.flush();
}

    //TODO __________[ Set Value Method ]__________
    public String Get_Male_Name()
    {
        return male_name; // Uses as the new value itself after saving it and preferred to be used in loading action.
    }

    public String Get_Female_Name()
    {
        return female_name;
    }

```

}
> 1 votes

---
Tags: libgdx, music, loading, savegame, filesystem
---


title: Using Assimp to load dae files

text:
# Question
Title: Using Assimp to load dae files
I've started looking into using Assimp to load in dae collada files into my game.

I believe I've managed to load the file into aiscene. I am using c++, OpenGL and SFML.

My problem lies with extracting the data from aiscene to use in my game.

My question:

What steps do I need to take to get my model on the screen after I have the data loaded into aiscene?

I don't even know where to start so I would be grateful for any tutorials or books showing this or simple examples?

Thanks very much!

# Answer
> 6 votes
You can look at the assimp docs here: http://assimp.sourceforge.net/lib\_html/data.html and http://assimp.sourceforge.net/lib\_html/structai\_scene.html

An asset loaded by assimp is assembled into several data structures. At the top there is the aiScene, which contains both a list of aiMesh mesh data, and an aiNode hierarchy for placing instances of the mesh data using various transforms and parenting. The scene also has a list of all materials and textures.

First you will probably want to create textures and possibly shaders from the list of textures and materials in the scene. The aiMesh data has all of the vertex data you need, so you'll want to create a vertex buffer for each mesh. Each mesh has one material, and each material can have multiple textures (color map, normal map, specular map, etc).

Then you walk the aiNode tree, calculate and set the transform, and draw the mesh referenced by the node. To draw the mesh, bind the shader and textures for the material used by the mesh, and then draw the vertex buffer.

If you want to support animation, you can look at the aiAnimation list in the scene. Each animation consists of a number of channels, which can affect a node's transform matrix. Skeletal animation is done via bone weights for the vertices of a mesh, and is a bit too complicated for this post.

I've written a simple opengl asset viewer based on assimp using the C api, which does skeletal animation. You can look at as an example: https://github.com/ccxvii/asstools/blob/master/assview.c

# Answer
> 1 votes
You have to extract the vertecie information. This data is containd inside the assimp model (i used an older version of assimp when i did this ) And from there you have to insert that data in to your buffer, to create a OpenGL buffer so you can use that one to draw the model.

http://ogldev.atspace.co.uk/www/tutorial22/tutorial22.html

Thats probably a perfect tutorial, since it´s about loading the model and using OpenGl. hope this helps.

---
Tags: c++, opengl, collada, assimp
---


# Question
Title: Is it a bad idea to have Game1 static in XNA?
Is it a really bad idea to have my `Game1` class as static? As at the moment in my `Game1` class I have a class called `TileHandler` which handles everything to do with my current set of tiles, and `AnimalHandler` which handles all my animals (surprisingly).

Now if I am in `AnimalHandler` and want to check if a tile is walkable from `TileHandler` then that causes problems or I have to pass a list of walkable tiles into `AnimalHandler`, which I'd rather not do.

What would be easier would be to make `Game1` static and then in `AnimalHandler` just go `Game1._tileHandler.WalkableTile(position)`.

Now I can't see anything immediately wrong with this or anything that'd cause any problems but I've only just started using static classes, so does anyone more knowledgeable see any giant reason why that's a bad idea?

# Answer
> Now I can't see anything immediately wrong with this or anything that'd cause any problems but I've only just started using static classes, so does anyone more knowledgeable see any giant reason why that's a bad idea?

When you have a shiny new hammer, every problem looks like a nail.

**In general there is nothing wrong with static classes and/or methods, if used properly** (for things that do not have or depend on per-instance state). However, in your case you are misusing them to *hide* a dependency on per-instance, confusing this with removing the dependency. It also appears that you are exposing implementation detail of the `Game1` class, which is also generally bad.

Here is the crux of your issue:

> ...if I am in `AnimalHandler` and want to check if a tile is walkable from `TileHandler` then that causes problems or I have to pass a list of walkable tiles into `AnimalHandler`, which I'd rather not do.

Ignoring the possibility that `AnimalHandler` needing these tiles may itself be a bad design (with the names you have chosen it's hard to tell the details of these classes) for the moment...if `AnimalHandler` needs a list of walkable tiles, then it needs a list of walkable tiles. **It is generally better to make dependencies more explicit than less so**, as it makes code more self-documenting. By passing the list directly to `AnimalHandler`, you explicit call out the fact that it needs such a list. If you instead make everything static and public so you can just access the static list held elsewhere in the code, all you do is *hide* the dependency without actually solving or removing it.

For a small game that doesn't need to scale this won't be a problem, per se, but it may lead you down the path of a bad habit so you may want to consider not doing it. At the very least keep this in mind for the next project you work on.
> 8 votes

# Answer
The reason that calling TileHandler in a static context is not the best possible design, is that it couples components of your design that could otherwise be decoupled.

If you choose to have more than one TileHandler in the future, you'll have to do a lot of work to accommodate this change.

If you choose to remove TileHandler, you'll have to do a lot of work to accommodate this change.

Suppose you build a different level/zone in the future, that handles tiles in a different way from your current TileHandler. Then you either need to have a way to specify the method of tilehandling to use, or you need to call a different handler.

If the TileHandler was passed as a parameter to objects that use it, then you can simply pass a different one next time, or set a different tile handler on objects that use it later.

Personally, I access many things in my XNA games from a static context, and assume that I'll never have more than one of them.

If you want to be able to reuse your game engine code in your next game, you're likely going to have to rewrite much of the stuff that you currently have written as static.

In short:

**In favor of not using static context:**

Passing objects as parameters as much as possible decouples game elements, and allows you to modify/reuse them for the current or future projects more easily. It also allows you to manage the complexity of large amounts of code a little easier (think of having hundreds of static managers in your game class, in a big game).

**In favor of static context:**

Declaring and accessing objects from a static context makes it easier to write small games that don't require hundreds of static managers. Simplifies many methods and constructors by not requiring one or more extra parameters that are instead accessed statically.
> 4 votes

# Answer
I do not think it's a super bad idea for a simple game, but you could also have a look at http://www.nuclex.org/articles/4-architecture/6-game-components-and-game-services for a better idea on how to build intercommunicating game components
> 2 votes

# Answer
Things like TileHandler and AnimalHandler I'd put a level higher into a game screen. Does your title screen need access to the TileHandler and is it initialized when the game is first loaded? Probably not.

Check out the XNA State Management sample. It has a lot of code in there, but basically the base game just initializes a stack of game states (or screens). Each screen is fairly independent of the others and runs as a simplified version of the Game itself. Your PlayScreen could have static members so they're accessible to PlayScreen components.

In the base Game, I do use a few statics, but they're very low level things like InputHelper, Log, or Config readers. They are pretty standard across all games so the base engine can be quickly and easily ported. The screens are where the actual game logic happens. So long answer short - no, I don't think it's a bad idea in theory, just be careful what you do make static. Once you go ahead and make something static, it's a tremendous amount of work if you change your mind.
> 2 votes

# Answer
The points raised here are all good. In my experience (which admitedly is weighted more toward business apps than games), there are great uses for static classes and members and I've used them many times. I have found, that as requirements and complexity grow, I end up recycling those static classes and converting them to instance classes and start passing them around.

The point I'd like to make is that, if using a static class helps you get **this** game out, go for it, but still do the right things: implement an interface or base class so it is easier to rip it out and convert it to an instance class later on.

An ounce of prevention is worth a pound of cure, so make sure your static class doesn't tie you down in away that makes it hard to change. It is pretty easy to refactor a method using a static class that implements an interface so it accepts a new interface parameter and uses that interface instead of the static class reference.
> 0 votes

# Answer
Yes, it is generally always a bad idea.

Turning objects containing changing data (i.e. anything but read-only constants and lookup tables) into static classes is where good design takes a dive.

1. It promotes haphazard dependencies that kill modularity and get in the way of code reuse. Assume you wanted to write an editor for your game - you'd suddenly have lots of classes crying for a `Game1` that you cannot easily move into a shared library.
2. Your code becomes untestable. Unit testing works by isolating individual classes from the rest by mocking or simulating their dependencies (which should be kept as minimal as possible). Any static class is a liability because it could be accessed at any time, carry state over multiple tests or require to be initialized before the tests can succeed.
3. It hides dependencies. Much like the service provider anti-pattern (also employed by XNA, Game.Services), your classes can pick dependencies which you don't see on the outside.

This approach becomes especially poisonous if one combines static classes with freight train calls (thingsl ike `Game.Instance.ActorManager.Enemies.FindInRange(10)` \- so called because of the train car-like chained symbols), where components suddenly not only require a `Game` class, but one with a static `Instance` property that returns something with an `ActorManager` property that has an `Enemies` property that returns an object with a `FindInRange()` method.

The only excuse I would accept for writing mutable static classes would be the one is still learning and doesn't have the ability to consistently apply good design and a trained eye for spotting bad choices yet.
> 0 votes

---
Tags: xna, c#, architecture
---


# Question
Title: Make bones in blender work corectly in XNA
So, I am trying to connect bones with vertex groups in blender, but I keep failing. if I move a bone in XNA, it doesnt also move those vertecis that are connected to this bone(vertex groups). What I have done is following:

-I made a model made up of four cuboids(seperate meshes).

-then I have created vertex groups for each of the mesh and assign vertecis to those groups.

-now I have added two bones(armatures).

-I renamed some of the vertex groups to the name of the first bone(not armature): "Bone".

-for the second bone "Bone2" I have made a vertex groups in all of the meshes, this vertex group contains all of the vertecis of that mesh.(because, if not all the vertecis are connected to at least one bone, XNA throws an error)

-then I exported if to .fbx format, checking: XNA Strict Options, XNA Rotation Animation Hack.

Thank you in advance!

**EDIT:** Ok, I have fixed the boneWeightCollection problem by unchecking Apply Modifiers in export menu. In blender now everything works great, if I move the bones in their POSE mode they deform the mesh. But they do not work in xna(if I move them, they do not deform the mesh)

# Answer
> 1 votes
Well, firstly, are you sure that your bones are correctly connected to your mesh(es)? If you move the bones around in Blender, do they deform the mesh as expected?

2nd: I'm no expert in XNA, but if it doesn't manage to import skinned meshes properly (i.e. take into account bones deformations), what you can do is make your animations in Blender (using bones, with IK or whatever), then bake those deformations into the mesh using the script: select armature (in object mode), open the scripts window and run Bake Constrains script from Animation directory.

---
Tags: xna-4.0, blender, rigging
---


# Question
Title: Please help me with my 2D isometric tile picking
> **Possible Duplicate:**
> How to convert mouse coordinates to isometric indexes?

Okay, I apologise in advance if I make no sense here.

Basically, I've got a simple application that takes in a file and populates a 2D array with tile objects that contain the type of tile, their X and Y values, location of the sprite in a tile map etc. The application then renders this back to front so the depth is sorted. The camera can be dragged about.

```
for (int i = 0; i < map.length; i++){
        for(int j = 0; j < map[i].length; j++){
            m_MapTest[i][j] = new Tile(((j * Tile.TILE_W / 2) + (i * Tile.TILE_W / 2)),
                      ((i * Tile.TILE_H / 2) - (j * Tile.TILE_H / 2)),
                      map[i][j], 0, map[i][j], 0);

```

The output:

The numbers are an example of where these tiles are located in the array. Ignore the temporary art.

**How do I get the tile index of my mouse click?** I've tried about 10 different picking algorithms including matrix translations but I haven't got anywhere. The closest I got was the application picking the right tile in one direction, yet the other axis would start at negative one, the next tile would be zero, the next would be zero then the next would be one and would be correct from there, although I seem to have deleted this in frustration. I feel bad that I don't really have any code for this.

My tile width is 64 and the height is 32, although the sprites are 64x64 and the actual tiles are located at the bottom of the image, if that makes sense... I have done it like this as I am planning on having varied tile heights.

If you need any more information to help me, please let me know. Math is not my strong point.

# Answer
> 1 votes
I just recently had to solve this one to make a level builder for my isometric game.

After trying many approaches I ended up using the following:

```
x = (mouseY + mouseX * 0.5) / 32;
y = (mouseY - mouseX * 0.5) / 32;
col = round(x);
row = round(y);

```

I had to offset the mouse coords so that the 0,0 coords were at the (visual) center of the tile at index 0,0.

However, my map is drawn slightly differently (rotated 90 degrees compared to yours, with 0,0 being at the very top).

---
Tags: 2d, java, mathematics, tiles, isometric
---


# Question
Title: Implementing a hook (Like pudge in Dota)
I'm coding a new game, which involves hooking.

Ive been testing a couple of ideas now and im quite stuck.

The player can throw a "hook" which fires away in the aimed direction, until it hits something, it will bounce on some obstacles and will return to the player if hitting other obstacles. While the hook is in the air, the player can move as he/she wishes, and hook will after a certain time be pulled back to the player.

I don't know if you guys have played pudge wars, but that is the kinda hook I'm after.

What do you think is the best approach in simulating this?

Should i save points a long the way?

Edit: Yes the bounce thing is a from pudge wars. And yes the length, not time, that is true!

# Answer
> 4 votes
Here's one approach to doing it. It's unlikely this is the approach Warcraft 3/Pudge Wars would use - more on this later.

1. Look into using parametric curves like Bezier. Given an initial set of points, you can have it construct a curve for you. Bezier (as an example) allows you to easily add more points if need be.
2. Start solving the curve via it's parametric equation. Do small steps of *t*, and add a vertex on each side of the curve. Keep track of your indices as well. You may need to draw this out on paper to visualize the first time around and do a few internet searches on doing it nicely, but it's nothing to fear. After this step, you have your geometry as it follows the curve. As the geometry *bends* you may need to add more points around these bends, otherwise it will look blocky. Again, all solvable using the information that something like Bezier gives you.
3. You can now texture this thing! If you want to have a *pulling animation* of some sort, you can play around with (u, v) offsets. Picking a *good* texture with an alpha map will go a long way to making it look eye catching. For this to work, you may want to have separate texture for the body - something like meat, and ending hook-like texture.
4. When it's time for the player to be dragged, position the player on the end of the curve and start moving them back along the curve.

Your end result should look something similar to this:

I watched the video Luis Estrada posted. Warcraft 3 modding community has learned a lot of neat tricks over the years on how to coerce WC3 engine into doing what they want it to do. This results in implementation-specific effects. However, you should be able to simulate the animation of the hook in that video by using #3.

This is a fairly *standard* approach to doing these effects. Ikaruga is one example where it uses neat texture offsets with alpha to create movement of rays.

---
Tags: java
---


# Question
Title: Instantiate objects that share same variable
I'm just wondering how to instantiate the same objects that all share the same variables, except their positions.

I'm basically working on the scene of my HTML5 game, and I've build a streetlamp post that turns on and off. All the lamps will have the same variables, such as Image, Size, on/off function. The only thing that will be different will be the position x and y.

I've built my lamp within a variable function (I think they're called that `var = {`), and within my actual game `DrawFunction`, I'm calling `LampPost.draw();`.

Is it possible to do something like this?

```
LampPost(0,0);
LampPost(100, 0);
LampPost(200, 0);

```

etc ... and then possibly place each instantiate `Lamp` within an array?

This is a snippet code for the lamp:

```
var LampPost = {

    lamp_xsprite : 0,
    lamp_ysprite : 0,

    light_xsprite : 0,
    lightysprite : 0,

    x : 440,
    y : 320,

    //Flicker effects
    lightFlicker : 0,
    seconds_Off : 0,
    seconds_On : 0,

    randomLength_Off : 500,
    randomLength_On : 150,

    draw: function(x, y) {

        this.x = x;
        this.y = y;

        ctxPropsOver.setTransform(1, 0, 0, 1, -Map.x + gameWidth/2, -Map.y + gameHeight/2);
        ctxPropsOver.rotate(Math.PI / -25);
        ctxPropsOver.clearRect(0, 0, 1000, 1000);

        ctxPropsOver.globalAlpha = this.lightFlicker;
        ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, -60 + this.x, -190 + this.y, 500, 463);
        ctxPropsOver.globalAlpha = 1;
        ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0 + this.x, 0 + this.y, 210, 36);

```

----- UPDATE -----

Okay, So I've converted it into an instance of object, this is what I have so far:

```
LampPost = function(lx, ly, la){

    x = lx; //500;
    y = ly; //335;

    centrex = 12;
    centrey = 17;

    rotate = la; //-8;

}

LampPost.prototype.draw = function (){

    ctxPropsOver.setTransform(1, 0, 0, 1, (-Map.x + gameWidth/2), (-Map.y + gameHeight/2) );

    ctxPropsOver.clearRect(0, 0, 1000, 1000);

    ctxPropsOver.save();
        ctxPropsOver.translate(this.x, this.y);
        ctxPropsOver.rotate(this.rotate*Math.PI/180);
        ctxPropsOver.translate(-this.centrex, -this.centrey);
        ctxPropsOver.globalAlpha = this.lightFlicker;
        ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, -60, -190, 500, 463);
        ctxPropsOver.globalAlpha = 1;
        ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0, 0, 210, 36);
    ctxPropsOver.restore();
};

```

# Answer
aha I see in your posted code that you created LampPost as a literal object, and not as an object to instantiate. So you'll do something like:

```
LampPost = function(x,y) {
  this.x = x;
  this.y = y;
  blah blah
}

LampPost.prototype.draw = function() {
  ctxPropsOver.translate(this.x, this.y);
  blah blah
}

var post = new LampPost(100, 0);
post.draw();

```

I suggest looking up JavaScript OOP, possibly by doing lessons on CodeAcademy
> 3 votes

# Answer
You can use Object.create instead of new to explicitly set the object's prototype. This lets you easily implement the flyweight pattern. You can also set the prototype property of the constructor, though that's less flexible.

A more general for all languages solution is to split your objects between data and instance info. Eg your Lamppost instance just has a member referencing some LamppostData instance.
> 2 votes

# Answer
Create a template object with all shared functions and member data. Then, use a create function to manufacture instances.

In the example below, you can provide arbitrary properties to be specified uniquely per instance, either overriding template parameters or adding new parameters unique to an instance.

Template for LampPost objects. Create instances with LampPostTemplate.create().

```
LampPostTemplate = {
  create:function(instanceVariableDictionary) {
    var result = createInstance(this, instanceVariableDictionary);
    //... any initialization code needed for LampPost instances.
    result.flickerAnimationTimeOffset = Math.random();
    return result;
  },
  draw:function() { /* ... */ },

  center:{x:.5, y:.5},
  position:{x:0, y:0},
  name:"Unnamed",
  flickerAnimation: [1,1,1,1,1,0,1,1,0,1,1,1,0],
  flickerAnimationTimeOffset: 0
};

```

Create instances:

```
Lamp1 = LampPostTemplate.create({ position:{x:1, y:2} });
Lamp2 = LampPostTemplate.create({
  position:{x:11, y:22},
  flickerAnimation:[1,0,0,0,0,1,0,0],
  name:"Hill top2"});

```

Here is the helper function to create copies of a template object and then copy arbitrary properties based on an input dictionary.

```
function createInstance(templateObject, instanceVariableDictionary) {
  var result = Object.create(templateObject);
  for (var property in instanceVariableDictionary) {
    if (typeof instanceVariableDictionary[property]['slice'] === 'function') {
      // Copy an array
      result[property] = instanceVariableDictionary[property].slice();
    } else if (typeof instanceVariableDictionary[property] === 'object') {
      // Copy an object
      result[property] = Object.create(instanceVariableDictionary[property]);
    } else {
      // Copy numbers, strings, ...
      result[property] = instanceVariableDictionary[property];
    }
  }
  return result;
};

```
> 1 votes

---
Tags: javascript, html5
---


title: Tangent plane for point on surface mesh

text:
# Question
Title: Tangent plane for point on surface mesh
I am working on the generation of hexahedral mesh , for surface construction i need to find the tangent plane for each point on the surface.

# Answer
> 2 votes
If you use OpenGL, you will have to split your hexahedrons into triangles. Each point lies inside a triangle, so find the tangent plane for that triangle.

# Answer
> 0 votes
(continued from Ivan's answer)

What format do you want the tangent plane in? A combination of (point, normal) already is a unique representation of a tangent plane. For example, if I have a triangle at points A, B, C; I can find the normal via the cross product `N = (A-B)x(A-C)`.

Since (A, N) uniquely defines the plane, I could write it out as the equation

```
Nx(x - Ax) + Ny(y - Ay) + Nz(z - Az) = 0

```

---
Tags: opengl
---


# Question
Title: Online card games: game loop or event based?
The only games I've made have been the game loop variety. I'm just starting to think about building an online poker game where people could meet up in a lobby, etc. Cards seem event based... is the game loop strategy viable here? Or is it just a waste of time to keep running while waiting for someone to make a move?

# Answer
Strictly separate your game engine from the rest of the project, such as GUI, net code, etc. The game engine itself should be event-based, let the OS provide the "game loop" in form of its regular event handling. Make all game events that are relevant to the outside accessible through events to which the GUI and all other parts can subscribe. Then you are free to implement your GUI whichever way you want.
> 3 votes

---
Tags: game-loop, turn-based, card-game
---


# Question
Title: Which image format is more memory-efficient: PNG, JPEG, or GIF?
Which image format is more efficient to save memory? PNG, JPEG, or GIF?

# Answer
"Memory" and "efficiency" are commonly misused terms, so I'll give you an answer for four different elements that may affect the performance of your game.

I will be oversimplifying way too many things to keep it short and concise, but there are tons of inaccuracies in this text below, so take it with a pinch of salt. However, the main concepts should be understandable.

**Storage**

This is the size your images consume on your software distribution. The more space your resources consume, the longer the *download* (as in from your website) will be. If you're distributing on physical media, such as CDs or DVDs, you're probably going to have to do some serious optimizations in this front.

In general, JPEG compresses the best for photographs and images with no sharp borders. However, your images will have degraded quality because JPEG uses lossy compression (you can fine tune the compression level/degradation when exporting images as JPEG. Refer to your imaging software's documentation for more information on this).

However, as good as JPEG may be, it doesn't support *transparency*. This is crucial if you want to have images that show through others, or if you want images with irregular shapes. GIF is a good choice, but it has been largely superseded by PNG (there's only a few things GIF supports that PNG doesn't, but they're largely irrelevant in game programming).

PNG supports transparency (and semitransparency), compresses data without degradation in quality (i.e. it uses lossless compression), and compresses fairly well, but not as much as JPG.

The problem arises when you need good compression, as well as transparency. If you don't mind slightly degraded images, you can use PNG quantization programs such as pngquant, which you can test online at TinyPNG. Keep in mind that the image degradation performed by quantization on its own is different than that of JPEG (which includes quantization as well as other aggressive techniques), so be sure to try both, with a wide variety of settings.

If you want to aggressively minimize your distribution size, you could manually process every image like this:

```
if the image has transparency then
    try pngquant on the image
    if the results are not satisfactory then
        revert to the non-quantized image
    end
    store as PNG
else
    try storing it as JPG with different quality settings
    if no single setting yields an image of an acceptable quality then
        try pngquant on the image
        if the results are not satisfactory then
            revert to the non-quantized image
        end
        store as PNG
    else
        store as JPG
    end
end

```

Tip: it is okay to store some images in one format, and others in another format.

There are other specialized formats such as DXT, ETC and PVRTC. They support compression, and can also be loaded compressed into memory, but they are only supported by specific GPUs, and most of these GPUs only support one of them, so unless you know the exact hardware specifications of your target hardware (a notable case is the iPhone/iPad, which supports PVRTC textures), you should avoid these formats.

**Program Memory**

I included it here, because this is what's commonly known by "memory". However, if your game uses graphics acceleration (and if you're making a game after 1998, you most likely are), then the only thing that will consume memory are your texture descriptors (just a few bytes per image), which is only effected by the *amount* of images, and not their size or format (this has a few caveats, but are mostly irrelevant).

If your platform does not have dedicated video memory, is not hardware accelerated, or other uncommon cases, then the next section regarding VRAM will happen completely or partially in RAM, but the main principles will be the same.

**Video Memory**

This is where your images will be stored once your program is running. In general, the format in which you stored them will make no difference here, as all images are decompressed before loading them into video memory.

Now, the VRAM consumed by your images will roughly be `width * height * bitdepth` *for each* image loaded in VRAM. There are a couple of things to notice here:

1. The width and height in which your images are stored in VRAM will not necessarily match the ones of your original image. Some GPUs can only handle textures with sizes in powers of 2, so your 320x240 image may actually be stored in a 512x256 space in VRAM, with the unused memory effectively wasted. Some times you're not even allowed to load textures with sizes that are not powers of 2 (like in GLES 1.1).

So if you want to minimize VRAM usage, you may want to considering atlasing your images, and sizing them with powers of 2, which will also have the advantage of fewer render state changes when rendering. More on this later.
2. The bitdepth is very important. Usually textures are loaded into VRAM in 32-bit ARGB or 32-bit XRGB, but if your hardware can support 16-bit depths, and you don't mind having a lower bitdepth, you can half the amount of VRAM consumed by each image, which may be something interesting to consider.
3. But no matter what you do, the most important factor when considering the amount of VRAM your game uses, is the *amount of images* you have in VRAM at a given time. This is the number you most likely want to keep as low as possible if you want a good performing game. Loading and unloading textures into VRAM is expensive, so you can't just load each image whenever you're going to use it. You must find a balance between preloading the images you will most likely use, and unload them when you're sure you're not going to use them anymore. Doing this right is not trivial, and you have to think of your own strategy for your particular game.

**Execution speed**

Even though not "memory", it is very related with performance in games. Drawing images is expensive, and you want to make sure your rendering runs as fast as possible. Of course, in here, format doesn't matter, but other things do:

1. Image size (actually, it would be "sampling size"): the biggest the region of an image you're going to draw, the more time it will take to draw it. Rendering a huge image in a small section of the screen is not very effective, so there is a technique called mipmapping, which consists of trading VRAM for rendering speed, by storing your images several times at several resolutions and using the smallest one that can give you the required quality at any given time. Mipmapping can be performed when the images are loaded, which will impact loading speed and VRAM usage, or at preprocessing (by manually storing different versions of the same image, or using a format that natively supports mipmapping such as DDS), which will impact storage and VRAM usage, but will have little impact on loading speed.
2. Render state changes. You will most likely want to draw several different images on the screen at the same time. However, the GPU can only use a single source image at any given time (this is not true, but please bear with me here). The currently used image for rendering is one of many *render states*, and it is expensive. So if you're going to use the same image several times (remember when I mentioned texture atlases?), you will notice a huge performance gain if you reuse an image as much as you can before you change the render state and start using a different image (there are other render states apart from this, and fine tuning the order in which you draw your stuff to minimize render state changes is a very common activity when enhancing the performance of a game)

**However**, image usage optimization is a very complex topic, and what I wrote here is a very broad and oversimplified overview of some of the factors you will have to consider when writing a game, so I think it's definitely best if you keep it simple, and only optimize whenever you really need to do so. Most of the times, prematurely optimizing is unnecessary (and sometimes even detrimental), so take it easy.
> 158 votes

# Answer
Once an image is loaded off the disk and is formatted for rendering, it will use the same amount of memory regardless of whether that image was saved to disk using PNG, JPEG, or GIF.

General rule of thumb: JPEG is a lossy format, and will degrade image quality in order to make the image smaller on disk. PNG, on the other hand, is a lossless image format, and so will typically result in larger file sizes on disk. GIF is also technically a lossless format, but only supports a maximum of 256 colors per image, and so a high-color image will often incur a heavy quality loss if saved as a GIF.

That's only for their on-disk representation, though. In memory, they'll both expand into the same texture format, using the same amount of memory, regardless of whether you saved them to disk as PNG, or as JPEG, or as GIF.
> 30 votes

# Answer
It depends.

Jpeg is most efficient for photographs. It isn't lossless, but the artifacts introduced by the compression are least visible in this use-case.

PNG is lossless and most efficient for pixel-art with sharp lines and few colors. It also supports alpha-transparency.

GIF can't do anything PNG can't do better, except for its ability to store animations. But this is only relevant in the context of web applications. In game development you usually create animations by using a spritesheet.

Note that when you use a graphic engine like Libgdx it will most likely uncompress the images just after loading them and then keep them in memory as uncompressed RGBA values. So the image format only matters for loading speed and had drive space (or bandwidth usage when you send them over the net).
> 3 votes

# Answer
I don't know much about libgdx, but about image formats and graphics:

JPEG is very good in cases of real world photos. They are lossy but you won't see artifacts on photos unless you take pictures of sharp edges with plain coloured spaces, like for example written text or comics. Use them for large background graphics.

GIF is obsolete, it can only store paletted colors (up to 8 bit per pixel) with one dedicated color for complete transparency. It allows small animations based on frames. Once there was a patent on its packing algorithm so that it could not be used everywhere legally. Because of that patent, PNG was developed.

PNG is more or less a zipped bitmap that can store RGB+alpha (up to 32bit) and other pixel formats. It is specialized for speed-unzipping of small parts of that picture, which is convenient for very small and slow devices (like a 10 year old cellphone), but todays libraries just unpack them to bitmaps when loaded.

PNG is better than GIF in size and speed and features, but if you want to store bitmaps efficiently, I'd suggest: .PNM.BZ2 (\[edit\]Because of the different packing method, .PNM.BZ2 is not always more efficient than .PNG.\[/edit\])

PNM/PBM/PGM/PAM are plain bitmap formats with K.I.S.S.-headers in plain text. Using gzip on those will result in a file size similar to PNG, so bzip2 is the better solution for that. If you are going to use bitmaps internally in your program, you might want to use bzip2 compressed bitmaps in a .tar or .zip container. If you don't have bzip2, using PNMs in a zip container (zip with maximum compression) might be similar to using PNGs. – So, storing PNGs in a ZIP file might have only small or no benefit – it would most likely just increase the time to load the image.

Besides that, it is a good choice to store several small sprites/pictures in one bitmap, especially when you need them all in the same situation together.
> 2 votes

# Answer
As storage format JPEG is probably the best choice for some textures like grass or walls, where the loss of information is probably undetectable. Followed by PNG when you need transparency or when you cannot pay with loss of information, for example sprites in a 2D game (the player, enemies, a treasury chest), you probably want to use PNG for that images.

When talking about memory cost, the format used to store game graphics in the file system is not relevant at all. Either if you store pixel buffers in VRAM, or RAM (software renderer), you probably have them stored uncompressed, because games favor fast read of pixels vs memory used by each pixel buffer.

Have compressed data stored in memory have no sense except you maintain some kind of cache to save disk reads, but you probably have to read from that cache to an uncompressed state for the images in use at a given time in your game.

Compressed image data have a bit more sense if fast hardware decoding were possible. For normal mapping at least, I remember this http://en.wikipedia.org/wiki/3Dc. With that you can save some VRAM. I'm not aware of other examples of hardware decoding yet.

In resume: whatever the formats used for your game to store graphics in persistent storage, you will have to decode that and maintain an uncompressed version in dynamic memory, video memory, or both, to be able to fast render them when needed.

Finally: I'm a desktop guy. When I say "memory" I always referring to dynamic memory. When I say "disk", "file system" or "persistent storage" I always referring to whatever your device use as persistent storage, usually I think in hard disks. When you said "memory-efficiency" I took it for "dynamic memory" not "persistent storage". Lately, I see a lot of people using the word "memory" to refer to "persistent storage" (maybe that the terminology of mobile devices?).
> 1 votes

---
Tags: graphics, graphics-programming, image, memory-efficiency
---


# Question
Title: Collision Detection Slows Screen Drawing
I have recently been pursuing game development as a hobby, and decided that in order to learn the in's and out's of game development, that I should create a game and render everything myself (without the use of a game engine). This has proven rather complicated, however I am making great progress. I did, however, run in to an issue that I think might be related to the way Android phones render their graphics and will need some clarification on this issue.

## The Problem

My game contains a series of balls in a cannon; when the user presses the screen, the cannon launches the balls and the engine (that I am implementing) handles the updates to the location information and collision detection from there. Now, before I had implemented collision detection my game ran very smoothly and responsively, however when I told the engine to only draw the bead if it is within the bounds, and "bounce" it off the wall otherwise, it would seem that the engine loop now takes a significantly longer amount of time to run.

This would be fine, if it were not for the latency it is providing to the user experience. For example, when the screen is touched *now*, it takes ~2 seconds for the ball to be displayed as moving around the screen, and sometimes **it does not appear at all**. Previously, the reaction was instantaneous.

Further, when I comment out the collision detection portion of my physics engine, it resumes its usual responsive behavior.

## What I Think Is Causing This Behavior

*Note: I have recanted this assumption (see 'Debugging Information' below)*

I think that since I do not have a frame limiter implemented for my game, and that it is rendering as fast as the hardware will allow it, that it is drawing so many old frames (in some buffer, maybe?) to the screen that it is busy drawing while it should be updating physics. Although my debugging thus far has not indicated that this is the case, I cannot seem to reach any other conclusion.

## Some Code

Note that this code is going to be rather confusing to understand not knowing what everything does. I simply included it in case anyone was particular about having some code to work with. The variables are clarified below the excerpt.

*PhysicsEngine.updateBeadPositions(float)*:

```
private void updateBeadPositions(float delta){

    //Update all of the beads currently on the board.
    beads = control.getBoard().getValues();

    temp_x = 0.0f;
    temp_y = 0.0f;

    //For each row...
    for(Bead[] row : beads){

        //For each bead...
        for(Bead bead : row){

            //If this bead exists...
            if(bead != null){

                temp_y = (float) (bead.getYCoordinate() * bead.getYVelocity() * delta);

                //If the coordinates are within the bounds of the game
                if(outwithVerticalBounds(temp_y, control.getBoard())){

                    //Set the X coordinate equal to the distance * the time differential (delta).
                    bead.setXCoordinate(temp_x);

                    //Set the X coordinate equal to the distance * the time differential (delta).
                    bead.setYCoordinate(temp_y);
                }
            }
        }
    }

    //If the cannon Bead has been set...
    if(control.getCannon().getReleased() != null){

        //Update the cannon bead
        if(control.getCannon().getReleased().getXVelocity() == PhysicsEngine.VELOCITY_STATIC && control.getCannon().getReleased().getYVelocity() == PhysicsEngine.VELOCITY_STATIC){

            control.getCannon().getReleased().setXCoordinate(control.getCannon().getX());
            control.getCannon().getReleased().setYCoordinate(control.getCannon().getY() - Cannon.PIVOT_Y_OFFSET);
        }
        else{

            temp_x = control.getCannon().getReleased().getXCoordinate() + (control.getCannon().getReleased().getXVelocity() * delta);
            temp_y = control.getCannon().getReleased().getYCoordinate() + (control.getCannon().getReleased().getYVelocity() * delta);

            //TODO: Commented out collision checkers!

            //If the horizontal coordinates are within the bounds of the game
            if(!outwithHorizontalBounds(temp_x, control.getBoard())){

                //If the vertical coordinates are within the bounds of game
                if(!outwithVerticalBounds(temp_y, control.getBoard())){

                    //Set the X coordinate equal to the distance * the time differential (delta).
                    control.getCannon().getReleased().setXCoordinate(temp_x);

                    //Set the X coordinate equal to the distance * the time differential (delta).
                    control.getCannon().getReleased().setYCoordinate(temp_y);
                }
                //Otherwise...
                else{

                    //Bounds off the wall in the y direction
                    control.getCannon().getReleased().setYVelocity(-1.0f * control.getCannon().getReleased().getYVelocity());
                }
            }
            //Otherwise...
            else{

                //Bounce off the wall in the x direction (flip the x velocity)
                control.getCannon().getReleased().setXVelocity(-1.0f * control.getCannon().getReleased().getXVelocity());
            }
        }
    }
}

```

Here, the variables are defined as:

* `control` is a reference to my game controller. It packages the majority of the game code.
* `beads` is a reference to the 2D array that contains the beads on the board currently (excluding the one that is moving)
* `delta` is the time differential between previous calls to the physics engine, and the current call

See the comments within the code for any other explanations.

*PhysicsEngine.outwithHorizontalBounds(float, Board)*:

```
private boolean outwithHorizontalBounds(float x, Board board){

    //If the horizontal values are within the bounds...
    if(x > (board.getRight() - bead_radius)){

        return true;
    }

    if(x < (board.getLeft() + bead_radius)){

        return true;
    }

    //Otherwise, it is not.
    return false;
}

```

The method `outwithVerticalBounds(float, Board)` is of equivalent functionality, but in the y-direction.

---

## My Question

What about collision detection would cause screen rendering to be inhibited so drastically? I know it is a very intensive operation, but my debugging has shown that the physics updates are completing at the same times as the draws.

## Debugging Information

*Last Updated: 29 Jan 2013 4:27PM EST*

Here is an aggregation of the debugging information that I have obtained thus far. I will update this as time progresses:

* The `update()` method within my engine, takes, on average, only `.018 ms` to execute. Usually, the delay jumps up to `0.020 ms`, when I tap the screen to release the bead.
* After comparing the times of the draws and the game updates, it would appear that I was correct: **they are occurring simultaneously**. Thus, this could not be the issue, right?
* The `FPS` of the game is roughly `87`, it spikes randomly to (at the low end) `60 FPS`, however this spike is **not** related to the releasing of the bead. There are no `FPS` drawbacks to doing this. This makes sense since the only part that increases its complexity after the bead is released is the `update()` call, drawing still happens as fast as possible.
* After further testing, it has become apparent that this is **not** the case that the screen is lagging behind the physics. I tested this with a simple boolean flag wherein the screen background would become white when i touched it, and **this happens immediately**. Thus, there must be some other cause for the bead not drawing. I will update soon.

## Supplemental Information

Here is some supplemental information that should help you understand my circumstances:

* I am testing this on a Google Nexus 7.
* There are quite a few beads on the map that are being updated at once (about 30), but only one of them is moving.
* Usually, after the bead starts moving (after the initial delay and **if** it actually draws), is continues to move in a very smooth manner.
* It is important to note that I have other UI elements on the screen that update in reaction to the touch event. For instance, the bead loaded in the cannon becomes a new bead when the screen is touched (signifying that it has been released), but the mobile bead is simply not drawn.

# Answer
> 8 votes
Frankly, I am rather embarrassed to announce the solution to my problem as I spent many hours in search of it, and it was so simple and could have been avoided so easily with a little less negligence on my behalf. On the bright side, I did end up finding a few other pieces of code that I can now optimize for even better performance!

## The Solution

The cannon that was launching the bead was below the lower boundary of my playable area.

This was misleading because the lower boundary of my playing area is a little bit above the bottom of the actual screen of the phone. So, basically, the physics engine was bouncing it back and fourth ever so slightly (invisible to human inspection) for about 5 seconds before it was rendered on screen.

I moved the cannon 50 pixels higher and it works as intended now.

---

Thank you all for you help! I wouldn't have got here without your thoughtful suggestions.

---
Tags: android
---


# Question
Title: How to create plasma trail for spaceship
I have seen a lot of great looking space games that all use similar effects. I am really interested in finding out how some of these effects are generally done.

In particular I want to know how some of the trails behind spaceships or missiles are accomplished without using all the available resources.

For examples of the effect I mean see the screenshots for Gimbal, and even the video at that same link. Also the missile trails in Ether Vapor.

Are these both the same techniques? I am mainly interested in 2D, but I can't imagine it would be too different.

So how would I go about creating this kind of effect? Are we talking pixel-shaders, blendmodes/filters, bitmap effects, particle systems, or what? Not really platform specific. I am just looking for the theory, but specific examples or links would be great. And more detail the better.

# Answer
> 7 votes
> So how would I go about creating this kind of effect? Are we talking pixel-shaders, blendmodes/filters, bitmap effects, particle systems, or what? Not really platform specific. I am just looking for the theory, but specific examples or links would be great. And more detail the better.

All of the above.

Unless you poke through their source code you may not know *precisely* how they did it.

However, from the looks of the two games, both of them have what *appears* to be geometry that is connected and trails the ship. May not necessarily be a basic point-sprite particle system, but it's not all that difficult either.

Some games will use a curved line algorithm and generate a list of vertices from that and do a bit of texturing with different textures applied at the two endpoints of the trail, so that at one point the exhaust looks hot and at the other it's cooler and trails off into space.

A player's ship is an interesting case because the movements are unpredictable, and you may either need to update the control points of your curve algorithm, or end up sampling the latest ship position and generate vertex positions based off of that.

Take a look at this answer from an earlier question if you want to have something that works off of control points. For your needs though, sampling the players position would probably work a lot better and be easier understood.

Here's something to get you thinking:

Start sampling the player position. These points will form the *body segments* of your trail, from which the geometry can be constructed. It's a good idea to keep a separate *tail segment* that has a separate texture. You may want to detect when a player is turning and increase the frequency of these segments, otherwise you'll end up with blocky curves. Unless that's the effect you're going for :)

At certain events, the segments need to stop generating and the existing ones should start slowly scaling down, starting from the body segment closest to the tail (but not the tail itself). This is in case of the player slowing down. But, if the speed at which the segments are scaled down matches the player's ship speed, then a new segment will be formed just in time as one is taken out. So this also works well for a ship that's in full motion. The length of the trail will always be the same - which gives a fluid, consistent stream.

The *head segment* should always be at the player's current position. If any turns are detected, the existing head segment is added to a body segment, and a new head segment is started. Repeat. Depending on your textures, each segment may have a maximum length as well.

This gives us an easy way to model this effect: working off of the idea that the effect will always be diminishing/shrinking by itself unless more segments are supplied, and playing around with speeds to keep it from shrinking.

# Answer
> 4 votes
There are lots of different possibilities to create such trails. You can use simple lines, polygons, point clouds, etc.

They all are usually based on one of two concepts:

* Track the previous positions and use these to draw the tail.
* Track the velocity/direction and adjust the tail based on that.

The first one is better suited for things such as missiles, while the second approach is better for some kind of attached things following something (like the tail of a dragon).

A simple implementation for engine tails isn't that complicated. You'll only need some buffer to store previous positions. I don't know which language you're using, but for this I'd either use a ring buffer or some kind of similar buffer (quick deletions and insertions on the ends).

Every x-th frame/update tick (you don't have to do it hundred times per second), you essentially drop the oldest/last element in your buffer and add the current position to its front (only if the buffer is filled; make sure it always contains n elements, where n determines the length of your tail).

Then, during drawing you just start at your current position and draw a set of lines through all points in your buffer, while lowering your opacity with every further vertex.

This way you should end up with a nice and clean tail. Based on your platform, you could extend this, e.g. using shaders or by wrapping some nice tail graphic along that path.

---
Tags: special-effects
---


# Question
Title: Is the city of the GTA, L.A. Noire, Assasins Creed or Saint Row games considered a level?
I'm trying to figure out whether or not the worlds in which these games take place are levels or not, for the sake of level design. I consider the world to be one big level and all the missions and such being levels as well. While most levels in other games have specific goals, there are pretty much no objectives tied to the "mega-levels" of these games.

I just wanted to get some opinions.

# Answer
There are many terms for "level" nowadays, depending on the genre of the game and also the preference of its designer(s).

*Level* typically means a secluded, in itself complete portion of the game, mostly independent of the rest; when I hear *level*, I think of 2D platformers exclusively.

For the first or third person shooter genre, levels are more typically referred to as *maps*. Maps are still technically secluded from the rest of the game - maps typically have a clear objective and transition between them is not seamless and requires significant time to load the next map. This implies greater freedom of movement and ability to backtrack at will, which is often significantly greater than in side-scrolling games.

For the sandbox shooter sub-genre, there is only one map, so it is more accurately referred to as *world*, as you already wrote, which implies the greatest possible freedom of movement.

As always, there are games that mix up the designs - for example, Wolfenstein (2009) had secluded, stand-alone maps with defined objectives, but they were connected by a "hub" map.

That being said, you could name the designer level, map, and world designer, respectively, but there is no standard set in stone - if someone said "I am a level designer for GTA", it would be understood.
> 11 votes

# Answer
This type of thing has a few names but "Hub & Spoke" is generally used. The best example of Hub & Spoke design is Mario 64. The Castle acts as the Hub which is essentially an interactive menu which defines the world. Each sub-section is the spoke.

The best way to think about this type of approach is to consider that Hub is essentially a menu that lets you select levels / missions in non-linear design.

In games like Elite Plus, this is literally a menu with star systems and you interact with a cursor. Over the years these have become more and more complex. The Commander Keen games are a good example.

The other term which is used to describe this approach is "Sand Box". A Sand Box is literally an environment for the player to enact mechanics - i.e. "do stuff".
> 3 votes

# Answer
I don't know, how it's in named games, but in Mafia 2:

Whole world is just a world. And missions are levels. Each mission can contain few "sublevels" (go from here to there and do some action) and special parts like buildings, items, characters, behavior, etc.

World is streamed as it is needed.

I think that level should represent one part of game (story), which can be "entered" (started) and completed.

And because you can travel freely around the game world, it's not a level, but environment. Level should be one mission.
> 0 votes

# Answer
At the most basic level they use what is refereed to as a 'chunk' or 'world chunk'. Chunks can also be called 'levels', 'maps', 'stages', or 'areas' but the reverse is not always true.

In a game like GTA/Noire/Saints the entire city will be made up of several chunks that will load as you traverse the city (maybe there is a graph layout and you get a chunk per suburb, or maybe it's just some kind of grid layout). In that kind of game the term 'level' doesn't make any sense.

In AC you will get something similar, however it also has missions that are completely separate from the main game world (at least in AC3), those missions could be considered to be a level but I probably wouldn't refer to the whole of a city as being it's own level (unless it's self contained, the AC series changes from game to game quite a bit, the original might not have had the open game world that the later ones had in which case each city might be considered to be a level).

I would consider levels to be self contained discrete chunks and generally provide a one directional linear progression through the game world (although there are exceptions, for example hidden levels).
> 0 votes

---
Tags: game-design, level-design, levels
---