title: Dividing up spritesheet in Javascript

text:
# Question
Title: Dividing up spritesheet in Javascript
I would like to implement an object for my spritesheets in Javascript.

I'm very new to this language and game-developement so I dont really know how to do it.

My guess is I set spritesize to 16, use that to divide as many times as it fits on the spritesheet and store this value as "spritesheet". Then a `for(i=0;i<spritesheet.length;i++)` loop running saving the number of sprites.

Then `tile = new Image();` and `tile.src = spritesheet[i]` to store the individual sprites based on their coordinates on the spritesheet.

My problem is how could I loop trough the spritesheet and make an array of that? The result should be similar to:

```
sprite.sprites = Array(
"0",
"1"
);

```

If possible this would be done with one single object that i only access once, and the tile array would be stored for later reference.

I couldn't find anything similar searching for "javascript spritesheet".

**Edit 2:** I've come a long bit since I first posted this question and this is what I've come up with so far:

```
function Sprite(){
    this.size = 16;
    this.spritesheet = new Image();
    this.spritesheet.src = 'spritesheet.png';
    this.spriteCount = this.spritesheet.height / this.spritesheet.width;
    this.spriteIndex = 0;
    var sprites = new Array();

    for(i=0;i<this.spriteCount;i++){
    sprites.push(this.spriteIndex); // Could insert pretty much whatever I want
    this.spriteIndex++;
    alert('spriteIndex # ' + sprites[i] + ' pushed');
    }
}
var sprite = new Sprite();

```

The alert method is only for testing, it alerts from 0 and up giving me usable X and Y values for the drawing (when multiplyed by size). If anyone has improvements please let me know.

**Edit 3:** I still have some trouble with the array. How would i access the index of it? For example the first sprite should give me sprite.sprites\[0\] second sprite sprite.sprites\[1\].

# Answer
> 1 votes
When I first posted this question I didn't know `drawImage();` had an imageposition function. After playing around with it I came up with a solution that only needs the sprite size. The simplicity is beautiful, and I feel retarded for not thinking of it before.

Since I'm using numbers ranging from 0 and up in my map i just take that number, multiply it by spritesize and voila, spritesheets Y position on the fly.

I'll post the code in case someone needs this in the future:

```
// First I load the Image
sprite = new Image();
sprite.src = 'img/spritesheet.png';
// Define sprite size
spriteSize = 16;
// Draw on map, tileIndex is the number i store in the map array
ctx.drawImage(sprite, 0, tileIndex * spriteSize, spriteSize, spriteSize, tileX, tileY, spriteSize, spriteSize);
// And the map looks like this but bigger
var map = Array([0,0,0,1,1],[1,1,0,1,0]);

```

This can absolutely be improved but for my current project it is perfect.

# Answer
> 5 votes
This is a little different than your object-based approach, but here is the code I'm using to preload tiles from a spritesheet into canvas elements:

```
  tileSize = 16;
  sprites1x1Image = new Image();
  sprites1x1Image.src = 'images/sprites-1x1.png';
  sprites1x1Image.onload = function() {

  sprites1x1 = [];
  var names1x1 = [
  'character1', 'character2', 'obstacle1', 'obstacle2'
  ];
  for (var i=0, iLimit=names1x1.length; i<iLimit; i++) {
   sprites1x1[names1x1[i]+'Canvas'] = document.createElement('canvas');
   sprites1x1[names1x1[i]+'Canvas'].width = tileSize;
   sprites1x1[names1x1[i]+'Canvas'].height = tileSize;
   sprites1x1[names1x1[i]+'Context'] = sprites1x1[names1x1[i]+'Canvas'].getContext('2d');
   sprites1x1[names1x1[i]+'Context'].drawImage(sprites1x1Image, 0, tileSize*i, tileSize, tileSize, 0, 0, tileSize, tileSize);
  }

```

Then I can draw sprites onto a canvas like so:

```
  context.drawImage(sprites1x1['character1Canvas'], x, y);

```

# Answer
> 1 votes
As far as I understand your intentions you can't do what you are looking to do, an `img` element doesn't take offset coordinates.

There are many tricks in the book for spritesheets, the simplest is to use set the background of a `div` element as that can be offset using the `background-position` CSS property, like so: `background-position:-32px -16px;`. And yes, the values have to be negative for the spritesheet trick. You should be able to shorthand it all into the CSS attribute `background` like so: `-32px -16px url("images/sprites-1x1.png")`

# Answer
> 0 votes
you can use spritely, it does all the job for you... Only that you need is a image with your drawings with the same size, and it does cuts of the objects for you. Spritely it's a Jquery based plugin and have a lot of options... http://www.spritely.net/download/

---
Tags: javascript, html5, spritesheet
---


# Question
Title: Efficient solution for multiplayer space partioning?
This question is a little tricky, but I will try to make it clear.

Lets say I am building an online game (not MMO-scale), but that supports as many players as possible, in a authoritative server approach. I want really **big** worlds with **lots** of AI simulated enemies.

I am aware of a few strategies to save server CPU by subdividing the space and not processing what doesn't need processing. I have already split the world by regions, that will require loading times and small transitions, which I think is important to maintain the quality of gameplay when playing locally (alone or even with a couple of friends). I don't expect the players to be in more than one or two regions.

The problem is that a region can become pretty big, and have a lot of NPCs simulating at once. How do I handle this without affecting the players' experience? Approaches like one server per region and alike are not in the table.

I am mainly looking for data structures to hold hordes of enemies, and even peaceful NPCs. To finalize the question, please note that vehicles exist, therefore its considerably fast to travel within a region, influencing the "when" to cull areas.

# Answer
> 5 votes
From what I understand you will have some sort of physics running on your server.

If that's the case there are also other techniques available for AI/physics other than space partitioning. From most to less obvious:

* priority: NPCs with no direct interaction with players can receive less CPU time by lowering their refresh rate. You can use priority queues and run queues with the higher priority from first to last, while other queues will run only 1/2, 1/4 or 1/8 of the queue each cycle. this way you ensure each object runs at some point but you reduce the number of times it consumes CPU.
* physics can also be lowered (only the collision boxes and spheres can be used while roaming and away from sight).
* simplifying AI/simulation by allocating very basic behaviors to NPCs and environment while players are far away. Usually it will be roaming or scanning for enemies instead of hunting, gathering, farming...
* some physics and AI can also be delegated to the clients. If you really lack CPU on the servers you can tag object as being partially resolved and the clients will adjust the physics and position of those objects locally (to avoid floating NPCs). The clients can be given some responsibility in running AI (during combat against a player the targeted player's device can be directly running the attacking NPCs)
* for players, physics can also be lowered on the server and clients will receive more responsibility in collision resolution. Ex: you hit an object with your vehicle, the server will only solve the collision on the collision boxes and tag the objects as potentially in collision. The client will send the resolution to the server with a timestamp which will accept it if the objects are tagged and the solution seems right.

Once you have implemented these mechanisms you can decide how much and how often you need them. The great thing about this is that later you can add a few servers which will be able to take over some of the tasks instead of the client apps.

Of course the approximated collision detection will create some aberrations, but you will be able to solve them by adding more precision from time to time.

Also concerning physics you should have a look at libs which support some sort of GPGPU system like OpenCL or CUDA if you have access to a server which supports either.

---
Tags: multiplayer, performance, data, architecture, space-partitioning
---


# Question
Title: Giving a Bomberman AI intelligent bomb placement
I'm trying to implement an AI algorithm for Bomberman. Currently I have a working but not very smart rudimentary implementation (the current AI is overzealous in placing bombs).

This is the first AI I've ever tried implementing and I'm a bit stuck. The more sophisticated algorithms I have in mind (the ones that I expect to make better decisions) are too convoluted to be good solutions.

What general tips do you have for implementing a Bomberman AI? Are there radically different approaches for making the bot either more defensive or offensive?

---

**Edit:** *Current algorithm*

My current algorithm goes something like this (pseudo-code):

1) Try to place a bomb and then find a cell that is safe from all the bombs, including the one that you just placed. To find that cell, iterate over the four directions; if you can find any safe divergent cell and reach it in time (eg. if the direction is up or down, look for a cell that is found to the left or right of this path), then it's safe to place a bomb and move in that direction.

2) If you can't find and safe divergent cells, try NOT placing a bomb and look again. This time you'll only need to look for a safe cell in only one direction (you don't have to diverge from it).

3) If you still can't find a safe cell, don't do anything.

```
for $(direction) in (up, down, left, right):
    place bomb at current location
    if (can find and reach divergent safe cell in current $(direction)):
        bomb = true
        move = $(direction)
        return

for $(direction) in (up, down, left, right):
    do not place bomb at current location
    if (any safe cell in the current $(direction)):
        bomb = false
        move = $(direction)
        return

else:
    bomb = false
    move = stay_put

```

This algorithm makes the bot very trigger-happy (it'll place bombs very frequently). It doesn't kill itself, but it does have a habit of making itself vulnerable by going into dead ends where it can be blocked and killed by the other players.

Do you have any suggestions on how I might improve this algorithm? Or maybe I should try something completely different?

**One of the problems** with this algorithm is that it tends to leave the bot with very few (frequently just one) safe cells on which it can stand. This is because the bot leaves a trail of bombs behind it, as long as it doesn't kill itself.

However, leaving a trail of bombs behind leaves few places where you can hide. If one of the other players or bots decide to place a bomb somewhere near you, it often happens that you have no place to hide and you die.

I need a better way to decide when to place bombs.

# Answer
> 4 votes
The problem you're facing is that your AI never stops to make an intelligent decision about where it should place its next bomb, which leaves it just dropping bombs whenever it can and then working out "shit, shit, what do I do now!?"

### Pausing to think

Right now, your AI just wanders to nowhere in particular. Sometimes, however, it should actually *be moving to* a target. For instance, if it sees a powerup and thinks it can reach it before the player, perhaps it ought to find a safe path to that tile and move there, keeping an eye out for bombs and avoiding them along the way.

The same moving-to-target behaviour can be used when it *thinks about where to place its next bomb*.

When your AI can place a bomb, instead of just doing so immediately, it should briefly use a search algorithm to choose from the available bomb placement spots based on criteria such as:

* Is it nearby? (so that it doesn't walk to the diagonal opposite corner of the map each time it wants to place a bomb)
* Is there a place I can hide from the explosion - and can I reach there before the bomb explodes?
* Will the explosion blow up tiles and give me powerups?
* Will it potentially attack the player? (an easier AI might avoid this in the early game, an aggressive AI will pursue this - whilst not forgetting about powerups)

When this decision has been made, the AI has chosen a bomb placement spot, and a place to hide from its explosion. It can now walk to the spot, place its bomb, then walk to its hiding place. Once it reaches its hiding place, it might want to keep walking and finding bomb locations (if it has multiple bombs), provided it keeps in mind to keep out of the way of the bomb it walked here to avoid.

### On walking, and finding a safe path

You can develop for your AI a single walk-to-point method and use this each time you want it to walk someplace. This method could use the A\* search algorithm to find its path.

In order to keep the AI safe, you may want to make it recheck its path each time a new bomb is placed. To avoid explosions, it could check the time til the bomb explodes, and consider a potential explosion tile safe to walk over if the bomb won't explode whilst it's walking through that tile - and if it's not safe, treat it as an impassable tile.

To give your AI faults (so it can actually be blown up sometimes) it should make calculation errors: forgetting about a bomb absent-mindedly, underestimating the explosion size or the time til the bomb explodes, etc.

**Side note:** You can also make its random walking seem more purposeful by randomly picking spots to walk to, or always having a new bomb placement spot in mind to walk to, instead of just randomly picking an adjacent tile to wander to. That way it won't go wandering back and forth on the same spot as if it can't make up its mind.

---
Tags: algorithm, ai
---


title: How can I enable CCD in Bullet Physics?

text:
# Question
Title: How can I enable CCD in Bullet Physics?
How can I enable Continuous Collision Detection (CCD) in Bullet Physics?

# Answer
You need to enable CCD per object as described in Bullet wiki or Panda3D Manual: Bullet Continuous Collision Detection. Basically you need to set `body->setCcdMotionThreshold(...);` and `body->setCcdSweptSphereRadius(0.2f);`
> 3 votes

---
Tags: bullet-physics
---


# Question
Title: Is there a limit on game updates in the iOS app store?
Does Apple implement any limit on the frequency / number of updates posted for a given app on the app store?

I have seen that apps that are updated get featured in the "new app" lists. So developers may choose to update their app every week to get featured in these lists on a regular basis?

# Answer
> 5 votes
There is no limit, but you have to be aware that there is a delay between the moment you submit and the release du to the approval process.

New and newsworthy is a selection made by apple staff. And the rules for getting on the list and remaining there are not known/consistent.

# Answer
> 5 votes
It is not true that your app will be listed under "New app" if you update it. Unless you release a different build with a new name for the app then your app might appear in the "New & Noteworthy" section in itunes.

Also there is no limit to the updates as the iOS version changes we have to make the existing apps compatible with the new version which requires a new update for the app.

---
Tags: iphone, appstore
---


# Question
Title: Easiest Way To Implement "Slow Motion" and variable game speed in XNA?
I have an XNA 4.0 game that I want to be able to switch into slow motion and back again to full speed every now and then.

So if you kill an enemy the game switches into slow motion as they explode and then goes back to normal.

What is the easiest way to do this in XNA 4.0 without having to alter all my existing code that relies on GameTime?

I have some code that relies on the TotalGameTime, which will be wrong unless I get XNA to slow down. Is there anyway to avoid refactoring that code?

Thanks!

# Answer
> 8 votes
For a fast answer, it is pretty simple, you should have something such as:

```
void update(float elapsedTime){
    // update code
    animation2.update(elapsedTime);
}

```

All you have to do is to create a float timeScale and multiply it beforehand by the elapsedTime;

```
void update(float elapsedTime){
    elapsedTime *= timeScale;
    // update code
    animation2.update(elapsedTime);
}

```

Normally, timeScale will be 1.0f, that means a regular time flow; Otherwise just make it smaller than 1 for a slower motion, and more than one for faster motion. You can even animate timeScale towards the desired speed. Only a couple of lines change, and it should do what you want.

# Answer
> 1 votes
It's exactly as DevilWithin said but you can actually retrieve the elapsed time using XNA:

```
public override void Update (GameTime gameTime)
{
    float time = gameTime.ElapsedGameTime.Milliseconds * scaledTime;
    ...
}

```

---
Tags: xna, physics, time-travel
---


# Question
Title: Callback a function when a label is touched in cocos2d-x?
How do I callback a function when label is touched in cocos2d-x?

# Answer
you can't set a callback function for `CCLabelTTF` or any other Label class, yet there is CCMenuItemLabel you can use.

you first need to create an instance of `CCMenu` class. then you need to allocate `CCMenuItemLabel` instance, using `CCMenuItem::initWithLabel (CCNode *label, CCObject *target, SEL_MenuHandler selector)`. just check how helloworld sample handled it, although it's using CCMenuItemImage, but the base idea is just same in both.
> 2 votes

---
Tags: c++, cocos2d-x
---


# Question
Title: How to control a spaceship near a planet in Unity3D?
Right now I have spaceship orbiting a small planet. I'm trying to make an effective control system for that spaceship, but it always end up spinning out of control. After spinning the ship to change direction, the thrusters thrust the wrong way.

Normal airplane controls don't work, since the ship is able to leave the atmosphere and go to other planets, in the journey going "upside-down". Could someone please enlighten me on how to get thrusters to work the way they are supposed to?

# Answer
I think your use of RigidBody physics for controlling the ship is an interesting idea (and might even be a very "correct" way of approaching this), however it's probably much easier to implement the logic yourself. In your last comment, you asked about the basic concepts:

## Inertia / Momentum

Space ships have inertia, and since space is (for our purposes) frictionless, they will simply continue to travel in a straight line with their current speed. This direction and speed is their inertia, and can be represented by a 3D vector (a Vector3 in Unity). This vector is typically referred to as the object's "velocity". In Unity terms, you will want to update your ship's position by adding this vector to it during every Update() call (remember to scale it by multiplying the vector by the deltaTime to cater for frame rate changes). Basically, our object will remember its velocity, and rotation and thrust will be used to change the velocity.

## Thrust

Whenever thrust is applied, it is simply added on to the velocity vector. The direction of this thrust vector is the opposite direction to the exhaust of your engine. If we're talking about a "main engine", and assuming we're looking forward, this would simply be the current rotation of your spaceship. This update of the velocity happens during Update() method, before you apply the velocity to the current position. You'd scale the thrust vector appropriately with deltaTime, engine strength, the thrust level input from the pilot, and anything else you'd wish to add. Remember that we're already "applying" the velocity to the position of the ship, so by updating the velocity, the position of the ship will be affected.

## Rotation

If we assume that we simply wish to rotate the ship in response to some user input (I mean: the rotation thrust is not going to be applied to the velocity as a "side-effect"), then things are relatively simple. Just as with aircraft, we have 3 primary axes around which you can rotate (refresher on Wikipedia), the pitch, yaw and roll axes. Fortunately, these correspond to the X, Y, and Z axes in the local space of the ship, meaning that we can perform a transform.RotateAround(*SHIPCENTRE*, *AXIS*, *ANGLE*).

If I remember correctly, transform.RotateAround operates in world coordinates, meaning that your rotation axis will need to be rotated into the ship's local space. It would be something like:

transform.RotateAround(transform.Position, transform.TransformDirection(Vector3.up), 20 * Time.deltaTime);

The above should give you some idea of how a standard inertia and thrust based control system works.
> 7 votes

---
Tags: physics, unity, rotation
---


title: Making entire scene fade to grayscale

text:
# Question
Title: Making entire scene fade to grayscale
When the player loses all of their lives, I want the entire game screen to go grayscale, but not stop updating immediately. I'd also prefer it fade to grayscale instead of suddenly lose all color. Everything I've found so far is either about taking a screenshot and making it grayscale, or making a specific texture grayscale. Is there a way to change the entire playing field and all objects within to grayscale without iterating through everything?

# Answer
The easiest way to do this is to create a shader for it (See code below). Draw everything to a render target, then use the shader to draw that to your back buffer

In your game code record when the player dies, then in subsequent renders interpolate a shader parameter between 1 (full colour) and 0 (full grey-scale) according to
`CurrentTime-DeadTime / FadeTime`

```
float ColourAmount;
Texture coloredTexture;

sampler coloredTextureSampler = sampler_state
{
    texture = <coloredTexture>;
};

float4 GreyscalePixelShaderFunction(float2 textureCoordinate : TEXCOORD0) : COLOR0
{
    float4 color = tex2D(coloredTextureSampler, textureCoordinate);
    float3 colrgb = color.rgb;
    float greycolor = dot(colrgb, float3(0.3, 0.59, 0.11));

    colrgb.rgb = lerp(dot(greycolor, float3(0.3, 0.59, 0.11)), colrgb, ColourAmount);

    return float4(colrgb.rgb, color.a);
}

technique Grayscale
{
    pass GreyscalePass
    {
        PixelShader = compile ps_2_0 GreyscalePixelShaderFunction();
    }
}

```

The reason for the 0.3, 0.59 and 0.11 is because the human eye doesn't treat colours equally, those values give a better greyscale image.
> 23 votes

# Answer
*EDIT*

After thinking about it, if you are not putting a tint on anything, but using the graphics original colors you could just have (like I state down below) all your colors of drawn objects set to a declared Color variable set to white. (Color NoTint = Color.White;) and then Lerp that if player lives is equal to zero. Every object drawn with the NoTint Color will slowly change (according to your interpolation rate mentioned below) to whatever you are Lerping it to.

However if you do have different tints on different objects, the below foreach loop *might* work.

*End Edit*

In my limited knowledge I would try this: Declare the colors you use when drawing specific objects, ex. Color catColor = Color.Brown, then add all of your games colors to a list.

```
public static Color catColor = Color.Brown;
List<Color> colorList = new List<Color>(){ catColor }; // and other colors
float interpolation = 0f;
float interpolationRate = .01f;
.
.
.
if(playerLives == 0)
{
   interpolation += interpolationRate;
   if (interpolation >= 1)
      {interpolation = 1;}

   foreach(Color c in colorList)
   {
      Color.Lerp(c, Color.Gray, interpolation);
   }
}

```

You can even do this for items you draw with no tint and Lerp the Color.White to a Color.Gray. (name that something like Color NoTint = Color.White, and put that on all your drawn objects)

There is probably a better way, regardless I hope this helps!
> 0 votes

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


title: How does Starcraft 2 load its metadata?

text:
# Question
Title: How does Starcraft 2 load its metadata?
Lets say you are playing Starcraft 2 melee map. The game loads the map. Melee maps have the following dependencies:

* Liberty (Mod)
* Liberty Multi (Mod)

I think the game engine will load the data from Liberty (Mod) first, then from Liberty Multi (Mod). For data that exists in both dependencies, the engine will use the one from Liberty Multi (Mod). Is this correct?

Liberty Multi (Mod) is updated with each patch of Starcraft 2.
Does the game engine load just the latest version of Liberty Multi (Mod)?
or
Does the game engine load all the versions and overwrite duplicate data with the latest version?

# Answer
> 5 votes
You are very close to understanding how the system works. My answer won't necessarily be how Starcraft works - but most moddable games work like this; and Starcraft is either very similar or the same.

Firstly the mod system would have some form of a header file for each mod. This would list any 'base' dependencies: in the instance of "Liberty Multi" it would list "Liberty" as the only base mod. This is basically used to build a chain of names and nothing more, so what you are looking for at the end of the day is:

* My Cool Map (*more on this later*)
* Liberty Multi
* Liberty

When you need to load an asset you would search the mods top-down. Starcraft would therefore look in Liberty Multi for assets and then Liberty. MPQ (Blizzard's zip-like files) are actually quite good at this as you can very quickly determine if a file is not present. If the file is not present look through any additional base mods. Something like the following pseudo-code:

```
routine findAsset(string assetName):
  let mods = "Joes Mod", "Liberty Multi", "Liberty"
  each mod in mods
    if modFileExists(mod, assetName):
      return loadAsset(mod, assetName)
  raise error "Asset not found" -- Or return a default asset for the asset type

```

You could even pre-build a table that contains the resolved file table for all the mods that are loaded - again investigate on how MPQ would make this possible.

Some systems let you skip the asset discovery and load an asset directly from a specific mod - this helps when, for example, a mod wants to call a script from the base mod that it has a new implementation/override of.

Starcraft overwrites assets when a patch is released. The engine is unaware of previous versions; except a routine which is used to upgrade (or translate-on-the-fly) previous save games and replays. If you remove something from the game you must leave the tombstones in your assets so that you don't get missing textures etc. for replays.

Finally remember that, in Starcraft specifically, a map is actually the first mod in the chain; and it is due to this that maps like DoTA were possible in Warcraft 3 (which is the code-base for Starcraft 2).

---
Tags: data-structure, starcraft-2, patching
---


# Question
Title: How should I unbind and delete OpenAL buffers?
I'm using OpenAL to play sounds. I'm trying to implement a fire-and-forget play function that takes a buffer ID and assigns it to a source from a pool I have previously allocated, and plays it. However, there is a problem with object lifetimes.

In OpenGL, delete functions either automatically unbind things (e.g. textures), or automatically deletes the thing when it eventually is unbound (e.g. shaders) and so it's usually easy to manage deletion. However `alDeleteBuffers` instead simply fails with `AL_INVALID_OPERATION` if the buffer is still bound to a source.

Is there an idiomatic way to "delete" OpenAL buffers that allows them to finish playing, and then automatically unbinds and really them? Do I need to tie buffer management more deeply into the source pool (e.g. deleting a buffer requires checking all the allocated sources also)?

Similarly, is there an idiomatic way to unbind (but not delete) buffers when they are finished playing? It would be nice if, when I was looking for a free source, I only needed to see if a buffer was attached at all and not bother checking the source state.

(I'm using C++, although approaches for C are also fine. Approaches assuming a GCd language and using finalizers are probably not applicable.)

# Answer
> 9 votes
Before deleting a buffer you **must** unbind it from each source that uses it (ex: `alSourcei(mSourceId, AL_BUFFER, NULL);` or delete all sources which are bound to the buffer.

You need to keep track of the length of each of your sounds to release them upon completions. You can do this using a structure for each source to keep the sound length and the time played (updated each game tick). Ex:

```
struct AudioVoice
{
    ALuint          mSourceId;
    ALuint          mMsDuration;
    ALuint          mMsPlayed;
};

```

If you use a component based system you can periodically check all running sources for completion and do the unbind/source delete there.

If you don't keep track of the play/pause changes in your code you will also want to check if the sources are playing before increasing the played time.

```
ALint sourceState;
alGetSourcei(mSourceId, AL_SOURCE_STATE, &sourceState);
if (sourceState == AL_PLAYING) { /* increase played time */  }

```

If you want to keep track of the sources bound to a buffer you can use a structure with the id of your buffer and a vector linking to the source structures this way you can even interrupt all sources which are bound to a buffer you need to release ASAP. Ex:

```
struct AudioData
{
    RKuint                      mMsDuration;
    ALuint                      mSourceId;
    std::vector<AudioVoice*>    mVoices;
};

```

This should be enough to get you on the right track. I can't give you more detailed code from my projects as they heavily rely on macros and hand made RTTI mechanisms.

---
Tags: openal
---


# Question
Title: Drawing isometric map in canvas / javascript
I have a problem with my map design for my tiles.

I set player position which is meant to be the middle tile that the canvas is looking at.

How ever the calculation to put them in x:y pixel location is completely messed up for me and i don't know how to fix it.

This is what i tried:

```
 var offset_x = 0; //used for scrolling on x
 var offset_y = 0; //used for scrolling on y
 var prev_mousex = 0; //for movePos function
 var prev_mousey = 0; //for movePos function

function movePos(e){

    if (prev_mousex === 0 && prev_mousey === 0) {
        prev_mousex = e.pageX;
        prev_mousey = e.pageY;
    }

    offset_x = offset_x + (e.pageX - prev_mousex);
    offset_y = offset_y + (e.pageY - prev_mousey);
    prev_mousex = e.pageX;
    prev_mousey = e.pageY;
    run = true;

}

player_posx = 5;
player_posy = 55;
ct = 19;

    for (i = (player_posx-ct); i < (player_posx+ct); i++){ //horizontal
    for (j=(player_posy-ct); j < (player_posy+ct); j++){ // vertical

//img[0] is 64by64 but the graphic is 64by32 the rest is alpha space
    var x = (i-j)*(img[0].height/2) + (canvas.width/2)-(img[0].width/2);
    var y = (i+j)*(img[0].height/4);

    var abposx = x - offset_x;
    var abposy = y - offset_y;

    ctx.drawImage(img[0],abposx,abposy);
    }
}

```

Now based on these numbers the first render-able tile is I = 0 & J = 36. As numbers in the negative are not in the array.

But for I=0 and J= 36 the position it calculates is : -1120 : 592

Does any one know how to center it to canvas view properly?

# Answer
> There is no player so to speak its a free looking thing (think more like age of empires). The player position is essentially the center of the screen.

If you have no player, and just draw the world, why complicate it with player positions? If that is the case I would have just defined the world position, (say top left where you start drawing). And starting from there render what you want to show in the viewport.

Don't overcomplicate it by stuffing in values you don't need.

Unless there is a particular reason for defining the center as player X that I'm not seeing?
> 2 votes

# Answer
Suggestion: slow down, make sure you are rendering the map nicely first. Then make sure you have the player on the map, and start moving the player ( and the camera ) on the map. This should result in a clearer solution. While nothing prevents having everything focused on the player, it is probably easier to have the player on the map.
> 1 votes

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Why does my ID3DXSprite appear to be incorrectly scaled?
I am using D3D9 for rendering some simple things (a movie) as the backmost layer, then on top of that some text messages, and now wanted to add some buttons to that.

Before adding the buttons everything seemed to have worked fine, and I was using a ID3DXSprite for the text as well (ID3DXFont), now I am loading some graphics for the buttons, but they seem to be scaled to something like 1.2 times their original size.

In my test window I centered the graphic, but it being too big it just doesnt fit well, for example the client area is 640x360, the graphic is 440, so I expect 100 pixel on left and right, left side is fine \[I took screenshot and "counted" the pixels in photoshop\], but on the right there is only about 20 pixels)

My rendering code is very simple (I am omitting error checks, et cetera, for brevity)

```
// initially viewport was set to width/height of client area

// clear device
m_d3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_STENCIL|D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0,0,0,0), 1.0f, 0 );

// begin scene
m_d3dDevice->BeginScene();

// render movie surface (just two triangles to which the movie is rendered)

m_d3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,false);
m_d3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); // bilinear filtering
m_d3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); // bilinear filtering
m_d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); //Ignored
m_d3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
m_d3dDevice->SetTexture( 0, m_movieTexture );
m_d3dDevice->SetStreamSource(0, m_displayPlaneVertexBuffer, 0, sizeof(Vertex));
m_d3dDevice->SetFVF(Vertex::FVF_Flags);
m_d3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2);

// render sprites
m_sprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE | D3DXSPRITE_DO_NOT_ADDREF_TEXTURE);

// text drop shadow

m_font->DrawText( m_playerSprite, m_currentMessage.c_str(), m_currentMessage.size(),
&m_playerFontRectDropShadow, DT_RIGHT|DT_TOP|DT_NOCLIP, m_playerFontColorDropShadow );
// text
m_font->DrawText( m_playerSprite, m_currentMessage.c_str(), m_currentMessage.size(),
&m_playerFontRect, DT_RIGHT|DT_TOP|DT_NOCLIP, m_playerFontColorMessage ) );

// control object
m_sprite->Draw( m_texture, 0, 0, &m_vecPos, 0xFFFFFFFF ); // draws a few objects like this

m_sprite->End()

// end scene
m_d3dDevice->EndScene();

```

What did I forget to do here? Except for the control objects (play button, pause button etc which are placed on a "panel" which is about 440 pixels wide) everything seems fine, the objects are positioned where I expect them, but just too big.

By the way I loaded the images using D3DXCreateTextureFromFileEx (resizing wnidow, and reacting to lost device, etc, works fine too).

For experimenting, I added some code to take an identity matrix and scale is down on the x/y axis to 0.75f, which then gave me the expected result for the controls (but also made the text smaller and out of position), but I don't know why I would need to scale anything. My rendering code is so simple, I just wanted to draw my 2D objects 1;1 the size they came from the file...

I am really very inexperienced in D3D, so the answer might be very simple...

# Answer
Normally when you load texture data with `D3DXCreateTextureFromFileEx` *and* pass 0 or `D3DX_DEFAULT` for the width and height parameters *and* the source data is not a power of two along both dimensions, the resulting texture will be resized so its dimensions are a power of two. This can result in your size computations not matching up correctly and resulting in stretching or scaling artifacts when you render, if you aren't careful.

The next power of two after 440 is 512, which is approximately 1.2 times greater, so this is what you *might* be seeing. I certainly don't see anything in your code sample that would cause the artifacts you describe, so if it's not the texture rescaling problem I'm describing, the issue is likely elsewhere in your code.

When you call D3DXCreateTextureFromFileEx, try passing `D3DX_DEFAULT_NONPOW2` instead of 0 or `D3DX_DEFAULT` for the width and height parameters, assuming your device does in fact support non-power-of-two textures (almost anything modern should, but if it doesn't this will have no effect).
> 3 votes

---
Tags: directx
---


title: Static Meshes vs 3D models

text:
# Question
Title: Static Meshes vs 3D models
What is the difference between static meshes and regular 3D models. I am very new to game development, and I am using UDK (Unreal Development Kit).

# Answer
According to UDN's page on static meshes:

"A Static Mesh is a piece of geometry that consists of a set of polygons which can be cached in video memory and rendered by the graphics card."

There really isn't much of a difference, other than that static meshes as UDK understands them are stored inside a package, (often if not always) associated with a material and a collision mesh, and usually have LODs which are themselves separate "regular 3d models" (though these can be automatically generated by Simplygon from inside the UDK static mesh editor).

I suspect you're asking "How can I import my 3d model into UDK, and use it as a static mesh?" in which case, there are a number of ways. The basic rundown is:

1. Find a plugin for your 3D package that supports exporting ASE or FBX format.
2. Import your ASE/FBX into a package as a static mesh.
3. If necessary, associate a material and collision mesh with it.

Of course, there are finer details to consider regarding UV setup for Lightmass, smoothing groups, etc., but those will all depend on your 3d authoring tool.

If you're just getting started, I would recommend taking a look at 3dbuzz' "Creating a Simple Level" video series. It requires (free) registration, but they cover all the highlights of what goes into using your assets in the UDK.
> 2 votes

# Answer
http://wiki.beyondunreal.com/Legacy:Static\_Mesh

> "Static" in "static mesh" doesn't mean "doesn't move" – it can be moved, rotated, retextured and scaled (even disproportionally) in realtime. The "static" only refers to the fact that it can't be animated, that is, the relative positions of the vertices are fixed. Hence, static meshes are useful for displaying pieces of architecture that don't move at all or might move as a whole, but they're no good for displaying players, whose bodies need to bend and change shape.
>
> Static meshes are cached into video memory, and so can be displayed many times with little extra overhead. Static meshes are a list of vertices stored once in the video memory (as opposed to "once per frame"), so drawing many copies of one static mesh is a relatively simple operation. When the static mesh is to be displayed on the screen, the engine only has to tell the video card where (and at which size, rotation, and with which textures) to do it.
>
> ...
>
> There is a difference to be made between "static mesh resources", as seen in the browser, which are stored like textures; and "static mesh actors" which are placed into a map. Don't confuse meshes with actors. A mesh (static or otherwise) is just the visual representation of an actor. For instance, weapon pickups display a static mesh in UT2003 as long as they're just waiting to be picked up over their spawn point.

Basically, they're cheaper to draw if you say that they don't animate.
> 1 votes

---
Tags: 3d, 3d-meshes, udk
---


title: Breakout collision using 2D Rectangles?

text:
# Question
Title: Breakout collision using 2D Rectangles?
Here is my code:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace BreakOut
{
    class Field
    {
        public static Field generateField()
        {

            List<Block> blocks = new List<Block>();
            for (int j = 0; j < BlockType.BLOCK_TYPES.Length; j++)
                for (int i = 0; i < (Game1.WIDTH / Block.WIDTH); i++)
                {
                    Block b = new Block(BlockType.BLOCK_TYPES[j], new Vector2(i * Block.WIDTH, (Block.HEIGHT + 2) * j + 5));
                    blocks.Add(b);
                }

            return new Field(blocks);
        }

        List<Block> blocks;
        public Field(List<Block> blocks)
        {
            this.blocks = blocks;
        }

        public void Update(GameTime gameTime, Ball b)
        {
            List<Block> removals = new List<Block>();
            foreach (Block o in blocks)
            {
                if (o.BoundingBox.Intersects(new Rectangle((int)b.pos.X, (int)b.pos.Y, Ball.WIDTH, Ball.HEIGHT)))   //collision with blocks
                {
                    removals.Add(o);
                }
            }

            foreach(Block o in removals)
                blocks.Remove(o);           //removes the blocks, but i need help hitting one at a time
        }

        public void Draw(GameTime gameTime)
        {
            foreach (Block b in blocks)
                b.Draw(gameTime);
        }
    }
}

```

I'm trying to add collision so that when the ball hits against a block, then one of the blocks disappears.

The problem I'm having is: When the ball hits the block, it removes them all in one instance.

# Answer
> 5 votes
## What you probably want

At the moment, your code only removes any `Block`s (they may be one or more) that the `Ball` collides with. You want the Ball to bounce off of the Blocks in addition to removing them. What you have is called *collision detection* (reporting when a collision has happened). What you'd like to have is called *collision response* (doing sensible things once a collision is detected).

You probably want the ball to bounce as if it had hit a wall.

## Collision response

The ball has hit the top, bottom or one of the sides. In this case, the ball should reverse its horizontal direction if it has hit a block to its left or right, or reverse its vertical direction if it has hit a block from the top or bottom.

At the moment, your collision detection only detects whether the ball is touching a block. For getting it to bounce realistically in the way described, you must also know which direction it should bounce in. You need more information: Which direction was the block in?

One way of finding out is to examine the intersection of the bounding boxes:

The coordinates of the corners of the block and of the ball can easily be used to calculate the intersection between the block and the ball. It is quite intuitive that if the ball collides with the top or bottom of the block, this intersection's **width** will be greater than its **height**. Conversely, if the ball collides with the left or right side of the block, this intersection will have a greater **height** than **width**. There are various other methods of detecting the same thing, but this one is fast.

With this information, you can make the ball bounce in the correct direction.

## Multi-block collisions

You may find that sometimes the ball intersects with multiple blocks at the same time, in which case the bounce may have to be in another direction which I haven't covered yet! You can for all cases draw similar diagrams for these cases and examine how you could go about telling them apart.

# Answer
> 3 votes
I think the basic problem here is to get the ball to bounce off a block. It looks like the block is disappearing fine.

The first step is to figure out when the ball touches a block. You have done that.

The second step is to figure out which side of the block it hit, so you know which way to bounce it. In practice, it is easier, since you only need to know whether the ball hit a horizontal or a vertical side. It is also much simpler with square blocks than with rectangular blocks.

The third step is to reflect the ball's motion in the appropriate direction

Here is some pseudocode for the second and third steps:

```
int x = (blockRect.X + (blockRect.Width / 2)) - (ballRect.X + (ballRect.Width / 2));
int y = (blockRect.Y + (blockRect.Height / 2)) - (ballRect.Y + (ballRect.Height / 2));
if (Abs(x) > Abs(y))
{
    // reflect horizontally
    ballSpeedVector.X = -ballSpeedVector.X;
}
else
{
    // reflect vertically
    ballSpeedVector.Y = -ballSpeedVector.Y;
}

```

---
Tags: xna, c#, collision-detection, collision-resolution
---


title: How do I do a game loop in c99?

text:
# Question
Title: How do I do a game loop in c99?
I'm having trouble with how to structure a game using c99. I've seen a few tutorials on making a game loop, but they are all done with c++ and classes. My main problem seems to be moving data around between the functions without creating a mess, and what stuff to put in what header files etc. Do I just do something similar to the c++ loops, and create a class-like header with a structure containing all items needed by more than one of the functions, along with the prototypes of said functions, and include the header in each function's header file? Then, in the main function, instantiate the structure and pass a pointer to it to every function in the loop?

Is this ok, or is there a better way to do it, and are there any good 'c' specific tutorials available?

Cheers

# Answer
> 6 votes
Fabian Sanglard has some excellent code reviews of id's C engines, such as his Quake 2 code review. It's a good reference for how a reasonably "modern" game was written in C.

# Answer
> 4 votes
Aside from the above answer, the common technique is to have a group of functions like draw and update that you can put in their own files and then call them from a loop in the main file. And to go deeper, you can make files for each state of your game like the main menu or the start screen, etc. and call those from the draw/update.

# Answer
> 2 votes
Depending on the type of game you are building you will have multiple ways to create you game loop.

A general approach would be to first create arrays of components (structs or arrays) your game will need. Then for each update calculate the delta time since the last update and run the appropriate functions for the right components.

Once you ran your input management, your game logics, world updates, animations and so on, you can either draw the scene or ignore drawing if your game runs faster than the FPS. Usually it's a good idea to draw on regular intervals and run the simulation independently of the graphics refresh rate.

You should study component based programming. It's not just a fad. And many people forget it's possible to do component based programming with standard C.

---
Tags: c, game-loop, architecture
---


title: When to detect collisions in game loop

text:
# Question
Title: When to detect collisions in game loop
My game loop uses a fixed time step to do "physics" updates, say every 20 ms. In here I move objects. I draw frames as frequently as possible. I work out a value between 0 and 1 to represent the proportion of the physics tick that is complete and interpolate between the previous and current physics state before drawing. It results in a smoother game assuming the frame rate is higher than the physics update rate.

I am currently doing the collision detection in the physics update routine. I was wondering should it instead take place in the interpolated draw routine where the positions match what the user sees? Collisions can result in explosions by the way.

# Answer
> 3 votes
I assume you're using an approach similar to what this article describes Fix Your Timestep!. I suggest that you don't mix your physics/collision with rendering; do the collision in update like you are right now. That interpolated state is an **approximation** simply used for smoother rendering. Even if you check for collision on interpolated state, it will not help with visuals.

Here is an example (partially taken from comments of that article):

Suppose you follow this scheme in each time step of physics engine:

1. Integrate
2. Test for collisions
3. Respond to collisions

Consider a ball bouncing off wall forming V shape path and collision is detected/resolved on second time step:

1. Ball is before collision, visually ball is at left side of the V path
2. Ball collides with wall, collision resolved, ball has now bounced off and is on right side of the V

Linearly interpolate between these 2 states and you'll be rendering the ball somewhere in the middle of the V path making the collision path seem flatter. Checking collision at the interpolated state will yield no collision and thus will not help in correcting the visuals. Only way to improve visuals here is to make time steps smaller.

---
Tags: collision-detection, game-loop, timing
---


# Question
Title: How to create a 3D world with 2D sprites similar to Ragnorak online?
As far as I know Ragnorak Online is a 3D game world with 2D sprites overlayed. I would like to use this style in a game I am making in Unity, so I would like the player to be able to select little square tiles on the terrain.

There are a couple routes I could take such as using a bunch of cubic polygons and linking them together or using one big map. The former approach doesn't seem to make any sense if the world is not flat as polygons wouldn't be reused often. The goal is to break down a 3D polygon into tiles which is hard to wrap my head around.

I believe using something like an interval tree or array would be appropriate to store the rectangle grid, but how would I display a rectangle around the selection the player has his mouse over on the polygon terrain itself?

Here is a screenshot. Here is a gameplay video. Here is the camera usage.

# Answer
> 9 votes
Ragnarok terrain is actually a rectangular heightmap, so there's no question of breaking down the terrain into little tiles-- the terrain *IS* little tiles.

The things like boats and pillars are doodads placed on the map. The map itself is a rectangular heightmap, kind of like the following code. Note that each tile stores 4 heights (for each corner) not just one, so completely vertical walls are possible.

```
class HeightMap {
    int width, height;
    Tile[] Tiles;
}
struct Tile {
    fixed float[4] CornerHeights,
    byte TileType;
}

```

A separate file then dictates for each cell what texture and lightmap area to use for its top, front, and side faces.

In response to your comment: I'm not familiar with Unity, but it seems like there's a straightforward way to import traditional heightmaps easily (with a single vertex height instead of 4x corner heights). There's plenty of articles and tutorials online, since a heightmap is one of the simplest ways to do 3D landscapes. See this for example: http://unity3d.com/support/documentation/Components/terrain-Height.html

You can read more about the way Ragnarok Online handles it at http://rolaboratory.ximosoft.com/file-format and checking the file layouts for the RSW, GND, and GAT formats, but it's not really a very straightforward strategy and definitely not something easy to learn for beginners.

What you can take away from the RO method, is that they actually use two heightmaps: one invisible heightmap used for collision detection, and a visible one used to draw the map. That way, they can extend the "invisible wall or platforms" around various objects (eg those boats or docks placed in the scene that are not part of the heightmap

---
Tags: c#, 3d, unity, tiles
---


# Question
Title: For normal mapping, why can we not simply add the tangent normal to the surface normal?
I am looking at implementing bump mapping (which in all implementations I have seen is really normal mapping), and so far all I have read says that to do this, we create a matrix to convert from world-space to tangent-space, in order to transform the lights and eye direction vectors into tangent space, so that the vectors from the normal map may be used directly in place of those passed through from the vertex shader.

What I do not understand though, is why we cannot just use the normalised sum of the sampled-normal vector, and the surface-normal? (assuming we already transform and pass through the surface normal for the existing lighting functions)

Take the diagram below; the normal is simply the deviation from the 'reference normal' for any given coordinate system, correct? And transforming the surface normal of a mapped surface from world space to tangent space makes it equivalent to the tangent space 'reference normal', no?
If so, why do we transform all lighting vectors into tangent space, instead of simply transforming the sampled tangent once in the pixel shader?

# Answer
First of all, re: "why we cannot just use the normalised sum of the sampled-normal vector, and the surface-normal?" If they're in the same space already, summing these two just has the effect of halving the strength of the normal map - it effectively blends 50% between the normal map and the non-normal-mapped geometric normals. If they're *not* in the same space, then the sum makes no sense and would just end up doing something odd, like biasing all your normals upward and screwing up your shading.

As for the space in which to do shading, it can actually be done in various ways - in tangent space, or in world space\*, or in another space such as view space.

One possible reason to do it in tangent space is that all the other relevant vectors - camera, light directions, etc. - can be transformed into tangent space in the vertex shader, saving work (except for some normalizes) in the pixel shader. Shading in another space means you have to apply a transform per-pixel to the sampled normal.

On the other hand, modern lighting models often include not just point-lights but lighting environments in the form of cubemaps, spherical harmonics, and suchlike, which are going to be defined relative to world space. So if you did shading in tangent space you'd have to throw in a bunch more per-pixel transforms to get the vectors for these things back into world space.

On the whole I generally prefer shading in world space at present.

\*Note that "world space" for shaders usually should have its origin shifted to the camera to assist with numerical precision issues, so it's really camera-centered world space, not true world space. Rotationally, it's still aligned with the world axes.
> 7 votes

# Answer
**Short Answer**

Because adding two vectors together and normalizing the result will give you a vector that is *halfway* between the two of them. I don't think that corresponds to what you were thinking it would do.

**Long Answer**

Take for instance the following picture from an unrelated subject (Blinn-Phong shading model) and pay attention to the `H` vector:

The `H` vector is the result of adding `V` and `L` and normalizing the result, which is pretty much what you were trying to do.

So, back to your problem, it should be clear from that diagram that simply adding the tangent space sampled normal and the world space surface normal together and normalizing the result won't be the same as applying the correct displacement to the surface normal as you expected.

It will just return you some new vector that is halfway between both of them, and since both vectors aren't in the same space, the result wouldn't even make any sense.

So it's important to do the conversion and work in the *same* space, either in tangent space or world space. Nathan gave the pros and cons of working in each of these spaces in his answer.
> 5 votes

# Answer
> Take the diagram below; the normal is simply the deviation from the 'reference normal' for any given coordinate system, correct?

No, it is not.

The simplest way to understand this is to take the simplest possible case of bump mapping. Your geometry is a flat quad. And you're going to apply a normal map to this quad. Now, let's say that all of the normals in this texture have a 45-degree angle pointing up. That may not be meaningful, but let's just say that this is what our normals are.

OK, so... *what direction is **up**?*

There are many ways to map a square texture onto a square quad. Maybe the texture coordinates point the top of the texture in the +Y direction of the quad. Maybe they point it in the +X direction of the quad. Maybe the -Y direction.

All of these answers must produce a *different* normal when accessed from the texture. After all, if you rotate the texture mapping by 90-degrees, the normal you fetch from the texture had better rotate with it, right? The orientation of the texture relative to the model is therefore important.

That's what the tangent-space basis matrix does. It provides a transformation from model space (not world-space) to tangent-space. It specifies what the orientation of the normals are.
> 2 votes

---
Tags: mathematics, lighting, normal-mapping, linear-algebra
---


# Question
Title: GameState management hierarchical FSM vs stack based FSM
I'm reading a bit on Finite State Machines to handle game states (or screens). I would like to build a rather decent FSM that can handle multiple screens.

e.g. while the game is running I want to be able to pop-up an ingame menu and when that happens the main screen must stop updating (the game is paused) but must still be visible in the background. However when I open an inventory pop-up the main screen must be visible and continue updating etc.

I'm a bit confused about the difference in implementation and functionality between hierarchical FSM's and FSM's that handle a stack of states instead. Are they basically the same? Or are there important differences?

# Answer
> 9 votes
As I understand it, the major difference between hierarchical state machines and stacked FSMs (HFSM and SFSM from now on) is that in an HFSM transitions away from a low level state can be specified directly, whereas in a SFSM, states in the subgroups cannot have specific exit conditions that leave the subgroup.

Probably best with an example:

This is a HFSM:

This is a SFSM (or nested FSM):

Essentially, the SFSM is "context free", in that a lower subgraph does not need to know about the implementation of the greater machine, while in a HFSM, the lower subgraphs will transition out to specific states in the greater machine. SFSM have clear benefits in that the lower subgraphs can be modified without knowledge of the complete machine.

There are some decent resources online that cover this topic too.

Images from http://aigamedev.com/open/article/hierarchical-or-nested-fsm/ (2012-03-20)

# Answer
> 14 votes
I'm not sure what sort of hierarchical FSM do you have in mind, so I'm sorry if this does not directly answer your question, but I'd really like to take the chance and add some input from my own experience using a *stack* based screen manager.

Since you need the ability to open a popup screen but still be able to see the screens below, having a stack based implementation will make implementing it pretty easy - you can just push the popup screen into the stack, and pop it again when you're done.

You can also easily wire it so that all screens on the stack will be drawn at all times (from top to bottom), but only the topmost screen will be updated. But here's a few extra tips that I find useful in my managers.

**Tip 1 - Provide a Switch operation**

Pushing a new state is useful, but I find that most of the time you won't be creating popup windows but rather transitioning between larger states. So I like to add a third operation besides the push and pop that allows me to swap states in one go. Something like:

1. `Push(State)` \- Pushes a new state into the stack.
2. `Switch(State)` \- *Replaces* the current topmost state in the stack with a new one.
3. `Pop(Amount)` \- Removes the N topmost states from the stack.

**Tip 2 - Registering states and addressing them by ID**

I've seen some state manager implementations that expect you to pass the actual state object when pushing a new state. This means that you will either be using it as `Push(new TitleScreen())` and creating a new screen object everytime, or you will have to create and store references to your screens and reuse those references.

Usually I don't want to recreate the same state everytime, but I don't want to have to manage the references myself either, so I always add a a method such as `Register(Name, State)` to my state manager which stores the states in a `Dictionary` and then I do all push or switch operations using the state name instead (e.g. `Push("PauseScreen")` instead of `Push(new PauseScreen()`).

I tend to create and register all my states at once when the application starts, although most of them hold little state until they are actually added to the stack.

**Tip 3 - Transition callbacks**

It's also useful to add a few callbacks to your states to be called whenever the state is pushed or popped. For instance, I use these four callbacks:

1. `OnEnter` \- Called when the state is pushed into the stack.
2. `OnExit` \- Called when the state is removed from the stack.
3. `OnSuspend` \- Called when a new state is pushed on top of the current one.
4. `OnWakeup` \- Called when the state on top of this one is popped.

I tend to put little or no processing in my states' constructors, and leave all the actual initialization to the `OnEnter` method. This way I can reuse my state object multiple times without having to create a new one.

You can also define a duration for your transitions, so that when you push or pop a state, the operation does not take place automatically, but only after a small transitioning phase, which you can use for fading or other animations.

**Tip 4 - Delayed operations**

Pushing or popping states right in the middle of the update phase can have unpredictable results. In order to address this, I delay my operations and queue them to be executed at the end of the update phase instead.

So when I issue a push/switch/pop operation I simply instantiate a new struct object with the parameters and type of operation that was performed and add it to a list.

Then after all states have been updates, I go over the list and apply any operation that have been queued. I use something like this inside my screen manager class:

```
private enum ScreenManagerCommandType
{
    Switch,
    Push,
    Pop
}

private struct ScreenManagerCommand
{
    public readonly ScreenManagerCommandType Type;
    public readonly Screen Screen;

    public ScreenManagerCommand(ScreenManagerCommandType type, Screen screen)
    {
        Type = type;
        Screen = screen;
    }
}

```

# Answer
> 1 votes
Give screens blocksUpdate and blocksRender fields. That way, you can easily tell a menu to stop the game from updating (and maybe rendering if you can't see the game anymore). So loop backwards through the stack until you reach a block and then loop forwards updating or drawing.

---
Tags: java, architecture, state, screen, fsm
---


title: LWJGL in Visual Studio (possible)?

text:
# Question
Title: LWJGL in Visual Studio (possible)?
I switched from XNA and C# to LWJGL and Java about 14 months ago. Inherently, this called for a switch in IDE. I started using eclipse because I have also done some basic Android development in the past.

I soon switched to Netbeans - Eclipse is just too primitive. After using netbeans for about six months, I've started looking over the fence at Visual Studio 11, toying with Metro apps for windows 8.

**Now I want to know, is there any known way to use Visual Studio for LWJGL?**

# Answer
Visual Studio has no support for Java. There are some hacks to using VS as an over-sized text editor but this won't give you any debugging capabilities and you will have to write your own build scripts. I have found no LWJGL ports to C# so I think the answer on your question is No.

However there are OpenGL wrappers for C#, see this SO question. And if you are just interested in games you can also try XNA which provides a bit higher abstraction above DirectX. There are even more alternatives to 3D in C#/C++/VB. Like SlimDX, MonoXNA and Unity.
> 3 votes

# Answer
You could just use Visual Studio as a text editor and trigger custom build steps, but then you would lose in my opinion one of the most important benefit of Java, strong IDE support.

If you didn't like Eclipse, you should try IntelliJ IDEA. Whenever I'm programming in Visual Studio, I really miss IntelliJ.
> 0 votes

---
Tags: java, lwjgl, ide
---


# Question
Title: Sidescroller variable terrain heightmap for walking/collision
I've been fooling around with moving on sloped tiles in XNA and it is semi-working but not completely satisfactory. I also have been thinking that having sets of predetermined slopes might not give me terrain that looks "organic" enough. There is also the problem of having to construct several different types of tile for each slope when they're chained together (only 45 degree tiles will chain perfectly as I understand it).

I had thought of somehow scanning for connected chains of sloped tiles and treating it as a new large triangle, as I was having trouble with glitching at the edges where sloped tiles connect. But, this leads back to the problem of limiting the curvature of the terrain.

So...what I'd like to do now is create a simple image or texture of the terrain of a level (or section of the level) and generate a simple heightmap (of the Y's for each X) for the terrain. The player's Y position would then just be updated based on their X position.

Is there a simple way of doing this (or a better way of solving this problem)? The main problem I can see with this method is the case where there are areas above the ground that can be walked on. Maybe there is a way to just map all walkable ground areas?

I've been looking at this helpful bit of code: http://thirdpartyninjas.com/blog/2010/07/28/sloped-platform-collision/ but need a way to generate the actual points/vectors.

EDIT: I did try pregenerating sloped paths using the link I posted but now I'm convinced I should use per-pixel collision as you suggested. I've been looking at the example at: http://create.msdn.com/en-US/education/catalog/tutorial/collision\_2d\_perpixel and am trying to figure out how to adjust the sprite once a collision has been detected. As David suggested, I made a few sensor points (feet, sides, bottom center, etc.) and can easily detect when these points actually collide with non-transparent portions of a second texture (simple slope). I'm having trouble with the algorithm of how I would actually adjust the sprite position based on a collision.

Say I detect a collision with the slope at the sprite's right foot. How can I scan the slope texture data to find the Y position to place the sprite's foot so it is no longer inside the slope? The way it is stored as a 1D array in the example is a bit confusing, should I try to store the data as a 2D array instead?

I also noticed several people mention that it's best to separate collision checks horizontally and vertically, why is that exactly?

# Answer
> 12 votes
I don't think you should try converting the entire map into a single height map, exactly because of the problem you described. Maps can have arbitrary complexity which you wouldn't be able to represent in a height map.

But you don't need to have a fixed slope for each type of tile either. You could store collision information on a per pixel basis for each type of tile or compute it from the tile's alpha channel and use it to determine where the character should stand at each moment based on the tiles he's currently intersecting. Here's an example of the collision data for one tile:

Using this scheme you can have any type of slope you want just by varying the tile's collision mask. This is how Sonic games were implemented back in the day, and as such I suggest reading the following page in its entirety for a better understanding:

http://info.sonicretro.org/SPG:Solid\_Tiles#Slopes\_And\_Curves

Then in order to process collisions between your character and the environment, I suggest defining a few *sensors* or collision points on your character, such as the magenta dots on the image below:

For instance, the top sensors could be used to detect and react to collisions with the ceiling, the middle sensors could be used to detect and react to collisions against walls, and the bottom sensors could be used to detect collisions with the floor and determine the correct height for the player. By moving the middle sensors up and down you can control how steep a slope has to be before the player can no longer climb it.

Another neat trick you can do with the bottom sensors, is depending on how many of them are colliding with the floor, you can detect when the player is near a ledge and possibly play a different animation such as the image below.

---
Tags: 2d, collision-detection, xna-4.0, textures, heightmap
---


# Question
Title: Legal issues around using real players names and team emblems in an open source game
I'm writing a sports management simulation game. Like most sport management games, it makes heavy use of statistics. I would like to use real players, teams and league names.

i) Am I running the risk of getting into legal battles if I should use the real names?
ii) Also what about team colours and emblems etc?

**Update** Much thanks for all the input!

# Answer
Neither one is legally acceptable. In short: a person's name and likeness is their own property and they have a right to decide how it's used, and the same goes for a sport team's emblem (but under separate laws).

### Using someone's name and likeness without permission

Wikipedia has this to say:

> The **right of publicity**, often called **personality rights**, is the right of an individual to control the commercial use of his or her name, image, likeness or other unequivocal aspects of one's identity.

Citizen Media Law Project, an American site, confirms that violation of a person's right of publicity would lead to tremendous legal trouble:

> In most states, you can be sued for using someone else's name, likeness, or other personal attributes without permission for an exploitative purpose.
>
> \[A few sentences later...\] There are two distinct legal claims that potentially apply to these kinds of unauthorized uses: (1) invasion of privacy through misappropriation of name or likeness ("misappropriation"); and (2) **violation of the right of publicity.** (The "right of publicity" is the right of a person to control and make money from the commercial use of his or her identity.)

Emphasis added. There are some exceptional circumstances (which you are almost certainly not covered by) and if you want to go into those I recommend you research the topic further yourself, or consult an actual lawyer.

### Usage of a sports emblem without permission

Sports emblems are a trademark of the sporting body *and* the emblem is their intellectual property, covered by copyright. For instance, the Blazers logo usage page expresses their position on the matter (emphasis added):

> We get many requests from Trail Blazers fans for permission to use or reprint the official Trail Blazers logos or other images for their own projects.
>
> While we certainly appreciate the enthusiasm, **Trail Blazers images and logos are protected under trademark and copyright laws and unauthorized use is not permitted.**
>
> Blazers.com content, including text, photos, graphics, audio and video material **can not be published**, broadcast, rewritten for broadcast or publication, used **or redistributed in any medium without the express written permission of the NBA and the Trail Blazers organization.**
> 19 votes

# Answer
* there are plenty of AAA games which are using fake names, so you should have guessed there *have* to be royalties involved
* being free and/or open source is usually irrelevant
* you *might* be able, according to your legislation, to use *something*, i.e. player names might be not allowed but, for example, team colors might be (that's just an random example, not real, check with a lawyer!)

The best course of action might be using all-fake, and allow your users to use "customisation packs" which of course you *won't* provide until you know they are legal (i.e. until your lawyer tells you you can).
> 5 votes

---
Tags: legal
---


title: RTS game diplomacy heuristics

text:
# Question
Title: RTS game diplomacy heuristics
I'm reimplementing an old 4X space-rts game which has diplomacy options. The original was based on a relation scoring system (0..100) and a set of negotiation options (improve relations, alliance, declare war, etc.) The AI player usually had 3 options: yes, maybe and no; each adding or removing some amount to the relation score.

* How should the AI chose between the options?
* How does the diplomacy work in other games and how are they imlemented?
* Any good books/articles on the subject?

(Googling the term diplomacy yields the game Diplomacy, which is unhelpful.)

# Answer
> 2 votes
You should answer that question from a player's perspective, i.e. if you were the AI player, how would you respond?

If a player offers you an alliance, you evaluate whether that alliance is a good idea. When is an alliance a good idea? When you stand to gain from it. When would you stand to gain from it? For instance when you're currently under threat from other players. Or when the player offering the alliance is a lot stronger than you.

You should attempt to measure these factors (heuristically) and evaluate that into a decision.

# Answer
> 1 votes
I don't know how you plan to implement your ai behavior, but lets assume you are going to implement something as described here: http://www.gamasutra.com/view/feature/1535/designing\_ai\_algorithms\_for\_.php?print=1

With such system with tasks modifiers in place, I think all you would need to do is to take also into account modifier from diplomacy, so for example if ai goes from friendly to neutral then "defend planet" task will get higher priority. This article mentions also filtering tasks which are not appropriate, so you could generate tasks which assumes player as enemy and then filter direct assault tasks in case of pace.

---
Tags: game-design, ai, rts
---


# Question
Title: Jumping a sprite while moving in a Bezier action
I'm creating a game and I need the sprite to jump (move up and down basically) while it's moving on a bezier path so it moves vertically while it still follows the path. If I do this while it's moving along the bezier path:

```
[mySprite runAction:[CCJumpBy actionWithDuration:0.1 position:ccp(0,0) height:10 jumps:1]];

```

It jumps vertically but instantly it returns to the position on the path. What I want is to jump relative to the path.

Does anyone know anything about it?

It would looks something like this:

The curve is a sequence of CCBezierBy's by the way.

Thanks.

# Answer
Aparently it is more simple than it looks. I had to sublclass CCJumpBy:

```
@implementation CCMyJumpBy

- (id)init
{
    self = [super init];
    if (self) {}
    return self;
}

-(void) update:(ccTime) t
{
    // parabolic jump (since v0.8.2)
    ccTime frac = fmodf( t * jumps_, 1.0f );
    ccTime y = height_ * 4 * frac * (1 - frac);
    y += delta_.y * t;
    ccTime x = delta_.x * t;
    [target_ setPosition: ccp( ((CCNode*)target_).position.x + x, ((CCNode*)target_).position.y + y )];//This is what has been changed
}
@end

```
> 1 votes

# Answer
Your sprite follows the bezier curve over time. So the position of your sprite is defined as:

```
sprite.x = bezier(time).x;
sprite.y = bezier(time).y;

```

This function updates the position of your sprite every frame. This is why you only see your 'jump' for a very short time (something like 1/30th of a second). To add the curve of jumping you need to change the function to this:

```
sprite.x = bezier(time).x;
sprite.y = bezier(time).y + jump(force, time);

```

This way you add the position on the curve of the jump, as defined by the force of the jump and the time to the y position.

Alternatively if you don't want the jump height to stay relative to the bezier curve you can do this:

```
if(jumping)
    sprite.x = bezier(time).x;
    sprite.y = bezier(timeOfJumpStart).y + jump(force, time);
else
// old code

```

Now my answer is very general so I hope it makes sense, but without seeing your code this is the best I can do.
> 3 votes

# Answer
The `CCAction` classes aren't very well suited to incorporate user-interaction. The primary use for them is animation, where you want your object to perform some fixed action/movement over time.

That being said, there are still ways to do what you want. The cleanest and most flexible approach would be to simply go ahead and implement the Bezier movement yourself, looking at the source of CCBezierBy might be a good starting point (you'll find the source in `cocos2d/CCActionInterval.m`), then factor in jump strength, much like Roy T. described in his answer.

If that's too much work or if you'd rather stick with `CCBezierBy`, then are also ways to do what you want. The simplest approach would be to have a `CCNode` which holds your sprite. Then you animate the `CCNode` using `CCBezierBy` and animate your sprite using `CCJumpBy`:

```
CCNode -> animated using CCBezierBy
   |
   +--- CCSprite -> is child of CCNode and is animated using CCJumpBy

```
> 0 votes

---
Tags: cocos2d-iphone
---


# Question
Title: Creating the nodes for path finding during run time - more like path making and more
I'm making my 1st game. I'm using javascript as I currently want to learn to make games without needing to learn another language but this is more of a general game dev question.

It's a 2d turn-based tile/grid game. You can check it here http://www.patinterotest.tk/ it creates a movable area when you hover a player and it implements the A\* algorithm for moving the player.

**The Problem:** I want to make the '*dynamic movable area creation*' already implement a limited number of steps for a player.

**The Questions:**

* What is a good way to do this?
* Is there another algorithm to use for this?
* The A\* algorithm needs a start and destination, with what I want to do I don't have a destination
* Or should I just limit the iteration of the A\* algorithm to the steps variable?

# Answer
> 0 votes
Since your game is a 2D tile-based game, I assume you're modelling each tile as a node, and the map is essentially a grid of nodes.

In this case, there is **no weight on any edge of the graph**, so I don't see why you're using A\* which was designed for finding minimum distances on weighted graphs. You should be using plain breadth first search

* The number of iterations you do with BFS is the max number of steps your character can take
* The path to any node can be extracted by keeping a predecessor list. Any path extracted this way is the shortest path because the graph is **unweighted**.
* The set of reachable nodes is basically any node BFS traverses; which you can use to generate your "dynamic movable area".

It will run the fastest because you don't need to do any distance considerations or heuristic calculations in the case of A\* or Dijkstra (which is basically A\* without using heuristics or H(x) = 0).

A\*/Dijkstra is overkill unless you got a **weighted graph**.

# Answer
> 3 votes
Sounds more like a you'd want a breadth first search, instead of a depth first like A\*, a common one is Dijkstra's algorithm. It is typically used for path finding, but you don't need to have a goal in mind. You can almost use it as is, except you want to limit the depth to the number of moves the player has.

A gif from the wikipedia page shows how this fits your situation:

# Answer
> 2 votes
Just execute A\* *each and every step*.

*If* this is too slow, think about optimising it. Then there are several approaches, for example jump-point-search makes the A\* itself faster. You can also try and work out the circumstances when you need to recompute the path, and only doing so then.

---
Tags: algorithm, tiles, path-finding, grid
---


title: Shadow-mapping xna

text:
# Question
Title: Shadow-mapping xna
I've been trying to implement shadows in my game and I've been following quite a few tutorials online, mainly Riemers, but I'm always getting the same 2 errors when I'm drawing my models and setting the parameters from the effect file. The errors are:

> This method does not accept null for this parameter. Parameter name: value

and

> Object reference not set to an instance of an object.

So I've then downloaded a sample and just replaced my model with the one found in the sample and the same errors occur. I this find very strange as it works with his model. I'm wondering if the problem is with my models (I made them myself). The errors start to occur after the second `foreach` loop.

```
void DrawModel(Model model, bool createShadowMap)
{
    string techniqueName = createShadowMap ? "CreateShadowMap" : "DrawWithShadowMap";

    Matrix[] transforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(transforms);

    // Loop over meshs in the model
    foreach (ModelMesh mesh in model.Meshes)
    {
        // Loop over effects in the mesh
        foreach (Effect effect in mesh.Effects)
        {
            // Set the currest values for the effect
            effect.CurrentTechnique = effect.Techniques[techniqueName];
            effect.Parameters["World"].SetValue(world);
            effect.Parameters["View"].SetValue(view);
            effect.Parameters["Projection"].SetValue(projection);
            effect.Parameters["LightDirection"].SetValue(lightDir);
            effect.Parameters["LightViewProj"].SetValue(lightViewProjection);

            if (!createShadowMap)
                effect.Parameters["ShadowMap"].SetValue(shadowRenderTarget);
        }
        // Draw the mesh
        mesh.Draw();
    }
}

```

Any help would be greatly appreciated, thanks.

# Answer
I had a hunch, which I've explained in the comments but I'm pretty certain I've figured it out.

The ShadowMappingExample uses a custom pipeline to add the ShadowMap effect to all the models. This way you can access the shadowmapping shader via

```
 foreach (ModelMesh mesh in model.Meshes)
            {
                // Loop over effects in the mesh
                foreach (Effect effect in mesh.Effects)

```

You have let Visual Studio know that you want your own models to be imported using the ShadowMappingExample pipeline and not using the default model pipeline that just applies BasicEffect as shader.

To do this set ContentProcessor to CustomEffectModelProcessor instead of just Model.

Here's a screenshot, it should be in the lower right corner of Visual Studio when you've selected your model.

Now to explain why you got the null reference error: this happens because the default processor applies the BasicEffect shader, which doesn't have the technique which you are trying to set as active.

Hope this explains everything.
> 2 votes

---
Tags: xna, shaders, hlsl, shadows
---


# Question
Title: How to make an object fly out of a slingshot?
At the moment I'm improvising a slingshot, the user can click and drag the projectile and let go. The force on the object is calculated by getting the distance between the vector of the slingshots two forks and the vector between where the user pulled it. However this will always result in a positive number and will not take into account the angle of the object relative to that of the slingshot. How can I make it fly out of the slingshot correctly?

My attempt:

```
float distance = mousePos.dst(pouchPos.x, pouchPos.y, 0);
Vector2 d = new Vector2(pouchPos.x - mousePos.x, pouchPos.y - mousePos.y);
object.setVelocity(d.nor().x * FIRE_SPEED, d.nor().y * FIRE_SPEED);

```

# Answer
Don't use the distance. Instead, subtract the fork position vector from the pull position vector and use (some constant multiple of) that as the projectile's velocity. This will automatically scale appropriately for the pull distance.

~~(Actually, it should possibly be squared — I'm not sure what the exact physics of a projectile accelerated by a slingshot band would be.)~~ Never mind: relating the energy, 1/2 *kx*² = 1/2 *mv*² ⇒ *v* = √(*k*/*m*)*x*, tells us that velocity is proportional to stretch distance (assuming the slingshot relaxes neatly and so doesn't waste energy, which is probably a good enough assumption).

Based on the code you posted, and assuming you have overloads for vectors in your language (I don't know what you're working in):

```
Vector2 d = (mousePos - pouchPos) * FIRE_SPEED;
object.setVelocity(d.x, d.y);

```

The code you posted in your answer will fire at the same speed no matter how far the slingshot is stretched, which is physically incorrect. Using vector operations also greatly simplifies the code.
> 6 votes

---
Tags: physics, box2d
---


# Question
Title: Where do I find the code for the open-source game Warmux?
I found an open source game called Warmux but I don't know how to get the code. I downloaded the file from here, but I don't know where to go from there. I didn't find any instructions on how to use the source. While I was looking for it, I came across something called git and repo. Do I use that?

# Answer
> 4 votes
The source code is available as a compressed file here. You'll have to use an unzip tool to extract the files, something like 7zip would work, since I assume you're on a Windows machine.

Keep in mind it looks like this code and its associated files were created on linux, so some of the files won't have extensions and it'll probably be somewhat confusing if you haven't see that before. Good luck.

Check out the `src` folder, it's where you'll find all the code.

---
Tags: android
---


title: Parallax Background Size

text:
# Question
Title: Parallax Background Size
If I have three scrolling/continuous parallax backgrounds, what should be the ideal size (width/height) of the background images assuming I am going to support all devices including the new iPad?

**UPDATE:**

1. Only landscape mode
2. Deployment Target: 4.2+
3. Same scene will be repeated.

# Answer
> 1 votes
The new iPad has a resolution of `2048 x 1536`. That means in landscape mode (assuming you don't want to stretch the image) your background image would need to be 1536 pixels tall and at least 2048 pixels wide if you don't want a repeated portion in the same scene. Now you can either scale down for the other devices, or you can create additional art for the other devices. If you're scaling, just scale the height of the image and allow the scrolling feature to buffer any aspect ratio changes.

---
Tags: ios, parallax-scrolling
---


# Question
Title: Why would GLCapabilities.setHardwareAccelerated(true/false) have no effect on performance?
I've got a JOGL application in which I am rendering 1 million textures (all the same texture) and 1 million lines between those textures. Basically it's a ball-and-stick graph.

I am storing the vertices in a vertex array on the card and referencing them via index arrays, which are also stored on the card. Each pass through the draw loop I am basically doing this:

```
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, <buffer id>);
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, <buffer id>);
gl.glDrawElements(GL.GL_POINTS, <size>, GL.GL_UNSIGNED_INT, 0);

gl.glBindBuffer(GL.GL_ARRAY_BUFFER, <buffer id>);
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, <buffer id>);
gl.glDrawElements(GL.GL_LINES, <size>, GL.GL_UNSIGNED_INT, 0);

```

I noticed that the JOGL library is pegging one of my CPU cores. Every frame, the run method internal to the library is taking quite long. I'm not sure why this is happening since I have called `setHardwareAccelerated(true)` on the `GLCapabilities` used to create my canvas.

What's more interesting is that I changed it to `setHardwareAccelerated(false)` and there was no impact on the performance at all.

Is it possible that my code is not using hardware rendering even when it is set to true? Is there any way to check?

EDIT:

As suggested, I have tested breaking my calls up into smaller chunks. I have tried using `glDrawRangeElements` and respecting the limits that it requests. All of these simply resulted in the same pegged CPU usage and worse framerates.

I have also narrowed the problem down to a simpler example where I just render 4 million textures (no lines). The draw loop then just doing this:

```
gl.glEnableClientState(GL.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL.GL_INDEX_ARRAY);
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();

<... Camera and transform related code ...>

gl.glEnableVertexAttribArray(0);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glAlphaFunc(GL.GL_GREATER, ALPHA_TEST_LIMIT);
gl.glEnable(GL.GL_ALPHA_TEST);

<... Bind texture ...>

gl.glBindBuffer(GL.GL_ARRAY_BUFFER, <buffer id>);
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, <buffer id>);
gl.glDrawElements(GL.GL_POINTS, <size>, GL.GL_UNSIGNED_INT, 0);

gl.glDisable(GL.GL_TEXTURE_2D);
gl.glDisable(GL.GL_ALPHA_TEST);
gl.glDisableVertexAttribArray(0);

gl.glFlush();

```

Where the first buffer contains 12 million floats (the x,y,z coords of the 4 million textures) and the second (element) buffer contains 4 million integers. In this simple example it is simply the integers 0 through 3999999.

I really want to know what is being done in software that is pegging my CPU, and how I can make it stop (if I can).

My buffers are generated by the following code:

```
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, <buffer id>);
gl.glBufferData(GL.GL_ARRAY_BUFFER, <size>
    * BufferUtil.SIZEOF_FLOAT, <buffer>,
    GL.GL_STATIC_DRAW);

gl.glVertexAttribPointer(0, 3, GL.GL_FLOAT, false, 0, 0);

```

and:

```
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, <buffer id>);
gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER,
    <size> * BufferUtil.SIZEOF_INT,
    <buffer>, GL.GL_STATIC_DRAW);

```

ADDITIONAL INFO:

Here is my initialization code:

```
gl.setSwapInterval(1); //Also tried 0

gl.glShadeModel(GL.GL_SMOOTH);
gl.glClearDepth(1.0f);
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glDepthFunc(GL.GL_LESS);
gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_FASTEST);

gl.glPointParameterfv(GL.GL_POINT_DISTANCE_ATTENUATION,
        POINT_DISTANCE_ATTENUATION, 0);
gl.glPointParameterfv(GL.GL_POINT_SIZE_MIN, MIN_POINT_SIZE, 0);
gl.glPointParameterfv(GL.GL_POINT_SIZE_MAX, MAX_POINT_SIZE, 0);
gl.glPointSize(POINT_SIZE);

gl.glTexEnvf(GL.GL_POINT_SPRITE, GL.GL_COORD_REPLACE, GL.GL_TRUE);
gl.glEnable(GL.GL_POINT_SPRITE);

gl.glClearColor(clearColor.getX(), clearColor.getY(),
        clearColor.getZ(), 0.0f);

```

Also, I'm not sure if this helps or not, but when I drag the entire graph off the screen, the FPS shoots back up and the CPU usage falls to 0%. This seems obvious and intuitive to me, but I thought that might give a hint to someone else.

# Answer
The answer is that the GPU was taking too long to render the frame and subsequent frames ended up doing a CPU intensive busy wait before moving onto the next frame.

The busy wait was occurring in: `com.sun.opengl.impl.windows.WindowsOnscreenGLDrawable.swapBuffers()`

The solution was 2 fold.

First, to prevent frames from backing up I changed my FPSAnimator to have `scheduleAtFixedRate` as `false`. That is:

`new FPSAnimator(canvas, 30, false);`

The second change was to render my entire scene into a Framebuffer Object and simply draw the Framebuffer Object to the screen each frame. Since my scene is mostly static, I was able to use this to increase the FPS while my scene is not changing. When the scene does change, I render it to the Framebuffer Object again.
> 1 votes

# Answer
If you weren't using hardware acceleration at all you would be getting less than 1 fps. Unless that applies we can discount that possibility.

My hunch is that your vertex pipeline has dropped back to software emulation. You're saying that you've got one million lines and you're calling glDrawElements with GL\_UNSIGNED\_INT, which - depending on your hardware - may be overflowing your hardware maximum for number of vertexes per draw call and max vertex index.

Note that glDrawElements itself doesn't specify these maximums, but you can bet that they do exist in hardware.

To resolve this you can try splitting up your glDrawElements calls so that your indexes fit in unsigned shorts. Yes, it's more draw calls, but it will fit within hardware limits for everything and won't choke your vertex pipeline.
> 3 votes

# Answer
My bet would be that your performance is not bound by GPU operations, and that hardware acceleration makes no difference because the amount of time spent doing the GPU work is dwarfed by 'something else'; be that marshalling on the driver side, something in the OpenGL libs itself, or even possibly your own code. The trouble is, figuring out what overhead is getting you isn't straightforward unless you know what's going on under the hood.

That diagnosis would be consistent with your reply to mh01's answer; increasing the number of draw calls to render the same primitives adds yet more overhead, while keeping the number of primitives drawn the same. Have you tried making the task less complex to see if there's one element of the problem that causes a massive drop in performance? E.g. does disabling textures but rendering the same amount of primitives work fine?

My advice would be to dig out a sampling profiler (something that breaks into your process every X microseconds and grabs the callstack), and see which module it's spending all this time in.
> 1 votes

---
Tags: opengl, hardware-acceleration, jogl
---


# Question
Title: How do I find which isometric tiles are inside the cameras current view?
I'm putting together an isometric engine and need to cull the tiles that aren't in the camera's current view. My tile coordinates go from left to right on the X and top to bottom on the Y with (0,0) being the top left corner.

If I have access to say the top left, top right, bottom left and bottom right corner coordinates, is there a formula or something I could use to determine which tiles fall in range?

This is a screenshot of the layout of the tiles for reference.

If there isn't one, or there's a better way to determine which tiles are on screen and which to cull, I'm all ears and am grateful for any ideas. I've got a few other methods I may be able to try such as checking the position of the tile against a rectangle. I pretty much just need something quick. Thanks for giving this a read =)

# Answer
X+Y is constant for all tiles in a column, and X-Y is constant for all tiles in a row. In your current screenshot, it seems like your screen is centered at (X=15,Y=15) or alternatively, at (X+Y=30,X-Y=0)

* 20 \<= X+Y \< 40 (vertical axis)
* -8 \<= X-Y \< 10 (horizontal axis)

Your loop should be based on X+Y, and X-Y, not precisely X and Y.

```
// current viewport is x+y=20to40 by x-y=-8to10
for(a=20;a<40;a++) {
    for(b=-8;b<10;b++) {
       if ((b&1) != (a&1)) continue;
       x = (a+b)/2;
       y = (a-b)/2;
       // do stuff with X and Y here
    }
}

```

Here's the demo
> 2 votes

# Answer
To get how many titles you can display on screen (with rounding taken into account):

```
numOfTitlesX = (int)((float)screenWidth / titleWidth + 0.5f);
numOfTitlesY = (int)((float)screenHeight / titleWidth + 0.5f);

```

Now you can just make loop to draw your titles. An example loop could look like this (without boundary check!):

```
for(int y = 0; y < numOfTitlesY; y++){
   for(int x = 0; y < numOfTitlesX; x++){
       titles[startingTopLeftIndex + y][startingTopRight + x].draw(screenDeltaX, screenDeltay);
   }
}

```
> 0 votes

---
Tags: tiles, isometric
---


title: Selecting objects on a 2D map

text:
# Question
Title: Selecting objects on a 2D map
I have a object selection function by checking the mouse click and getting the relevant object.

How ever there is a rare situation where if one object is partially behind the other then both objects are in the given area so im wondering how I can make the game know which one was selected, as currently my method does not know.

This is my function that works it out:

```
function getobj(e){
    mx = e.pageX - curleft; //mouse click x
    my = e.pageY - curtop; //mouse click y

    function searchSprites(sprites, x, y) {
        var matches = [],
        i = 0,
        data = null;
        for (i = 0; i < spritea.length; ++i) {
            data = spritea[i].data;
            if (x > data[0] && y > data[1] && x < data[2] && y < data[3]) {
                var imageData = ctx2.getImageData(x, y, 1, 1);
                if(imageData.data[3] !== 0){
                    return [spritea[i].id];
                    i = spritea.length;
                }
            }
        }
    }
    res = searchSprites(spritea, mx, my);
    bid = res[0];
    if(bid === '1'){
        alert('You selected the skyscraper in front!');
    }else if(bid === '3'){
        alert('You selected the skyscraper behind!');
    }
}

```

Image of the map:

It keeps telling me I clicked the skyscraper behind which is not necessarily what the user is trying to do. How can I improve the accuracy of this ?

# Answer
`bid = res[0];` Seems like that's your issue. Instead of just selecting the first one, you'll want to sort through the found sprites and get the one that's closest to the camera. Also, not sure if it's a copy and paste error or what but:

```
if(imageData.data[3] !== 0){
    return [spritea[i].id];
    i = spritea.length;
}

```

`i = spritea.length;` won't be reached.

**EDIT**

OK, I looked into this more and I can't find if `getImageData` can be changed to get multiple layers of images. However, the below function will return the ids of all the images that overlap the point the mouse is at. I don't know much about your code, but I'm assuming you have some way of getting the sprite ID from your sprite array, I'm just assuming it's `spritea[i].id`. You'll have to figure that one out on your own I'm afraid. Also keep in mind that I don't do javascript, so I'm just assuming this code works, don't expect to copy/paste it and have it work though.

```
function searchSprites(sprites, x, y) {
    var matches = [],
        i = 0,
        data = null;
    for (i = 0; i < sprites.length; ++i) {
        data = spritea[i].data;
        //Assuming data is an array that contains the corners of the sprite
        //data[0] = x_Minus_Side
        //data[1] = y_Minus_Side
        //data[2] = x_Plus_Side
        //data[3] = y_Plus_Side

        if (x > data[0] && y > data[1] && x < data[2] && y < data[3]) {
            matches.push(spritea[i].id)
        }
    }
    return matches
}

```

Once you have that list, you can sort it based on depth, or the one closest to the bottom of the screen wins, or whatever you want.
> 5 votes

---
Tags: javascript
---