# Question
Title: OpenGLES 2.0 batching method and do not draw inactive object
I am researching about "batching" objects for one big VBO and reduce draw call.

These are what I am doing now:

1. Create interleaved VBO based on texture or render state (like Blending)

* So, for example, there will be two separate VBO and draw call if I want only some object has blending
2. For more batching, add unused vertex data.

* eg) Object "A" doesn't need to have color data, but I added white empty color, so can be batched in interleaved array
3. For hiding object, set vertex positions to 0.0. So, stay on the array, but cannot see.

* eg) if it is quad, set to \[0.0, 0.0, 0.0, 0.0\]

These are my questions:

1. Should I create one Giant VBO, and use draw call based on offset??

* If I do that, then is there any limitation on glbufferData?? (or performance drop, if too much data in)
    * Is there any method that vbo can contain different types of interleaved vertex?
    * Is multiple "offset" draw call not affect performance unlike single draw call?
2. Should I bind multiple texture atlas to each unit, and use uniform?

* Currently, I am only binding one texture per draw.
3. Is there correct way for above #3 method?? (Feels like not correct)
4. I am updating "All" vertices every frame, even though some object doesn't need to be updated. (glBufferData) Should I do multiple update call??

Sorry for my wording, but please point me anything that I am doing something wrong.

Thank you.

# Answer
> 1 votes
**Should I create one Giant VBO, and use draw call based on offset??**

Maybe. Try it that way and any other way that works for you on your target hardware. What works best in this regard can vary quite a bit with target hardware and driver version. "Giant" is a bit of a relative term, too. There's a big difference between 1,000 objects, 50,000 objects, and 1 million objects. Your definition of "giant" may not be all that big to the hardware, or it might be way too big. Depends on the hardware.

**If I do that, then is there any limitation on glbufferData?? (or performance drop, if too much data in)**

There is a limit, and particularly large updates can be slower than smaller incremental updates, though making a ton of small updates can be slower than making one big update. Whether it's faster to use a single array and update it with `glBufferSubData` or multiple VBOs can, again, vary by hardware and driver.

**Is there any method that vbo can contain different types of interleaved vertex?**

Just append all the vertices of whatever types you want in contiguous chunks in the VBO(s). A VBO is really nothing more than a chunk of memory on the GPU. You can only use a single vertex layout per draw call, however. Nothing stops you from filling up a big VBO with a few thousand Position/Color vertices followed by several thousand Position/TexCoord/Normal vertices, assuming you don't intend to draw them all at the same time. VBO offsets are partly for handling this in the event you think you need it.

**Is multiple "offset" draw call not affect performance unlike single draw call?**

Again, it'll vary. In theory, it's one less bit of state to switch (VBO bindings) between draw calls which is usually a win, but a particular driver/GPU may be really good at such state changes and have a lot of draw call overhead. It may just be a balancing act on your hardware to find the right trade off between state changes and draw calls, assuming you come even remotely close to stressing the hardware in the first place (and if you don't, just do whatever is simplest and concentrate on more important aspects of your game).

**Should I bind multiple texture atlas to each unit, and use uniform?**

The uniform approach is unlikely to perform well from my understanding of how most modern GPUs works. Just bind a different texture per batch. It's easier. If unsure... profile on target hardware and find out.

**Is there correct way for above #3 method?? (Feels like not correct)**

Just don't write the object into the VBO. If you're dynamically updating the whole thing every draw call, just append your "live" objects to the buffer in a loop, and draw the corresponding number of vertices in your draw call. No reason to spend time copying vertices for invisible objects around. You don't need a particular sprite/object to maintain the same position in the VBO with each draw call; the GPU does not know or care what was in the VBO in the previous frame.

```
index = 0
for each object:
  if object is visible:
    vbo[++index] = object.topleft
    vbo[++index] = object.bottomleft
    vbo[++index] = object.bottomright
    vbo[++index] = object.topright

```

Note that the "if object is visible" part can be more sophisticated than just checking a visibility flag. If you have a large play area and lots of objects, culling out objects which will be entirely off screen is often beneficial here, and it can be one of the easier parts of the engine to parallelize should you need that performance boost.

Just remember to use a dynamic/streaming (`GL_DYNAMIC_DRAW`) VBO config.

---
Tags: opengl, rendering, opengl-es2, vbo
---


# Question
Title: switching from third person view to first person view
I have done a scene in opengl where I'm using a third person camera (that I can control with the mouse). Then, inside it, it has the camera of the first view (that I called `thirdpersonCamera`, see the code above), drawing the camera, the frustum etc..

It looks like this picture:

and I've done with this code:

```
void GLView::drawSubThirdpersoncamera()
{
    // set perspective viewing frustum in the 3rd person camera
    thirdpersonCamera.setFrustum(FOV_Y, (float)(W)/(H), NEAR, FAR);

    // use 3rd person camera projection matrix (the frustum, the perspective etcetera)
    // as the opengl camera
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(thirdpersonCamera.projectionMatrix.getTranspose());
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glPushMatrix();
    {
        // First, transform the camera (viewing matrix) from world space to eye space
        glLoadMatrixf(thirdpersonCamera.viewMatrix.getTranspose());

        // translate and rotate the mouse control
        // (keeping the camera fixed because
        // we want only the scene to rotate/translate)
        // for thinking about modern opengl: should be a matrix..
        glTranslatef(mousePosition[0], mousePosition[1], mousePosition[2]);
        glRotatef(mouseAngle[0], 1, 0, 0); // pitch
        glRotatef(mouseAngle[1], 0, 1, 0); // heading
        glRotatef(mouseAngle[2], 0, 0, 1); // roll

        // now the draw the scene
        drawScene();

        // draw the first person camera
        glPushMatrix();
        {
            glMultMatrixf(physicalCamera.viewMatrix.getTranspose());

            drawAxis(4);
            drawCamera();
            drawFrustum(physicalCamera.fovy, physicalCamera.aspectRatio, physicalCamera.near, physicalCamera.far);
        }
        glPopMatrix();

    }
    glPopMatrix();
}

```

Now I want to switch to the eye of the camera I've drawn, with this code:

```
void GLView::drawSubPhysicalCamera()
{
    // use physical camera projection matrix (the frustum, the perspective etcetera)
    // as the opengl camera
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(physicalCamera.projectionMatrix.getTranspose());
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glPushMatrix();
    {
        // the view matrix: how the camera is positioned in the world space
        glLoadMatrixf(physicalCamera.viewMatrix.getTranspose());

        drawScene();
    }
    glPopMatrix();

}

```

I think it should go because I'm using the same matrix once for translate the object in the screen, once for translate the camera but.. in the second view I don't see anything.. I don't find any error because the transformation in the space is the same but.. it doen't work..

Where am I wrong?

# Answer
As clearly explained in this article I have to take the inverse:

> If you only have the view matrix and you need to find a camera transform that can be used to position a visual representation of the camera in the scene, you can simply take the inverse of the view matrix.
> 0 votes

---
Tags: opengl, camera, matrix, third-person-view
---


# Question
Title: How to check metadata stored in FBX files?
Is there a way to check and edit metadata information stored in FBX files? I'm using 3ds Max's fbx exporter. Can this be done with it or is there any other tool for that?

For example: adding name, contact info, tags or anything that provides ownership of the file.

# Answer
I'm not sure exactly what you want to do but you can always export it from 3ds max in ascii format instead of binary and open it later in a text editor (notepad).
> 2 votes

---
Tags: unity, data, fbx
---


# Question
Title: Entity Component Systems, Input, and Angry Birds!
I am using Artemis ECS. I have the very basics of a game already. I am now trying to determine how to gracefully handle input and to a lesser extent collisions. Some people say with ECSs, everything should be a component and data driven and you shouldn't really use events/messages, or at least avoid them where possible.

Input handling in component based design covers what I am asking as well, but I would understand when and how to raise events, add components or whatever much more fully by using a game we all know (Angry Birds) as an example.

So, for Angry Birds I would have some entities with components (where components are pure data, and an entity is just an id):

* catapult (position, sprite, state{free, available}?, clickable?, dragable? releasable?)
* bird (position, velocity, physics{density}, sprite)
* baddy (position, velocity, physics {density}, sprite, health)
* box (position, velocity, physics{density}, sprite, health)

And the following systems to start with:

* SpriteSystem (has all entities with sprite component)
* PhysicsSystem (has all entities with position, velocity and physics components)
* HealthSystem (has all entities with health component)
* InputSystem (knows about keyboard/mouse events such as clicked, dragged, released, key down etc, not sure what entities should have...)

How would the InputSystem interact with other Systems to say the catapult was clicked, and if there are birds left, and none are in flight, allow it to be dragged and release/fire the bird.

Would the InputSystem modify ClickableComponent, DragableComponent and ReleasableComponents on the catapult entity? Or, should it raise some sort of Click, Drag and Release Events? What System would listen for the component changes/events? A CatapultSystem perhaps?

When the PhysicsSystem notices a collision between the bird and a baddy, should it create a Collision event, that I guess the HealthSystem would listen for? Or again, should it modify a collision Component already on the Entity?

Collision and click components would need to be cleared every game loop if I took the component approach (seems a bit naff...)

# Answer
The entity component system (ECS) is great. There are plenty of misunderstandings about it though. For example, it's perfectly fine to use event/messages in an ECS. People often think you're supposed to completely avoid inheritance too. Also not true. The ECS methodology is just a strategy for avoiding issues that come with a large hierarchy of inheritance. It's a great system, and fun to use. But you should only follow it if it makes sense and is the easiest method for you to use.

Make things a lot easier on yourself and create a catapult control component, along with that `CatapultSystem`. This system handles all the input and calculations for launching a bird. The catapult component stores the launch angle, and force. With this pair you can get rid of `clickable`, `dragable` and `releaseable`.

All systems should have access to the current input. This can be via a global static class that's cleared each frame, or with messages.

Don't forget that birds respond to clicks too. It might be easiest to have a `birdInFlight` property on the catapult component that responds to clicks and sends a message to the current bird to trigger its special ability.

Collisions are handled by the physics system. And it can send messages to the health system to appropriately deduct health from baddies/birds and destroy the objects collided with.

It sounds like for the most part you're on the right track. Your ideas are good enough to move forward with, and that's exactly what you should do. Move forward with your ideas until you find an actual problem. If you're not sure, just pick a route to go with and try it out. You're only going to learn for sure if it was the right way to go or not, and it may open up new possibilities you hadn't thought of before.
> 7 votes

---
Tags: input, component-based, entity-system, entity-component, artemis
---


# Question
Title: Finding possible moves for an entity in a 2d tiled game
I'm having issues coming up with a specific search term for this, but how would one go about finding the possible moves in a 2D turn-based strategy game (i.e. FF:Tactics, Fire Emblem, Advance Wars).

I'm not so much thinking about terrain (or even collision) at this point. I'm just wondering what algorithm I can use to figure out that X entity can move 5 tiles and attack 2 farther tiles than that.

I know I can use something like Dijkstra to find the distance between two points. One possible implementation is starting at the players location and then branching off from there until the distance returned by Dijkstra is greater than the move count.

Just wondering if someone could point me in the right direction (i.e. name of algorithms, technique, articles, etc).

# Answer
I think a bounded Dijkstra is precisely what you want to use. The way that Dijkstra finds the distance between two points is it maps out the distance to every node from an origin node, and then 'selects' the shortest path from this distance map. You want to do virtually the same thing, except you want the distance node graph it creates as output, rather than a path to any particular point.

The one modification you'll want to make is to skip calculating the distance from nodes that have already exceeded your maximum movement range. Then you'll have a node graph of all of the nodes that the unit can travel to, plus a border, so just cut out the nodes that have a distance greater than the movement allowance.

Viola.

**In other words, pretty much what you described in your question is what you need to do.** It also has the benefit of being able to use the output to do the pathfinding, without need to do any further calculations.
> 5 votes

# Answer
Most simple (and probably most naive) approach I can think of right now:

* Start at your character and mark all surrounding fields as `steps - 1`.
* Iterate over all newly marked fields and once again mark their surrounding fields as `steps - 1` where `steps` would be the current field's step number, unless the new field has an already higher number.
* Repeat the last step till you're running out of steps.
> 12 votes

# Answer
I think what you're looking for might be Manhattan Distance. Assuming no obstacles, you can say that a square is reachable simply if:

|toX-fromX| + |toY-fromY| \< maxMoveDistance

This algorithm may not be the right direction to go if you're going to have obstacles later; one possible way to adapt it might involve having obstacles cast 'shadows' and re-evaluating from the nearest point.

EDIT (Because I have a bit more spare time now):

By 'shadows' I mean something like this, if 0 is a reachable square, C is the character, and X is an obstacle:

```
 012345678
0    0
1   00
2  000X
3 000C000
4  00000
5   000
6    0
 012345678

```

Since (5, 2) is an obstacle, you start by assuming that you can't get to anything with x\>=5 AND y\<=2. You can then recalculate from another square; if you want to go to (5, 1) you could calculate the manhattan distance from (4, 1) and see if that + the distance from the character to (4, 1) is less than the player's movement distance.

This is a fairly trivial example, but if you have multiple obstacles and/or a bit longer movement range, it should be able to handle the complexity.

Whether it'd actually be any better than just flood-filling, either in programming complexity or execution efficiency, I have no clue. Just seemed like a more interesting way to solve the problem.
> 2 votes

---
Tags: tiles, path-finding, turn-based-strategy
---


title: Development with multiple libraries

text:
# Question
Title: Development with multiple libraries
I'm almost fresh to the game development and I have one question about libraries.

**If I choose one library, such as SFML, to develop the menu of my game, is it possible to merge with, for example, Direct X to handle the graphics(load maps and etc)?**

# Answer
There are lots of libraries you can use together. However, SFML uses OpenGL. You can't run OpenGL and DirectX at the same time.

Most libraries that utilize the same core libraries will be compatible with each other. You may find some difficulties integrating them. For example 2D libraries along with 3D libraries may have different requirements for setting up your view matrices. For the most part, if both libraries use the same rendering tech, work with the same number of dimensions and do different things, they're likely compatible.

Learn more about what these core libraries do as well. DirectX wouldn't be used for loading maps for example. Get into some basic tutorials and learn what these things do. It should clear up a lot of the simple questions like this.
> 4 votes

---
Tags: c++, directx, sfml
---


# Question
Title: What measurement units are used in the return value of the getWidth method in the UnicodeFont class supplied by Slick2D?
I'm working on a small component for a game that essentially wraps the provided String so that it fits within the width of the provided rectangle. The rectangle is provided by the Slick2D library as well. I've assumed thus far that the width of that rectangle is in OpenGL units, but the distinction has been irrelevant in any way I've used Slick2D geometry so far.

Now, I'm using the UnicodeFont class and I'm not sure what units the return value of the getWidth method of that class is in. UnicodeFont.getWidth() returns an int value, so my initial inclination was to think it returned the value in pixels.

The Rectangle class supplied by Slick2D however, returns a float value. This leads me to believe that it is measuring the width using OpenGL coordinates, but I'm not sure.

So perhaps the community knows. Do the return values of both the Rectangle.getWidth() and the UnicodeFont.getWidth() methods use the same system of measurement?

# Answer
> 3 votes
We can look at the source to answer this question. The `getWidth` method goes through each character and gets the `getGlyphBounds` which goes and gets `vector.getGlyphPixelBounds`, eventually leading down to `Glyph.getWidth()`. The `getWidth` method there says:

> Returns: The width in pixels of the glyphs image

So, **pixels** is the unit of measurement used for `getWidth` of a `UnicodeFont`.

---
Tags: opengl, java, lwjgl, slick
---


title: Drawing entities in an isometric engine

text:
# Question
Title: Drawing entities in an isometric engine
I am having some problems drawing my entities in an isometric map.

Tiles are drawn using Painter's algorithm to do the z-sorting which works great for the tiles alone. Entities are parented to a particular tile and have an offset within it. They are drawn immediately after their parent tile. The problem is that when the entity is too far right or too far down; the next tile(horizontally to the right, or vertically below) is drawn over parts of it like so:

(Note, currently my player has his registration point (red circle) a little higher than right at the bottom, just to better approximate the centre of his feet.)

A couple of ideas I had to try and remedy this:

1) To simply offset the position of entities to move them so that they will always draw in a place that won't be drawn over later. I really don't like to add in strange offsets that must be compensated for all over the place but this seems like a viable option.

2) To draw everything tiles and entities, using painter's algorithm. Entities would not need to be parented to a tile anymore but every renderable graphic would need it's drawing position offset. (Tiles would have their point at the very top, entities at the very bottom so that painter's orders things correctly)

3) Implement some kind of layering system so that all floors are drawn first, then things behind entities etc etc. This seems complex and would change from scenario to scenario. As my game will have randomly generated levels, I feel this isn't the right solution.

So, do any of the above have merit? Do I have it all completely wrong and there's another solution I've missed?

# Answer
I think that layering is the way to go. Layer 0 would be the ground, then layer 1 would include everything that is on the ground, and finally layer 2 would be anything above the ground (blimps, clouds, etc.). Add/remove layers as needed. Each layer would be painted in order, and a painting algorithm would be used to order the entities within each layer. Randomly generated levels or not, it shouldn't really affect the layering system.
> 7 votes

---
Tags: rendering, isometric
---


title: Securing game plugins / mods for java

text:
# Question
Title: Securing game plugins / mods for java
I am looking into using Java to write a game core, then writing the game logic separate either in Java, or using something like Python. This way I open up the ability for any future users to modify the game to their liking, similar to how TES or Torchlight 2 is setup.

However, my main concern is doing this securely. Looking at the Java option, I can't help but feel that this would allow nefarious users from accessing a lot more than would be safe (OS-level stuff, complete access to the user's file system, etc.). So I was hoping that there was some way of making sure that this isn't possible. Ideally I'd like to use something like Python, Lua, or Angelscript to reduce what the mod writer has access to, but I'm not sure how secure even this would be.

So I came here hoping that this is something dealt with on a regular basis, since I know it's a long shot but... I hope to get on Steam at some point, and I can't imagine Workshop support would allow unsafe code.

# Answer
The Java Scripting Framework is what you need. It's a system which let's you register script engines in your java app (e.g. Groovy, Javascript), so you can pass control to an engine/script. It's used to create the flexible parts of a heavy-duty JEE application. So corporate users can customize your deployed application with individual scripts.

The following example is taken from the official Oracle page, you send a string to a script engine, which evaluates it and returns the result:

```
import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("print('Hello, World')");
    }

```

You can pass parameters to the script and there are many other possibilities - see the official docs.

As for security, you can use a SecurityManager with finely tuned policy files which grant specific rights to your script engine. E.g. calls like System.exit(-1); will not get executed.

An example policy file (just copied from https://db.apache.org/derby/docs/10.9/devguide/rdevcsecure871422.html) :

```
/* Grants permission to run Derby and access all      */
/* databases under the Derby system home              */
/* when it defaults to the current directory               */

grant codeBase "file://f:/derby/lib/derby.jar" {
  permission java.lang.RuntimePermission "createClassLoader";
  permission java.util.PropertyPermission "derby.*", "read";
  permission java.util.PropertyPermission "user.dir", "read";
  permission java.io.FilePermission "${derby.system.home}","read";
  permission java.io.FilePermission "${user.dir}${/}-",
      "read,write,delete";
  permission java.util.PropertyPermission "derby.storage.jvmInstanceId",
      "write";

};

```
> 3 votes

# Answer
look at the security framework in java, which is the same framework that should prevent java web applets from deleting `c:\windows\system32`

for the scripting engine you can then decide exactly what the script has access to, do be careful because opening holes can have unintended consequences
> 1 votes

# Answer
There are various scripting languages for JVM, e.g. Lua (luaj) and Javascript (rhino). These are typically used to script things like games, and present the scripter only with functionality you chose to expose.
> 1 votes

---
Tags: java, modding, security, plugin
---


title: Luminance increase in SDL

text:
# Question
Title: Luminance increase in SDL
We have managed to create grayscale picture using the following snippet of codes in SDL. What we need to do now is how to first convert into YUV or YCrCb for it be able to set the luminance value and thereafter back into RGB?

```
const unsigned int gray = (component1 + component2 + component3) / 3;

const int gray_rgb = SDL_MapRGB(original->format, gray, gray, gray);

```

# Answer
> 0 votes
First of all, this sort of thing is easier to do if you convert your pixel values to floating-point \[0, 1\] rather than integer \[0, 255\] values:

```
// convert 8-bit int to [0, 1] float
float r = r_int / 255.0f;
float g = g_int / 255.0f;
float b = b_int / 255.0f;

// ... do your processing on the float rgb values ...

// at the end, convert back to 8-bit int (with clamping and rounding)
r_int = int(min(max(r, 0.0f), 1.0f) * 255.0f + 0.5f);
g_int = int(min(max(g, 0.0f), 1.0f) * 255.0f + 0.5f);
b_int = int(min(max(b, 0.0f), 1.0f) * 255.0f + 0.5f);

```

You can scale the luminance of the image by simply multiplying the RGB values by some constant. Constants less than one will make it darker, and constants greater than one will make it brighter. There's no need to convert to YUV or YCrCb, or even calculate the luminance, if all you want is to make the image brighter or darker.

(You should also technically convert the RGB values from gamma space to linear using the sRGB transformation before operating on them, and convert back afterward...but I'd forgive you if you didn't want to deal with that complication at this point. :) Also, if you do need to calculate the luminance, it's best to convert to linear and average the RGB using the Rec. 709 luma coefficients rather than just doing `(r + g + b) / 3`. Then convert back to gamma space before displaying the grayscale value on screen.)

---
Tags: sdl, c
---


# Question
Title: Help choosing a collision prediction method?
This takes a little backstory, bear with me.

This is also a very general question, and I'm aware that without greater specifics the best answer might be "it depends."

So the context is that we're doing a real-time two-player iPhone game, with one iPhone acting as host and the other as client.

One of the things that's happening in the game, that needs to sync properly across devices, is similar to a Break-Out style situation: multiple rows of bricks at the top of the screen and a ball that bounces up and destroys them.

The wrinkle is that the projectile is more like a bullet than a ball. It takes out all the bricks in its path.

So to sync this across devices, what we're doing is calculating all the bricks that will be hit as soon as the bullet launches along a given trajectory. We have to do this because due to the physics model we're using, if we just launch the bullet at the identical angle and identical velocity on each of the two devices, the bullet ends up taking out slightly different bricks on each device.

So that's the task at hand: we need a calculation of all the bricks that will be taken out by a given bullet. Once we have that, we can send that array to the client, and then (ideally) the clients knows what bricks to take out before the bullet actually hits them, and the games sync infinitely better than if the collisions were reported in real time.

The last important element to consider is that there can be lots of bullets shooting at once. Anywhere from 4-40+ of these arrays need to be calculated as rapidly as possible.

So what's the best way to do it? We've thought of two ways:

1) Drawing an imaginary line along the path of the bullet and detecting all the bricks it intersects.

2) Shooting a separate invisible bullet along the normal bullet's path at something like 20x faster velocity. This "phantom bullet" doesn't cause any reaction upon contact with the bricks, it just passes right through them. But when it passes through a brick, that brick gets added to an array, and it ends up creating the array we need.

I should note that we've actually implemented option 1, and it works really well. The only problem is that when we get upwards of ten or twenty bullets it seems to cause massive slowdown. We're considering option 2 to try to boost framerate because we think it would be easier on the processor.

So, we're looking for a way to figure out if that's true.

I know that different physics simulators are different, and everything is different and difference is different and etc. etc. different, but I guess I was wondering if anyone has a general idea whether or not, *in general*, one of these methods should perform better than the other.

I'm hoping there's some knowledgeable individual here that can provide insight--or even suggest a simple test we could do to find out for ourselves.

# Answer
Before implementing a new solution you should make profiling tests to identify the bottleneck of your application. I think it must be either the data transfer latency between host and client or the processor capabilities of devices. Just make simple stress tests in both cases and profile the results.

For example, if the results show that you have problems with transfer latency you must minimize data transfer. A solution could be to send the ray description over network and make the two devices calculate the entire collision in parallel. As a prerequisite you must have a way to offset the angle or velocity error to achieve the same trajectory in the host. You could make a test to see if this error is predictable.

If sending data over network is not the bottleneck you could divide the processing among host and client by letting each one check collisions for one half of the trajectory, for example. As a prerequisite the client must have the capability to send data to the host for sync.
> 1 votes

# Answer
create a grid for your playing field

each brick is composed of one or more grid spaces

when you shoot a bullet it goes at a certain angle from perpendicular take the tangent (`tan`) of that and you can do the following:

```
double y=starty;
for(int i=0;i<maxX;i++){

    if(tan>0){
        for (int ytmp=floor(y);ytmp<=floor(tan+y);ytmp++){
            GridBlock gr = grid[i][floor(y)];
            if(containsBrick(gr)){
                //remove brick
            }
        }
    }else{
        for (int ytmp=floor(y);ytmp>=floor(tan+y);ytmp--){
            GridBlock gr = grid[i][floor(y)];
            if(containsBrick(gr)){
                //remove brick
            }
        }
    }
    y+=tan;
}

```

the main speedup I introduce here is not looping over all bricks but instead going over a grid and checking for each cell whether there is a brick that needs to be removed and you don't have to muck about with line-line intersections

just transmit the `tan` and `starty` with as much accuracy as possible

note I didn't account for wall bouncing
> 0 votes

---
Tags: collision-detection, ios, multiplayer, realtime
---


title: rotating objects in a double orbit

text:
# Question
Title: rotating objects in a double orbit
I have a object at the center. Other set of objects rotating around center in first orbit. Now i want other objects to rotate around the objects in 1st orbit.

In the above fig, set of triangles are rotating around the square and circles are rotating around the triangle. I have the code which works for 1st orbit, but i am not able to render that second orbit.

I am calling display in loop. i is static global variable. which transformations will do the second orbit?

# Answer
> 3 votes
You can do it by inserting another "push, transform, draw, pop" sequence before your pop. Something like this:

```
// your current code
glPushMatrix();
glRotatef(...);
glTranslatef(...);
glRotatef(...);
DrawTriangle();

    // new code
    glPushMatrix();
    glRotatef(...);
    glTranslatef(...);
    glRotatef(...);
    DrawCircle();
    glPopMatrix();

glPopMatrix();

```

The idea is that since the operations for the circle are done before the triangle's transform is popped, all the triangle's transforms will apply to the circle as well. For instance, the translation to set the circle's position will be relative to the triangle's position.

BTW, your code is a bit odd in that you're applying two separate rotations to the translation vector. You're calculating the translation vector using `cos` and `sin`, so the vector will already be rotated by `angle1`. Then, since you're doing a `glRotate` before your `glTranslate`, the translation vector will be rotated again by `i`. You could simplify this by just rotating by `angle1 + i` from the beginning, and removing all the `glRotate` calls. (Since you're undoing the rotation by `i` before you draw, none of the rotations are applying to your actual models.)

---
Tags: opengl, glut
---


title: Help on my glow shader!

text:
# Question
Title: Help on my glow shader!
I'm trying to create a glow shader for a neon style game but I'm having a little trouble with rendertargets. Right now all I want is something VERY simple where I change the rendertarget, draw to it and then pass it into the shader. A lot of the examples I've looked at do the first part but don't include how to pass it all through a shader. Right now I'm not really concerned about the glow part, I just want to get it passing through a shader so I can work on the glow part.

edit - new code:

```
graphicsDevice.SetRenderTarget(renderTarget);

..
..
..

graphicsDevice.SetRenderTarget(null);

renderTargetTexture = (Texture2D)renderTarget;
loader.GlowShader.Parameters["glowTexture"].SetValue(renderTargetTexture);

for (int l = 0; l < loader.GlowShader.CurrentTechnique.Passes.Count; l++)
{
    loader.GlowShader.CurrentTechnique.Passes[l].Apply();
}

renderQuad.Draw();

```

And the glow shader (this is probaly really messy but I'm not really fuzzed about that right now, I just want the basic thing to work):

```
float4x4 World;
float4x4 View;
float4x4 Projection;

Texture glowTexture;

sampler glowSampler = sampler_state
{
texture = <glowTexture>;
magfilter = LINEAR;
minfilter = LINEAR;
mipfilter = LINEAR;
AddressU = clamp;
AddressV = clamp;
};

struct VertexShaderInput
{
float4 Position : POSITION0;
};

struct VertexShaderOutput
{
float4 Position : POSITION0;
};

VertexShaderOutput VSOutline(VertexShaderInput input)
{
VertexShaderOutput output;

float4 worldPosition = mul(input.Position, World);
float4 viewPosition = mul(worldPosition, View);

output.Position = mul(viewPosition, Projection);

return output;
}

float4 PSOutline(VertexShaderOutput input, float2 pixel:VPOS) : COLOR0
{
float2 uvPixel = (pixel + 0.5) * float2(1.0 / 1600, 1.0 / 900);
    return tex2D(glowSampler, uvPixel);
}

technique Outline
{
pass Pass1
{
    AlphaBlendEnable = TRUE;
    DestBlend = INVSRCALPHA;
    SrcBlend = SRCALPHA;

    VertexShader = compile vs_3_0 VSOutline();
    PixelShader = compile ps_3_0 PSOutline();
}
}

```

On a side note, if I try running this and drawing it using sprite batches it works so I think up until "rendertargetTexture = (Texture2D)renderTarget" everything is correct. It's just when I try to use the quads that nothing appears still.

```
        graphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
        using (SpriteBatch sprite = new SpriteBatch(graphicsDevice))
        {
            sprite.Begin();
            sprite.Draw(renderTargetTexture, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1);
            sprite.End();
        }

```

# Answer
Assuming that graphicsDevice, renderTarget and loader are properly set I think you are missing the apply() of the glow pass and a fullscreen quad draw. If you don't draw the fullscreen quad, the glow pixel shader cannot apply the effect since there is nothing being draw to the default render target. I think that's why nothing appears on the screen.

```
graphicsDevice.SetRenderTarget(renderTarget);
//
//...
//
graphicsDevice.SetRenderTarget(null);
renderTargetTexture = (Texture2D)renderTarget;
whateverEffectToGlow.whateverTechniqueToGlow.pass[0].apply;
RenderFullScreenQuad();

```

You can use this example to write RenderFullScreenQuad(): http://projectvanquish.wordpress.com/tag/fullscreen-quad/
> 1 votes

# Answer
What you are missing out is actualy where you do your "posteffects". The first part all seems alright.

A breakdown of glow & post effects would be like this :

1 : Render all your models to offscreen rendertarget ( this you have done )

2 : Render your offscreen rendertarget to a fullscrean quad, that will cover the entire screen. this way you will get a texture that looks like your world over the screen, and can manipulate the pixels.

3 : once you are rendering the quad, you can manipulate the orginal texture to do diffrent stuff with the pixels, like bloom or glow.

4 : Once all this is done, you got a new rendertarget ( or backbuffer ) that have an applied glow onto it.

All in all, you only miss the part where you are drawing the fullscreen quad with the postpass texture. I think this article : Good article about lightprepass
> 0 votes

---
Tags: xna, shaders, glow
---


title: Texture Won't Load in OpenGL

text:
# Question
Title: Texture Won't Load in OpenGL
I've started trying to make a 2D game in C++ using OpenGL, and I'm using SOIL as the imaging loading library. The problem is, I've been trying to get a simple 64x64 image of a red square to open and display, but when I render it, I get a 64x64 white square.

I've used SOIL before to great effect to load textures for a 3D program I was working on earlier. I have copy-pasted code from that program into the new one, but the texture is not displaying for some reason. I've checked that it was loaded properly, and the ID is being set to a proper ID, and it's getting the dimensions correctly, just not the colors. Even more confusing, when I try to get the height and width of the texture, they are both returning 0.

I'm starting to believe more and more that its something I did wrong initializing the Orthographic Projection matrix, or something is missing from my OpenGL initialization code.

Here is the initialization code:

```
//Init glfw
if (!glfwInit())
{
    fprintf(stderr, "GLFW Initialization failed!\n");
    exit(EXIT_FAILURE);
}

processCmdArgs(argc, argv);

//Create window
glfwWindowHint(GLFW_SAMPLES, g_aaSamples);
g_mainWindow = glfwCreateWindow(g_screenWidth, g_screenHeight, "Stellar Miner", g_appFullscreen ? glfwGetPrimaryMonitor() : nullptr, nullptr);
if(!g_mainWindow)
{
    fprintf(stderr, "Could not create glfw window!\n");
    exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(g_mainWindow);

//Create view matrix POSSIBLE PROBLEM AREA
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0f, g_screenWidth, g_screenHeight, 0.0f, 0.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);

//Init glew
int err = glewInit();
if (err != GLEW_OK)
{
    fprintf(stderr, "GLEW initialization failed!\n");
    fprintf(stderr, "%s\n", glewGetErrorString(err));
    exit(EXIT_FAILURE);
}

```

Here is the code for the Texture class:

```
Texture::Texture(const char* path)
{
        //TODO: Detect the settings based on the target hardware capabilities
    filepath = path;
    textureID = LoadSoilTexture(path, SOIL_LOAD_RGBA, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y, true);
    //GetTextureDimentions(textureID, &width, &height);
    this->height = 64;
    this->width = 64;
    if (textureID < 1)
        printf("Error loading texture.\n");
    printf("Using width %f and height %f.\n", height, width);
}
void Texture::Render(vec2 pos, float rot, float scale)
{
    glBindTexture(GL_TEXTURE_2D, textureID);

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(pos.x, pos.y, 0.0f);
    glRotatef(rot, 0.0f, 0.0f, 1.0f);
    glScalef(scale, scale, 0.0f);

    glBegin(GL_QUADS);
    //Top Left
    glTexCoord2f(0.0f, 0.0f);
    glVertex2f(0.0f, 0.0f);
    //Top Right
    glTexCoord2f(1.0f, 0.0f);
    glVertex2f(width, 0.0f);
    //Bottom Right
    glTexCoord2f(1.0f, 1.0f);
    glVertex2f(width, height);
    //Bottom Left
    glTexCoord2f(0.0f, 1.0f);
    glVertex2f(0.0f, height);
    glEnd();

    glPopMatrix();

    glBindTexture(GL_TEXTURE_2D, 0);
}

```

Interestingly, even hardcoding width and height to 64 makes them print out as 0...

And here is how I load textures:

```
GLuint LoadSoilTexture(const char* file, int channels, unsigned int id, unsigned int flags, bool useLinear)
{
GLuint textureID = SOIL_load_OGL_texture(file, channels, id, flags);

glBindTexture(GL_TEXTURE_2D, textureID);

bool hasMipmaps = (flags & SOIL_FLAG_MIPMAPS) > 0;

if(useLinear)
{
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, hasMipmaps ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
}
else
{
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, hasMipmaps ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST);
}

glBindTexture(GL_TEXTURE_2D, 0);

return textureID;
}

```

Sorry for the long post, and any help would be greatly appreciated. You can find my entire solution on Github here.

# Answer
> 5 votes
You never call `glEnable(GL_TEXTURE_2D);` to switch on texturing. And since you seem to use the fixed function pipeline that means that only the currently set color (which is white by default is used) to draw.

As for why the texture dimensions are not printed correctly: the format specifier `%f` expects a 64 bit `double` value on the stack (`floats` are automatically converted to `doubles`), but `width` and `height` are (probably 32 bit) `int`s which results in undefined behavior. Use `%d` or `%i` instead.

---
Tags: c++, opengl, textures, rendering, glfw
---


# Question
Title: Crossfade Between Two Music Tracks in Pygame
My intention is to have **two music tracks**, which are similar in nature, **fade between each other** at various times. When such a fade occurs, one music track should fade from full volume to muted in a short period of time, and, simultaneously, the other track should fade from 0 to 100 and continue playing from there. They must be able to do this **dynamically** at any time - when a certain action occurs, the fade will occur and **the new track will start playing at the same time index** that the other one left off at.

This might be plausible by either using volume manipulation or by starting and stopping the music (however, it appears that only a "fadeout" option exists, and there is a lack of a "fadein" option). How can I do this? What is the best method, if any, that exists? If it is impossible using Pygame, **alternatives to Pygame are acceptable**.

# Answer
> 3 votes
There is a "fadein" option, it just isn't a function. From the pygame.mixer.Sound documentation:

> **play()**
>
> begin sound playback
>
> play(loops=0, maxtime=0, fade\_ms=0) -\> Channel
>
> ...
>
> The **fade\_ms** argument will make the sound start playing at 0 volume and fade up to full volume over the time given. The sample may end before the fade-in is complete.

# Answer
> 1 votes
There is no easy method with pygame.

pygame uses sdl\_mixer and shares its limitations. sdl\_mixer only supports one streamed, music channel. You could use sound effects instead and manage your own sound samples and channels, but it's a lot of work:

* Track the progress of each piece of music, including the channel it was played on
* Without streaming, you have to preload the entire music file into memory. It's a lot because we're talking about uncompressed audio, you're looking at many 10s of MB per minute, depending on sampling rate and bit depth.

So really, you're rolling a crossfade library from scratch.

If you limit your requirements so that you crossfade only at the end/start of tracks, you could create a transition music, and play music1, transition, music2 in that order. It's still annoying to do though.

For more details see this thread: http://forums.indiegamer.com/showthread.php?12641-Cross-fading-with-SDL\_mixer

---
Tags: python, pygame, music
---


title: Parallax scrolling with 2D camera

text:
# Question
Title: Parallax scrolling with 2D camera
I'm developing a 2D Platform game, I have a 2D camera, some backgrounds, and everything is working good. Now I want to implement parallax scrolling to give the illusion of depth in my game, but i can't imagine how to make my different layers of background to move (most correctly, be rendered by the camera) with a different speed from each other).

In brief this is my game structure:

I have 3 layers of backgrounds: the first is the road level, where the player runs; the second is the intermediate; the third are some mountains very distant (in my mind). Everyone of these layers is created with seamless textures and organized with the tilemap technique, with every texture positioned one after the other. Of course I make the spritebatch draw only the visible ones.

The camera is a rectangle that follows player movements and goes just horizzontaly.

Since layers aren't moving, but only the camera is moving, I don't know how to make a background scroll with a different speed from another!

# Answer
You just move the backgrounds despite them being meant to be static.

* For example, your character (and the camera) move 5 units to the right.
* Move the background right behind the character to the right by 1 unit.
* Move the background behind the other background by 2 units.
* Move the next background by 3 units, etc.
* The furthest away background (i.e. the background supposed to be static) is moved with the player/camera (here: 5 units).

Doing this will already create the parallax effect you're looking for.

Simplified:

Move your backgrounds with your camera, where the actual movement is a function based on the camera's movement and the distance to/behind the screen. The further away something is, the more you move it (so it appears static).

This can get a bit tricky drawing wise, but you'll essentially just have to draw your backgrounds twice at most (so it always fills the screen, no matter the offsets).
> 4 votes

---
Tags: xna-4.0, parallax-scrolling
---


title: Maya 3d view port issues

text:
# Question
Title: Maya 3d view port issues
Hi currently i am working on modelling an object within view port, but i have issues here. On my right panel view port, when i try to alter an vertex of an cube i'm getting an 3d effect similar like this:

But instead i should see effect similar like this:

Where am i wrong here? Thanks

# Answer
> 1 votes
The problem is you only selected and moved one vertex, when in fact you need all the vertices in that row. That is, all the vertices stacked onto one spot in an orthogonal view.

If you selected it with selection box and it selected 1 vertex, you may have turn on/off backface culling or your selection tool based on camera selection. Double click on selection tool to view tool setting and uncheck camera based selection. it could work.

---
Tags: 3d, models, maya
---


# Question
Title: How would I display a unit that is hidden behind another object
Right, I've tried searching for this but as you might be able to tell from the title, I didn't really know how to word it anyway...

In some games such as rts games, when a unit is hidden or half hidden behind another object, such as a tree of building, the player will be able to see a translucent coloured version of that unit where it is hidden.

I was wondering how it would be possible to figure out which parts of the units sprite have actually been covered, and how to then use this information to then draw the translucent coloured version of the sprite.

If possible could the answers given relate to c++ and sfml? If not other answers will still be appreciated.

Sorry if my language is unclear its the first time I've asked a question on this site.

# Answer
> 2 votes
You can use the stencil buffer.

A good approach for drawing outlines generally is using the stencil buffer, as described on flipcode.

To draw obscured objects using the stencil buffer, here is a recipe I've used:

* draw all units normally, setting z-buffer.
* draw the scenery and set the stencil buffer as well as the z-buffer.
* clear the z-buffer.
* draw all units a second time, setting the z-buffer, but only where the stencil buffer is set, this time with a shader that draws outlines or glows or whatever affect is desired.

This has limitations in that you'll have difficulty drawing units that are obscured by other units properly with this approach. You can however class enemy units as 'scenery' for this, so enemy units behind rocks are not highlighted but your own units behind enemy units are.

# Answer
> 9 votes
You can use depth buffering for this, just as you would for rendering. Just flip the depth comparison operator between *lessorequal* and *greater*.

First, draw the whole scene as normal, filling in the depth buffer as you go. Now flip your depth comparison. Then redraw the desired object(s) using a highlight shader.

This will cause the occluded parts of an object to be be drawn in the highlighted color. If you want to draw partially-occluded objects with a highlight on the whole object, the technique may be more complex.

One approach there is to render all static geometry. Then do an *occlusion query* render pass for all the dynamic objects, recording whether any object was occluded more than ~20% or some heuristic. Then do a rendering pass the draw all the non-occluded objects with Z buffer testing/writing on and no special effect. Finally do a pass to render all the occluded objects with their own depth buffer in the highlight effect. This process can be optimized with some cleverness, but I assume you want the basics working before you worry about optimizing something that might not even need it for your game.

---
Tags: c++, graphics, sfml
---


# Question
Title: Why does the order matter in multiplication of matrixes?
I stumbled on this question because I had the same problem with my camera, and changing the multiplication order worked.

I ran into a similar problem when scaling a model. This code produced the wrong result:

```
// world is an existing Matrix
var scale = world * Matrix.CreateScale(3.2f);

```

whereas this worked perfectly (scaled a model to 3.2x it's size):

```
var scale = Matrix.CreateScale(3.2f) * world;

```

I don't understand why the order matters though - in "normal" math (that is, 5\*3 vs 3\*5), swapping the factors yields the same result. I understand differences if there are more than 2 factors (like in this question), but I don't see the issue here?

I don't know much about how Matrices really work and so I don't know if that's an XNA quirk or if it would happen in OpenGL as well?

# Answer
> 26 votes
The fact that matrix multiplication isn't (usually) commutative is a mathematical fact, and doesn't have anything to do with which API or library (XNA, OpenGL, etc.) you're using.

At the level of arithmetic, the order matters because matrix multiplication involves combining the rows of the first matrix with the columns of the second. If you swap the two matrices, you're swapping which one contributes rows and which one contributes columns to the result.

The deeper reason that order matters is that matrices represent geometric transformations, and the order of transformations matters. For example, since simple scaling is always relative to the origin of coordinates, doing a scale after a translate is different from a translate after a scale, since the translate moves the origin. Similarly, rotations don't commute with translation, and rotations around one axis don't commute with those around another axis.

# Answer
> -2 votes
Man is this kind of hard to figure out a good explanation of why.

Basically the matrices all transform the geometric values. If you shift the object any, you aren't just performing on a mathematical operation on the original object, but you are performing the operation after any other adjustments you have already done.

You can almost think of the object after any matrix operation as a completely new object, because that's what it is in RAM, for the most part. So, if you move the object 4 steps to the left, you end up with (Object on top of an "invisible board" 4 steps to the left). If you rotate the resultant object, you aren't rotating the original object anymore, but the object based on the object that is attached to that "invisible board" 4 steps to the left.

---
Tags: xna, mathematics
---


# Question
Title: Structure of Visual C++ Projects in Visual Studio
In particular, I was wondering if it was possible for Visual Studio to treat source files in different directories as all in the same directory. I first saw this after purchasing the Introversion Software Humble Bundle which gave people access to their source code for their previous games from Subversion. I noticed with one of their games that it was split into physical folders for different parts (like "\world", "\lib", ect.), but in Visual Studio the files were put into filters with the same names as the physical folder and all of the files were treated as if they were in the base directory. I also noticed that they included files in the VS project that weren't even in the base project folder. This is what I mean:

Things like the \data folder are included with the folders from \source, even though they are in different directories and levels.

What I also want to know is how to go about including folders and files from different locations and treat them all like they are all in the same place. But most of all, I would like to figure out how they made all source files act like they were all in the base folder, instead of the separate physical folder that they are, as shown by the `#include`s in the files:

Image Here

As you can see, the app.h/.cpp files are in the "\app" folder, but the includes are able to reference things from "\lib" without including "..\lib" to go up a folder, effectively treating all of the source files like they originate in the base folder.

TL;DR: How does one include multiple folders from different places as filters, and how do you treat all source files like they originate from the same place.

Any help is greatly appreciated, as this will help me organize my project better. Thanks.

# Answer
> 5 votes
The structure of what VS calls "filters" (just folders in the project tree) is entirely independent of the structure of directories on disk. There's no connection between them. You can choose to make the filters match the directories, if you like, but VS doesn't do that automatically or anything.

When you add files to your project, you can select them from any directory. They go into the root filter by default, regardless of their location on disk. VS will internally maintain a relative path from the project file to each source file (you can see these if you open up the .vcxproj). Then you can create filters as you like and drag different files into them. It doesn't move the files on disk, just reorganizes the project.

---
Tags: c++, visual-studio, project-management
---


# Question
Title: do games use multiple threads to play music?
Do games use multiple threads to play music and other operations besides things like server connections and sockets?

And is that why when the game freezes (for any reason) the music can sometimes keep playing, because only the game thread is slowing down?

# Answer
> 10 votes
As always, it depends. Audio is a very complex topic, and the details can be vastly different from API to API, and from system to system.

# Introduction to audio processing

*Note: for all the examples below, we will be considering linear PCM, at 44100Hz (samples per second), with 16-bit samples, and two channels (stereo). This is a very common configuration.*

Audio processing usually consists of two components: a data producer and a data consumer.

The **consumer** is normally the audio driver, or audio hardware. In order to play sounds, the data consumer will need a constant stream of bytes. The exact amount of bytes that a consumer needs is defined exactly by:

```
bytes_per_second = samples_per_second * bytes_per_sample * channels

```

So, for 44100 samples per second, 2 bytes per sample (16 bits), and 2 channels (stereo), this equates to 176400 bytes per second.

The **provider** is normally your program. Your task is to provide data for the consumer. Your task consists of creating *exactly* 176400 bytes per second of audio you want to play.

In a perfect world (and real-time environments), you must be able to provide exactly 44100 samples per second, which means 1 sample every 22675.7 nanoseconds.

These samples would be received by the consumer and immediately sent to the speakers, so it is crucial that you send 1 sample exactly at every 22675.7 nanosecond mark. This is very difficult to get right, and if you fail to provide the required data at the exact time mark, the consumer will not know what to do, and the results will not be what you expect (more on this later).

# Buffering

To solve this problem, most audio processing systems work with a FIFO buffer (like a queue) for the provider to store data on one end as it sees fit, and the consumer will consume as it sees fit. The idea is that the producer will in average be a given amount of bytes ahead of the consumer, so the producer has relaxed restrictions on the exact timing at which the bytes have to be produced.

For example, if you make a system in which the producer is 256 samples (1024 bytes) ahead of the consumer, the producer can be up to 256 samples behind in its obligation to produce bytes, and the consumer will still have audio data to play. 256 samples is approximately 6ms worth of sound data, so your program can stall for up to 6ms before the consumer will notice.

Make no mistake, you still have to provide an *average* of 176400 bytes per second, and if for some reason you fall back, you will have to catch up at some point in the future. The purpose of the buffer is simply to relax the timing at which you have to provide the data, not reduce the amount of data you have to send.

# Delay

However, buffering creates a problem. If the producer is 256 samples (6ms) ahead of the consumer, any audio you queue to play will only be heard on the speakers 6ms after you enqueue it. This is called "delay".

In general terms, the greater the amount of bytes the producer is ahead of the consumer, the more slack the producer will have to fall behind, but also the greater the delay between the moment at which the program decides to play a sound, and the moment at which the sound is actually played on the speakers.

# Actual systems

In practice, audio systems are much more complex, with large chains of producer-buffer-consumers, filters, splitters and mixers, called the "Audio graph". However, when playing audio to speakers, there will be a final consumer, which sits right behind a DAC, and will in fact provide exactly 1 sample exactly every 22675.7 nanoseconds. The circuit that does this is commonly outside of the CPU, and has its own clock, so no matter what happens on the CPU, this guy will work in perfect sync.

# Why is audio programming difficult?

Even in the most simple audio graphs, you still have to buffer audio to be played. The large variety of hardware that exists, with many different types of drivers, on so many systems, means that there are *way too many* variables to get your sound right at the right time.

Delay is directly proportional to the length of your buffers, as well as to the amount of elements your audio graph has. You usually want to make the buffers as short as you can, but in modern OSs, where your program only has a very small and unpredictable share of CPU to use, creating a program where the audio is very responsive, while not leaving the buffers empty is very difficult.

# Onto your question

So, what happens if your program is stuck doing something, and you can't fill the buffer? Well, it depends on how your system is built.

## Low-level APIs

If you made your program so you're actually responsible of filling the buffer, like when you're programming with DirectSound, OpenSL, Core Audio or other low-level audio API, and the thread responsible for filling the buffer stalls, then you won't be able to keep on filling the buffer. That's what the buffer is for, so initially nothing will happen. The sounds you've already enqueued will be played as requested.

If your program is still stalling, and the buffer runs empty, then what happens is up to the audio driver/hardware, and is never good. Many audio systems will just fill the output with zeroes, so the audio will go silent. If your program manages to recover shortly after that, this will manifest as an audio "click", also called "audio glitches".

However, other audio systems may fill the output with garbage, so you may hear white noise. Many other systems with circular buffers will just loop through the buffer, so you will hear the last few milliseconds of successfully queued bytes looped over and over again.

## High-level APIs

If you're making your program with an API that manages the enqueueing for you, like XAudio2, SoundPool, AVAudioPlayer or other high-level audio API, then the results will unsurprisingly be dependent on the API. Many of these APIs will manage the sound queue on a separate thread with higher priority, so as long as that thread doesn't stall, you won't hear glitches.

# Answer
> 1 votes
Yes. An audio device plays a fixed buffer size of samples then request the next buffer. Also generally music is streamed from disc so there's another thread handling data streaming.

# Answer
> 1 votes
Sound back-ends usually use threads to make sure that the sound/music is played continuously and not interrupted or distorted when larger calculations are done. However you won't need to deal with those yourself, as they are implemented by the backend, for example OpenAL.

There is one additional issue that can be solved via threads, namely the streaming of the music from the hard disk, this however, isn't as time critical as the playing of the sound itself and mostly depends on how much you buffer, if you buffer multiple seconds at a time and have a recuring loop such as the game loop a dedicated thread should not be necessary.

---
Tags: multithreading, audio
---


title: Rotations and angular velocity

text:
# Question
Title: Rotations and angular velocity
I'm new to 3D-game programming and I'm having some trouble making objects rotate the way I want them to. I just read Glenn Fiedler's tutorials on game physics, awesome stuff by the way! (http://gafferongames.com/game-physics/physics-in-3d/)

Now, I'm trying to make a simple space sim. If you imagine a spaceship that is not yet rotated in any way (up = Vector3.Up etc..). If I apply some yaw-input (which would increase the angular velocity) I'd then expect the ship to rotate around the up-vector of the ship (which is also the world y-axis at the moment). That works fine. If I would then roll the ship a little bit, I'd expect the ship to roll around its forward axis, but it should also continue to spin around the world y-axis.

At the moment with my implementation instead of keeping it's momentum around the y-axis, it continues to spin around its local up-vector - which is obviously wrong.

I think I understand why this happens with my current implementation, I'm just not sure how to fix it.

This is what I have at the moment, with some minor simplifications (runs every update):

```
Vector3 addedRotation = new Vector3(pitchInput, yawInput, rollInput);
addedRotation = Vector3.Transform(addedRotation, rotation);
rotationVelocity += addedRotation;

rotation.Normalize();

Quaternion w = new Quaternion(rotationVelocity, 0);
rotation += Quaternion.Multiply(w * rotation, 0.5f);

```

I'd be very happy if someone could point me in the right direction here. If anything needs clarification, please tell me and I'll try explain it better.

Thanks for taking the time!

# Answer
> 6 votes
`rotationVelocity += addedRotation` is actually fine. Angular velocity is a vector and adds in the usual way.

The part you may be missing is that in your description of the desired motion, you have a rotation around a *constant* axis (the global up-vector) combined with a rotation about a *rotating* axis (the ship's roll axis, which is rotating because of the ship's yaw angular velocity).

This does not correspond to a constant angular velocity, which would be the combination of several rotations about constant axes - e.g. the global up-vector and the ship's roll axis *at the moment of adding the roll*.

Also note that the quaternion renormalization, `rotation.Normalize()`, should probably be done *after* you add `0.5 * w * rotation`, not before. (Also, you seem to be missing the delta time, which should be multiplied in there as well - your angular velocities are in radians per frame instead of radians per second.)

(Finally, as a side note I should mention that in general, angular velocity doesn't remain constant over time, even if no torques are acting on an object. Angular *momentum* remains constant, but for a non-trivial inertia tensor, this results in time-varying angular velocity because the inertia tensor is rotating with the object.)

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


title: Showing trajectory indicator

text:
# Question
Title: Showing trajectory indicator
From the image you can see that the ball fired on the left that fire behind it, does not match the calculated trajectory. Im drawing the ball trajectory using an equation from a SO question, this is modified to take into consideration the box2d steps of 30 frames per second. This does calculate a valid trajectory but it does not match the actual trajectory of the ball, the ball has a smaller trajectory. I am applying a box2d force to the ball, this also has a density set and a shape. The shape radius varies depending on the type of ball. Im setting the start velocity in the touchdown event.

```
public class ProjectileEquation {

    public float gravity;
    public Vector2 startVelocity = new Vector2();
    public Vector2 startPoint = new Vector2();
    public Vector2 gravityVec = new Vector2(0,-10f);

    public float getX(float n) {
        return startVelocity.x * (n * 1/30f) + startPoint.x;
    }

    public float getY(float n) {
        float t = 1/30f * n;
        return 0.5f * gravity * t * t + startVelocity.y * t + startPoint.y;
    }

}

@Override
    public void draw(SpriteBatch batch, float parentAlpha) {
        float t = 0f;
        float width = this.getWidth();
        float height = this.getHeight();

        float timeSeparation = this.timeSeparation;

        for (int i = 0; i < trajectoryPointCount; i+=timeSeparation) {
            //projectileEquation.getTrajectoryPoint(this.getX(), this.getY(), i);
            float x = this.getX() + projectileEquation.getX(i);
            float y = this.getY() + projectileEquation.getY(i);

            batch.setColor(this.getColor());
            if(trajectorySprite != null) batch.draw(trajectorySprite, x, y, width, height);

           // t += timeSeparation;
        }
    }

public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                if(button==1 || world.showingDialog)return false;
                touchPos.set(x, y);
                float angle = touchPos.sub(playerCannon.position).angle();
                if(angle > 270 ) {
                    angle = 0;
                }
                else if(angle >70) {
                    angle = 70;
                }
                playerCannon.setAngle(angle);
                world.trajPath.controller.angle = angle;
                float radians =  (float) angle * MathUtils.degreesToRadians;
                float ballSpeed = touchPos.sub(playerCannon.position).len()*12;
                world.trajPath.projectileEquation.startVelocity.x = (float) (Math.cos(radians) * ballSpeed);
                world.trajPath.projectileEquation.startVelocity.y = (float) (Math.sin(radians) * ballSpeed);
                return true;
            }

public CannonBall(float x, float y, float width, float height, float damage, World world,  Cannon cannonOwner) {
        super(x, y, width, height, damage, world);
        active = false;
        shape = new CircleShape();
        shape.setRadius(width/2);

        FixtureDef fd = new FixtureDef();
        fd.shape = shape;
        fd.density = 4.5f;
        if(cannonOwner.isEnemy) { //Enemy cannon balls cannot hit other enemy cannons just the player
            fd.filter.groupIndex = -16;
        }
        bodyDef.type = BodyType.DynamicBody;
        bodyDef.position.set(this.position);

        body = world.createBody(bodyDef);
        body.createFixture(fd);
        body.setUserData(this);
        body.setBullet(true);
        this.cannonOwner = cannonOwner;
        this.hitByBall = null;
        this.particleEffect = null;
    }

  private CannonBall createCannonBall(float radians, float ballSpeed, float radius, float damage)
    {
        CannonBall cannonBall =  new CannonBall(CannonEnd().x, CannonEnd().y, radius * ballSizeMultiplier, radius * ballSizeMultiplier, damage, this.world, this);
        cannonBall.velocity.x = (float) (Math.cos(radians) * ballSpeed);
        //cannonBall.velocity.x = (float) ((Math.sqrt(10) * Math.sqrt(29) *
            //  Math.sqrt((Math.tan(cannon.angle)*Math.tan(cannon.angle))+1)) / Math.sqrt(2 * Math.tan(cannon.angle) - (2 * 10 * 2)/29))* -1f;
        cannonBall.velocity.y = (float) (Math.sin(radians) * ballSpeed);
        cannonBall.active = true;
        //cannonBall.body.applyLinearImpulse(cannonBall.velocity, cannonBall.position);
        cannonBall.body.applyForce(cannonBall.velocity, cannonBall.position );
        return cannonBall;
    }

trajPath = new TrajectoryActor(-10f);
        trajPath.setX(playerCannon.CannonEnd().x);
        trajPath.setY(playerCannon.CannonEnd().y);
        trajPath.setWidth(10f);
        trajPath.setHeight(10f);
        stage.addActor(trajPath);

```

# Answer
The problem is that your trajectory is built from an analytical form, while your physics engine is using an erroneous numerical approximation. Here are 3 solutions:

1. **Make a kinematic projectile:** I don't know Box2D, but I'd guess there's a way to make a rigid body "kinematic," which would allow you to specify its position/velocity as a function of time. You would then just use the same logic you're using to draw the trajectory to place the projectile.
2. **Draw the trajectory using the same numerical integrator Box2D does:** A simpler solution is the inverse of that, where you'd recreate the integration scheme Box2D is using to numerically solve for the drawn trajectory. Assuming Box2D uses symplectic Euler integration (I think all the physics engines do), it'd look something like this, in pseudo-code:

```
while(ball.y > 0)
    ball.velocity += g * dt
    ball.position += ball.velocity * dt
    // draw ball
```
3. **Find a closed form solution:** The tidiest answer is to find a closed form solution to the Euler integration. I just ran through all the math and come up with:

```
def get_pos_at_nth_step(n)
    return x0 + n * ((0.5 * g * dt^2) * (n + 1) + v0 * dt)
```

where `x0` and `v0` are the initial position and velocity, respectively. This allows you to keep your code as it is, but end up with a trajectory equal to what your physics engine will find. Note that the solution won't work if Box2D doesn't use symplectic Euler, but you can take the same approach.
> 3 votes

---
Tags: android, physics, box2d
---


# Question
Title: How can I avoid false positives with "blow" input?
I’m working on a game which uses blow functionality to move an object in the game screen. This screen also has background music in it.

The problem is that the microphone is detecting the BGM as blow input and the object is being moved without any actual user input.

How can I avoid this kind of false positive?

# Answer
Consider a volume threshold.

The nature of "blow" input usually, on the small microphones used by devices with games that employ this mechanic (like phones or the Nintendo DS), seems to saturate the input range of the microphone. This results in a noisy, static-like sound with very consistently high amplitudes.

Knowing that, you may be able to get away with having the game sample a few points of the microphone input and compute an average amplitude for the sound. Then, check if that value is higher than some threshold value you set in your game code (possibly chosen by preprocessing your background music and choosing something well above its maximum volume).

Similar to how joysticks have "dead zones," this will help you avoid false positives in your audio input.

You could also try other, more complex techniques (such as subtracting out the BGM sound wave from the input a kind of noise-cancelling approach), but they may be too extensive for realtime operation on a mobile device. A volume threshold approach, as described above, is relatively cheap to perform.

You may find this link on microphone input in Unity relevant.
> 4 votes

---
Tags: unity, iphone, sound
---


title: Smooth Biome transitions with tile map?

text:
# Question
Title: Smooth Biome transitions with tile map?
I'm using a simplex noise system to generate height maps for an "infinite" 2d world map. It works perfectly - I can define which tile belongs at which height value, etc.

However, I'm trying to add in biomes - I want different areas of the map to use tiles exclusive to that "biome".

I've tried generating a second noise value divided by a larger number so that I can generate very large areas. That noise value determines the biome, and the noise value for tiles determines the tile inside that biome. This works ok - but when the same noise value means different tiles in each biome, then you wind up with very ugly cut-off lines between biomes.

I tried adding the biome noise and tile noise together and only selecting the tile based on those. The edges were smoother, but there really was no actual use of the biome code - just tiles locked to unique noise values, never overriding each other.

What's a better way to do this, so that biome boundaries follow "features" of the terrain? I want them to be fairly large, but not cut through a "mountain" - the boundary should follow the natural curvature of the height map values.

# Answer
> 4 votes
You should be including the elevation in your biome generation (higher elevation reduces temperature, and above a certain height, reduces moisture). See this question and my answer for more details on that. Basically, you should add multiple large noise values, for different aspects of the terrain. You can get more detailed and apply wind patterns that carry moisture from wet areas and deposit it in dry areas. The wind would be blocked by high elevation, creating deserts on the other side of the mountains, similar to what happens in real life.

If you want even smoother transitions (visually), you'll need to make tiles to represent the transition. You may consider creating textures for these tiles on-the-fly with texture blending. Blend the two textures of the bordering biomes based on the percentages each has in that location.

---
Tags: procedural-generation
---


title: Dynamic Shapes and dynamic animations

text:
# Question
Title: Dynamic Shapes and dynamic animations
I saw this video: Video
And now I am curious about the following: How can you achieve dynamic forms like they are shown in this video.
What I mean is: Do you need to have some "base" models which can be just linked together? Or is it possible to generate these 3D models "on the fly"?

If yes: How could that be done?
And: Is something like that as well possible in 2D?

And: How can you do animations, like (some) in the video? Because it seems as if the body parts of the creatures work together more or less correctly. As well here is the question: Would this be possible in 2D?

# Answer
> 0 votes
It's not possible to create them on the fly. What you can do is copy the same model thousand times in the memory, and make them slightly different. Then you just choose correct model for each frame.

One copy of the model per frame eats large amount of memory. To reduce memory consumption, you can choose one model per 2 seconds of animation, and interpolate the frames in between. You'll need a time range \[a..b\] and a function m(a) and m(b) gives you the models for the keyframes. Then shader interpolates the points between m(a) and m(b).

Same features work in 2d and 3d.

---
Tags: 2d, 3d, graphics, models
---


title: Building triangle adjacency data

text:
# Question
Title: Building triangle adjacency data
Given a list of triangle indices, how exactly does one go about converting that to a list of indices with adjacency for a geometry shader?

Note that we're strictly talking about *indices* here - vertices are present, but we're going to focus solely on indices, because we can use them to match duplicate vertices without having to get into floating-point comparisons and epsilons - that work has already been done.

I know that for any given triangle in the list, indices {0, 1}, {1, 2} and {2, 0} (or {n, n+1}, {n+1, n+2}, {n+2, n} if you prefer) of it form it's edges; the index list is well-formed and respects winding order correctly.

I know that for any given such edge, we can search the entire list for another triangle that uses two of those indices, and the third index of that triangle is the one to use for completing the adjacent triangle for that edge.

I know that in the adjacency list each original triangle is represented by 6 indices, the original indices go into slots 0, 2, 4; the new indices to complete the adjacency go into slots 1, 3, 5. The index to complete for edge {0, 1} goes into slot 1, the index to complete for edge {1, 2} goes into slot 3, the index to complete for edge {2, 1} goes into slot 5.

What have I tried?

I've tried brute-forcing it, and yes, that will work, but I'm after a more elegant approach.

I've tried Eric Lengyel's edge list builder, but (1) it doesn't seem to respect the original triangle order, (2) it doesn't seem to respect winding order, (3) it's as clear as mud where to go next after you've built the edge list, and (4) I've a suspicion of sample code that has such obvious glaring errors as "triangleIndex" versus "faceIndex" - did the author even compile the code, never mind run it to verify it?

So -- any suggestions or pointers from here on?

# Answer
> 12 votes
I would try using a hash table for this (for instance, `std::unordered_map` if you're in C++). Build a hash table that maps from a half-edge (expressed as a pair of indices, in order) to the third index of the triangle the half-edge belongs to.

This can be built by simply iterating over the triangle list and adding each triangle's three half-edges to the hash table. If your initial index list had a pair of adjacent triangles, (0, 1, 2, 2, 1, 3), you'd end up with a hash table containing:

```
(0, 1) -> 2
(1, 2) -> 0
(2, 0) -> 1
(2, 1) -> 3
(1, 3) -> 2
(3, 2) -> 1

```

Note that edges (1, 2) and (2, 1) both appear in the table, representing the two sides of the edge, and pointing to the third vertex of each of the two triangles.

Then, to build the adjacency data all you have to do is iterate over the triangle list again, and query each triangle's edges with the opposite winding. So when processing triangle (0, 1, 2) you'd query edges (1, 0), (2, 1), and (0, 2). This will find the opposite vertex of each edge, if it exists.

# Answer
> 2 votes
Look at the half-edge data structure.

The idea roughly is that you store a list of *half edges*, e.g. the half of a particular edge attached to a particular face. This structure then also stores information about the corresponding half-edge for the adjoining face.

The data structure makes queries about connectivity, adjacency, and so on very efficient. There are algorithms to generate the data efficiently, though not necessarily "game run-time" efficiently (you'll probably want to do this offline in your asset pipeline).

See also these blog posts. I believe the structure and algorithms are also in Real-Time Collision Detection, but I don't recall for sure and dont' have a copy at the office.

---
Tags: algorithm, 3d-meshes
---


# Question
Title: XNA - how to prevent a sound from looping
So in XNA I have this code: Variables:

```
SoundEffect optionSelected;

```

In the `LoadContent()` method:

```
optionSelected = Content.Load<SoundEffect>("gameSounds\\selectOption");

```

In the `Update()` method:

```
optionSelected.Play();

```

So when it comes time for the sound to play it never stops looping. I want to hear it only once. How to achieve that? Thanks in advance!

# Answer
> 2 votes
Well if you are calling Play() every time the update loop runs it will play each time the game updates. However ignoring that to stop it looping you'd do

```
optionSelected = Content.Load<SoundEffect>("gameSounds\\selectOption");
optionSelected.IsLooped=false;

```

Hope that helps

EDIT: From the comment thread the solution would be to add a keypress event listener and call Play() when the desired key is pressed.

---
Tags: xna, c#, sound, sound-effects
---


# Question
Title: HTML5 Jump and Run Game Performance issues
we're developing a HTML5/Javascript jump and run game and therefore we have developed our own gameframework. It consists of following most important structures:

* Stage/Scene/Layer: divs
* ObjectEntites/Rectangle/Sprite: canvas

In the gameloop things get moved by calculating an offset value: e.g. if we place a coin and this coin moves through the screen, it gets a new offset in each gameloop-call. The dirty area of the coin is cleared in the canvas and the coin is repainted. We pay attention that we just draw at int-values (no floating point).

Unfortunately we have some performance issues now and can't figure out why our macbook pro's are running hot while playing the game.

Are the drawing operations so crucial? We have layered Canvas, so just moving stuff gets repainted and even not the whole canvas but just dirty-areas get cleared.

IStat shows following values while playing the game: Memory module A1 and Heatsink B get up to 60° and the rpm-Value of the Fans increases up to 3000-4000. In firefox we see these values:

And chrome shows us this, where we also see how cpu increases:

Do you have any idea how to check performance of our game, how to find bottlenecks or general tips? We have searched for canvas performance, used firebug profiler... We'd be grateful for any advice!

# Answer
> 4 votes
I recently watched a Google I/O 2012 video (http://www.youtube.com/watch?v=Prkyd5n0P7k) which talks about using an off-DOM canvas to perform your rendering, then "blitting" that canvas to an on-DOM canvas for final presentation. The speaker indicates their game saw a 30X performance increase simply by using an off-DOM canvas. YMMV, but maybe this will help you out.

# Answer
> 2 votes
It doesn't seem that you have a real issue.

The exact amount depends on the browser, but pretty much all over the line canvas is a compute expensive tool relative to the number of pixel you push through.

Your CPU gets hot, that is to be expected if you do anything moderately complex with a canvas.

I'm not saying that there necessarily isn't something smart you can do to decrease the processing required, but from the very moderate amount of information you give about your game I don't see any red flags.

# Answer
> 0 votes
Moving canvas is generally slow: differents browser has different performance issue, but moving just a big background image in enought to slow down the frame rate.

If you are supposed to perform real time, i suggest you to use webGL or equivalent.

How to check performance:

* Time in drawing SVG: monitoring all changes may help to know what operation is expensive. Also check that you optimize your code with: id = mySvg.suspendRedraw(x) and mySvg.unsuspendRedraw(id). See http://dschulze.com/blog/articles/4/efficient-redrawing-on-svg-or-why-suspendredraw-is-a-lie and set svg quality to low/fast.
* Time in database: never mix lot of rows with lot of data per rows. Divide queries in sub-queries that get ids and then get only interesting rows.
* Javascript usually does not take lot of time, but if you expect a function is taking lot of time, monitoring it and try to optimize it (for example with asm.js)

# Answer
> 0 votes
If i understand well you have all your gfx in canvas.
So it doesn't seem difficult to have the behaviour of the divs handled by some hand made class that will handle scene/layers. This way you can have the whole scene draw on a single canvas and avoid costly dom layout computations.

You might even have the context do a part of the job for you :

```
   // takes x,y,scale and a list of elements (which might be Scene)
   function Scene(x,y, scale) {
       this.elements = Array.prototype.slice.call( arguments, 0);
       this.x = x;
       this.y = y;
       this.scale=scale;
   }

   Scene.prototype.draw(ctx) {
       ctx.save();
       ctx.translate(this.x, this.y);
       if (this.scale !=1) ctx.scale(this.scale, this.scale);
       // rotate clip, ... here
       for (var i=0; i<this.elements.length; i++) {
           this.elements.draw(ctx);
       }
       ctx.restore()
   }

```

or you can have the elements compute their position based on their parent's.

Anyway i bet it will be much faster.

---
Tags: javascript, html5, performance
---


title: Translation over a vector trajectory

text:
# Question
Title: Translation over a vector trajectory
I'm working on a particle field system, where the particles can go from a point of the map, to another point of the map, using an angle (with sin and cos).

By now, I can calculate the vector by defining an angle using the cos and sin

```
float X = sin(DEGREES_TO_RADIANS(45));
float Y = cos(DEGREES_TO_RADIANS(45));

```

That forms a trajectory, like in this image: (Trajectory in red)

I need the particle to follow that trajectory, to move over that trajectory and arrive to the the vector (X,Y).

How can I translate the object ONLY over the red trajectory?

# Answer
> 0 votes
If you're asking how you can move a particle from the point 0,0 to the point X,Y. You have to first ask yourself how long that particle is going to take to get to that point. Give it a value in units per second. For instance if it takes one second then it goes 1 unit per sec, that's your speed. Multiply your speed by the vector you created with the cos/sin equation, this is your velocity vector.

Start the particle at 0,0. Then every frame you're going to update the particle's position by adding the current position of the particle with the velocity vector multiplied by the delta time (that's the time in seconds between frames). For instance at 30 fps the detla is 0.0333...

---
Tags: trajectory, mathematics
---


# Question
Title: Where can I meet other independent game developers?
I live in a large urban area and suspect there are groups of independent game developers that meet to discuss games and just hang out. Are there any clubs or groups or associations or whatever for indie devs?

# Answer
**Yes! Indie developers tend to be very social.** Without knowing which city you live in, it's tough to say what's available, but check out the IGDA's chapter list:

Though these events include students and non-indie industry members, your fellow indies will often be there in force. For example, here in Boston, we have the Boston Postmortem group which meets monthly:

And there's a large enough dev scene in the Cambridge/Boston area such that we even have a monthly meeting specifically for indies:

Generally speaking, once you start networking with other local indies, you'll find out about everything that's going on in your city, whether you want to or not.

Good luck!
> 12 votes

# Answer
TIGSource has a forum for get-togethers at http://forums.tigsource.com/index.php?board=15.0
> 10 votes

# Answer
http://gamedev.meetup.com/
> 8 votes

# Answer
If you're in NYC: http://www.nycgameindustry.com/
> 4 votes

# Answer
In San Francisco:

http://www.meetup.com/sfgamedevelopers/

and

http://www.unknownworlds.com/postmortem

Both very active monthly meetups.
> 2 votes

# Answer
Portland, Oregon, USA: http://pagdig.org has a monthly get together
> 2 votes

# Answer
For anyone in Seattle please join us at the Seattle Games Co-op. We currently meet twice a month, once to present a topic of interest -- say Blender or Linear Algebra -- and once just to hang out and have a beer.

We're always looking for fellow game developers to participate and we're planning a lot of great stuff for the future, so get involved now!
> 1 votes

# Answer
For the Cambridge, UK indie scene, including Chris Delay of Introversion and the creator of VVVVVV, see Cambridge Friendship Club.
> 1 votes

# Answer
In Chicago, in addition to the IGDA chapter, there is also Indie City Games.
> 1 votes

# Answer
In San Francisco I would recommend the http://www.meetup.com/SFGameMonetization/

They run workshops and regular drink meets. There is a good mix of indie and established developers that attend.
> 0 votes

---
Tags: dev-groups
---


# Question
Title: Is it legal to make a game out of a book?
I want to learn what legal constraints are on the copyrighted material.

If I want to make a Quidditch (the fictional game in Harry Potter series) game, should I pay some kind of copyright to the book's writer? Where can I learn about these things, without being a lawyer :) ?

# Answer
You can't copyright ideas or game mechanics. That much should be obvious from the number of "clone" games around. So you can make a game that exactly followed Quidditch rules without much worry.

Use of copyrighted material (whole chunks of Harry Potter's text explaining the rules of Quidditch, for example) is generally not possible without the copyright owner's permission.

Use of small snippets of copyrighted material (the name "Quidditch", for example) is a grey area. Possibly it would be OK because of "fair use" exceptions, but it would depend on jurisdictions and how willing either side is to file/defend a lawsuit. Also Quidditch might be trademarked - which is separate from copyright and would bring in a whole new set of legal complexity. You should probably consult a lawyer if you plan on entering this territory.
> 1 votes

---
Tags: game-design, legal, books, copyright, licensing
---


# Question
Title: Registering and (more importantly) Unregistering with Message Server
I've finally implemented an extendable message class and messageServer class. The message class dynamically assigns a unique static ID to each derived message type (ex. ObjectCreatedMessage might be assigned id = 1). The actual message data is a member of the derived class.

Messages can be pushed to MessageServer class by upcasting to MessageBase\*.

Systems (or anything) can subscribe to Message Server by passing a std::function to:

```
typedef std::function<void(MessageBase*)> Callback;
void registerCallback(int messageType, Callback callback);

```

When MessageServer is processing messages, it pops a message off the queue, checks the message type, then sends the message to each callback function registered to that type.

---

My Questions are:

1. Is this efficient?
2. How could I implement an "unregister" function? std::functions can't be compared by equality.
3. What is a smart way to handle the callback failing? (perhaps the registered object went out of scope so the function pointer is undefined)

# Answer
Using callbacks can be one way to decouple parts of a program. They're often used in GUI interaction because this interaction is generally sporadic and not something that happens excessively. So the caveats and downsides to callbacks don't out weigh the benefits of them.

If you intend to use callbacks for event handling, be mindful that emitting function callbacks in tight loops could be detrimental to your instruction and data cache.

Lastly, don't over estimate the power of polling. Often it is far more efficient to have an event be raised and placed into a queue/buffer. At future points in your code, you poll to determine what events have been raised that are of interest. This approach may be easier to apply parallel processing constructs against than if you used an immediate callback concept.
> 1 votes

---
Tags: c++, component-based, entity-system, messaging
---


# Question
Title: XNA Zoom in/out on model instead of scaling the model
I'm trying to implement zoom in/out functionality into my game. I can change the cameraDistance value with the Z and X keys. Instead of zooming, it looks like the model is scaled smaller or larger (moves closer or farther away from the camera). Instead, the camera should move closer to or farther away from the model.

Below are my view and projection matrix. cameraDistance is the value that seems to 'scale' the model. After days of messing around, I realize (yes after days!:)) that I should never change this value.

```
Matrix view = Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) *
                      Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
                      Matrix.CreateTranslation(0, -45, 0) *
                      Matrix.CreateLookAt(new Vector3(0, forwardRotation, -cameraDistance), new Vector3(0, 0, 0), Vector3.Up);

        Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1, 10000);

```

So instead of changing the cameraDistance value, I think I should change my *CameraPositionOffset*. Below is my updateCamera method

```
        // This vector controls how much the camera's position is offset from the
        // sphere. This value can be changed to move the camera further away from or
        // closer to the sphere.
        Vector3 CameraPositionOffset = new Vector3(0, 10, 90);

        // This value controls the point the camera will aim at. This value is an offset
        // from the sphere's position. middle value is distance from surface
        Vector3 CameraTargetOffset = new Vector3(0, 27, 0);

    private void UpdateCamera(GameTime gameTime)
        {

            // start arcball
            float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            // mouse movement
            MouseState currentMouseState = Mouse.GetState();
            if (currentMouseState != originalMouseState)
            {

                float xDifference = (currentMouseState.X - originalMouseState.X);
                float yDifference = currentMouseState.Y - originalMouseState.Y;

                Mouse.SetPosition(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);
                if (Mouse.GetState().RightButton == ButtonState.Pressed)
                {
                    cameraRotation -= xDifference * 1.05f;
                    cameraArc += yDifference * 1.025f;

                    // Limit the arc movement.
                    if (cameraArc > 90.0f)
                        cameraArc = 90.0f;
                    else if (cameraArc < -90.0f)
                        cameraArc = -90.0f;
                }
            }

            // Check for input to zoom camera in and out.
            if (currentKeyboardState.IsKeyDown(Keys.Z))
                cameraDistance += time * 0.25f;

            if (currentKeyboardState.IsKeyDown(Keys.X))
                cameraDistance -= time * 0.25f;

            // Limit the camera distance.
            if (cameraDistance > 500)
                cameraDistance = 500;
            else if (cameraDistance < 0.001f)
                cameraDistance = 0.001f;

            /// end of arcball

            // The camera's position depends on the sphere's facing direction: when the
            // sphere turns, the camera needs to stay behind it. So, we'll calculate a
            // rotation matrix using the sphere's facing direction, and use it to
            // transform the two offset values that control the camera.
            Matrix cameraFacingMatrix = Matrix.CreateRotationY(sphereFacingDirection);
            Vector3 positionOffset = Vector3.Transform(CameraPositionOffset, cameraFacingMatrix);

            Vector3 targetOffset = Vector3.Transform(CameraTargetOffset, cameraFacingMatrix);

            // once we've transformed the camera's position offset vector, it's easy to
            // figure out where we think the camera should be.
            Vector3 cameraPosition = spherePosition + positionOffset;

            // We don't want the camera to go beneath the heightmap, so if the camera is
            // over the terrain, we'll move it up.
            if (heightMapInfo.IsOnHeightmap(cameraPosition))
            {
                // we don't want the camera to go beneath the terrain's height +
                // a small offset.
                float minimumHeight = heightMapInfo.GetHeight(cameraPosition) + CameraPositionOffset.Y;

                if (cameraPosition.Y < minimumHeight)
                {
                    cameraPosition.Y = minimumHeight;
                }
            }

            // next, we need to calculate the point that the camera is aiming it. That's
            // simple enough - the camera is aiming at the sphere, and has to take the
            // targetOffset into account.
            Vector3 cameraTarget = spherePosition + targetOffset;

            // with those values, we'll calculate the viewMatrix.
            viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, new Vector3(0.0f, 1.0f, 0.0f));

        }

```

In summary: I want to move the camera farther or closer to the model, and keep the position and scale of the model.

How should I go about this?

# Answer
Have you tried changing the field of view component of your projection matrix? Your current field of view is set to MathHelper.PiOver4 if swap this out for a modifiable value you should be able to zoom in and out.
> 1 votes

---
Tags: xna, camera, scale, orbit
---