title: Rasterization Rules and States

text:
# Question
Title: Rasterization Rules and States
This thread directly concerns lightmap generation; however, indirectly, the rasterization of polygons by the GPU.

I am currently generating lightmaps using a pixel shader. To the shader I send 3 lightmap UV coordinates per mesh face. Those UV coordinates are directly rendered onto a lightmap texture( by setting the lightmap as the render target ). The vertex shader looks like this:

```
// ---------------------------------------------------------------
// Vertex Declaration
// ---------------------------------------------------------------
struct VS_INPUT_Std
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 tUV : TEXCOORD0; // diffuse UV coordinates
    float2 lUV : TEXCOORD1; // lightmap UV coordinates
};
//--------------------------------------------------------------//
// LightMap Pass
//--------------------------------------------------------------//
PS_INPUT_Std LightMapPass_Vertex_Shader( VS_INPUT_Std Input )
{
    PS_INPUT_Std Output = ( PS_INPUT_Std )0;

    Output.Position = float4( ( Input.lUV.x * 2 ) - 1, ( Input.lUV.y * -2 ) + 1, 0, 1 );
    Output.Normal = mul( Input.Normal, mW );
    Output.Pos3 = mul( Input.Position, mW );
    Output.tUV = Input.tUV;
    Output.lUV = Input.lUV;
    return Output;
}

```

The pixel shader returns a color based on light contribution. The result of the lightmap generation for this test mesh looks like this:

The light for this scene is floating in the center of the room...

The problem is that the lightmap has 'cracks' due to the rasterization of polygons by the GPU. It appears as though that for a given face lightmap pixels are not included during rasterization because their pixel centers do not fall within the bounds of the face's UV coordinates despite the fact that the face overlaps those pixels. As a result a black( unset ) pixel is rendered and effectively blackens the diffuse color of the mesh during texture modulation. Here is a screenshot:

Here is a screenshot of an auxiliary window which shows both the lightmap and a selected mesh face. This is generated by rendering the UV coordinates of the mesh face over a screen quad of the lightmap:

As you can see, the mesh face( green ) extends beyond the pixels rendered during generation of the lightmap. It seems as though those pixels were excluded during rasterization. Most of the problem faces are narrow in dimension. I thought that I could fix this by increasing the size of the lightmap, however, this doesn't always work...

Here is the entire lightmap:

Can I change a rasterization state to allow pixels under certain conditions?

EDIT: Lightmap and Deferred Shading Cube Pics

# Answer
The lightmap shouldnt be dissasociated from the vertex information.

if the vertices are lined up to display no cracks and no rounding errors coming from the CPU (i.e. object positions + vertex positions interpolation) they they won't let anything through, the edges have to be aligned and no triangle intersections.

If the mesh doesnt have cracks, nothing will.
> 1 votes

# Answer
Conservative rasterization is a fix for this problem. Thanks to Nathan Reed's comments, in preparation for the generation of a lightmap, I dilate the uv coordinates and recalculate they're associated positions based on the dilation.

For each triangle:

1. Compose an array of edges in uv space.
2. For each edge:

a. Compute the cross product using the edge direction vector and a point that lies on the edge. The resulting vector is the edge's normal(It should face away from the triangle, perpendicular to the edge direction vector)

b. Compute the edge center position in uv space.

c. Translate the edge center position along the edge normal by a distance of a half pixel(or desired dilation amount in uv space...it should definitely be a value between 0 and 1).
3. After all edges have been translated, calculate the intersection points between each edge to determine the new uv coordinates for the triangle.
4. Adjust the triangle's position data. Each position should be dilated as well.
5. The dilation of triangles with acute angles may cause too great a change in the uv coordinates. You should calculate an axis-aligned bounding box for the original triangle in uv space. Then dilate the AABB by the same amount as the triangle. When computing the lightmaps just make sure that the uv coordinates lie within the AABB, if not then discard the pixel.

Here is code in c++:

```
struct VertexData
{
D3DXVECTOR3 position;
D3DXVECTOR3 normal;
D3DXVECTOR2 uv;
};

struct MeshData
{
// vertex data
VertexData* vertices;

// index data
int* indices;

// attribute data
int* attributes;

// face count
int ncFaces;
};

// mesh data contains vertex data, index data, face count...
MeshData* pMeshData = GetMeshData();

// face count
int ncFaces = data.ncFaces

// dilation amount for my use is a half-pixel
D3DXVECTOR2 vHalfPixel( 0.5f / ( float )LightMapWidth, 0.5f / ( float )LightMapHeight );

for(int iFace = 0; iFace < 3 * ncFaces; iFace += 3)
{

// edge uv coordinates
D3DXVECTOR3 vUV[3];

// edge normals in uv space
D3DXVECTOR3 vEdgeNormal[3];

// edge center positions in uv space
D3DXVECTOR3 vEdgeCenter[3];

// distance of edge normal from origin
float fD[3];

// axis-aligned bounding box in uv space
D3DXVECTOR4 vAABB;

// vertices for the current triangle(face)
VertexData vertices[]
{
pMeshData->vertices[pMeshData->indices[iFace + 0]],
pMeshData->vertices[pMeshData->indices[iFace + 1]],
pMeshData->vertices[pMeshData->indices[iFace + 2]],
}

// store original vertex data
VertexData originalVertices[3];
memcpy(originalVertices, vertices, 3 * sizeof(VertexData));

// place each uv coordinate in a 3 component vector for cross product calculation
memset( vUV, 1, 3 * sizeof( D3DXVECTOR3) );
memcpy( &vUV[ 0 ], &vertices[ 0 ].uv, sizeof( D3DXVECTOR2 ) );
memcpy( &vUV[ 1 ], &vertices[ 1 ].uv, sizeof( D3DXVECTOR2 ) );
memcpy( &vUV[ 2 ], &vertices[ 2 ].uv, sizeof( D3DXVECTOR2 ) );

// compute edge direction vectors
D3DXVec3Normalize( &vEdgeNormal[ 0 ], &( vUV[ 1 ] - vUV[ 0 ] ) );
D3DXVec3Normalize( &vEdgeNormal[ 1 ], &( vUV[ 2 ] - vUV[ 1 ] ) );
D3DXVec3Normalize( &vEdgeNormal[ 2 ], &( vUV[ 0 ] - vUV[ 2 ] ) );

// dilate each of the 3 edges that make up the triangle
for( UINT j = 0; j < 3; ++j )
{
// compute edge normal( perpendicular to edge )
D3DXVec3Cross( &vEdgeNormal[ j ], &vEdgeNormal[ j ], &vUV[ j ] );

// set z component to 0( we're only interested in 2D vectors )
vEdgeNormal[ j ].z = 0;

// normalize edge normal
D3DXVec3Normalize( &vEdgeNormal[ j ], &vEdgeNormal[ j ] );

// compute distance from origin
fD[ j ] = -D3DXVec3Dot( &vEdgeNormal[ j ], &vUV[ j ] );

// get edge center point
vEdgeCenter[ j ] = fD[ j ] * vEdgeNormal[ j ];

// translate edge center
vEdgeCenter[ j ].x += vEdgeNormal.x * vHalfPixel.x;
vEdgeCenter[ j ].y += vEdgeNormal.y * vHalfPixel.y;

// calc new dist from origin
fD[ j ] = -D3DXVec3Dot( &( -vEdgeNormal[ j ] ), &vEdgeCenter[ j ] );

// compose plane
vEdgeNormal[ j ] = D3DXVECTOR3( vEdgeNormal[ j ].x, vEdgeNormal[ j ].y, fD[ j ] );
}

// compute intersection points
D3DXVec3Cross( &vUV[ 0 ], &vEdgeNormal[ 2 ], &vEdgeNormal[ 0 ] );
vertices[ 0 ].vUV = *( D3DXVECTOR2* )&vUV[ 0 ] / vUV[ 0 ].z;

D3DXVec3Cross( &vUV[ 1 ], &vEdgeNormal[ 0 ], &vEdgeNormal[ 1 ] );
vertices[ 1 ].vUV = *( D3DXVECTOR2* )&vUV[ 1 ] / vUV[ 1 ].z;

D3DXVec3Cross( &vUV[ 2 ], &vEdgeNormal[ 1 ], &vEdgeNormal[ 2 ] );
vertices[ 2 ].vUV = *( D3DXVECTOR2* )&vUV[ 2 ] / vUV[ 2 ].z;

// adjust vertex position to account for uv offset
for( UINT j = 0; j < 3; ++j )
vertices[ j ].position = UVPOS( originalVertices[ 0 ]->position, originalVertices[ 1 ]->position, originalVertices[ 2 ]->position, originalVertices[ 0 ]->uv, originalVertices[ 1 ]->uv, originalVertices[ 2 ]->uv, *( D3DXVECTOR2* )&vertices[ j ].vUV );

// initialize aabb
vAABB.x = vertices[ 0 ]->uv.x;
vAABB.y = vertices[ 0 ]->uv.y;
vAABB.z = vertices[ 0 ]->uv.x;
vAABB.w = vertices[ 0 ]->uv.y;

// determine aabb
for( UINT j = 1; j < 3; ++j )
{
vAABB.x = min( vAABB.x, vertices[ j ]->uv.x );
vAABB.y = min( vAABB.y, vertices[ j ]->uv.y );
vAABB.z = max( vAABB.z, vertices[ j ]->uv.x );
vAABB.w = max( vAABB.w, vertices[ j ]->uv.y );
}

// adjust aabb by dilation amount
vAABB.x -= vHalfPixel.x;
vAABB.y -= vHalfPixel.y;
vAABB.z += vHalfPixel.x;
vAABB.w += vHalfPixel.y;

// clamp AABB
vAABB.x = Clamp( vAABB.x, 0.0f, 1.0f );
vAABB.y = Clamp( vAABB.y, 0.0f, 1.0f );
vAABB.z = Clamp( vAABB.z, 0.0f, 1.0f );
vAABB.w = Clamp( vAABB.w, 0.0f, 1.0f );
}

// This method takes as input:
// Triangle position data
// Triangle uv coordinates
// and a test uv coordinate(tx)
// The position data and uv coordinates are used to determine the position of the test uv coordinate with respect to the triangle
// the calculations in this method were found online a number of years ago and I can't right now reference the source...my apologies
D3DXVECTOR3 UVPOS( const D3DXVECTOR3 &v1, // tri position 1
                          const D3DXVECTOR3 &v2, // tri position 2
                          const D3DXVECTOR3 &v3, // tri position 3
                          const D3DXVECTOR2 &t1, // tri uv 1
                          const D3DXVECTOR2 &t2, // tri uv 2
                          const D3DXVECTOR2 &t3, // tri uv 3
                          const D3DXVECTOR2 &tx ) // test uv coordinate
{
    float i;
    float s;
    float t;
    D3DXVECTOR3 r;
    i = 1 / ( ( t2.x - t1.x ) * ( t3.y - t1.y ) - ( t2.y - t1.y ) * ( t3.x - t1.x ) );
    s = i * ( ( t3.y - t1.y ) * ( tx.x - t1.x ) - ( t3.x - t1.x ) * ( tx.y - t1.y ) );
    t = i * ( -( t2.y - t1.y ) * ( tx.x - t1.x ) + ( t2.x - t1.x ) * ( tx.y - t1.y ) );
    r.x = v1.x + s * ( v2.x - v1.x ) + t * ( v3.x - v1.x );
    r.y = v1.y + s * ( v2.y - v1.y ) + t * ( v3.y - v1.y );
    r.z = v1.z + s * ( v2.z - v1.z ) + t * ( v3.z - v1.z );
    return r;
}

```
> 1 votes

---
Tags: textures, hlsl, uv-mapping, lightmap
---


# Question
Title: How to rotate and move a model in the direction it is facing?
I am not using Unity or XNA. Eventually, I will probably use OpenTK for graphics. But for the concept of a game I'm writing, I am using the console for keyboard input and visual logging of events, etc.

I am also using a WPF window to display world and player data.

*Update: I am using 0 deg as North. I understand that this may not be 'standard'. I don't mind switching to the standard where 0 deg is East if necessary.*

The standard keys are W, A, D, S and Left/Right arrows.
W: move forward
A: move left
D: move right
S: move backward

L Arrow: rotate left 2.5 (degrees)
R Arrow: rotate right 2.5 (degrees)

I am new to the *physics* of movement within a 2D space (as if I am looking down from overhead). What I have is a `World` and `Player` model; each `Player` encapsulates an `IEntityVector` object.

*Edit: added the conversion to radians in the following method. Seems to work more correctly as long as the orientation is 0, 90, 180, or 270 degrees.*

**Move Model:**

```
  public static void MoveEntity (Guid EntityId, Direction Direction) {
     var entityVector = default(IEntityVector);
     var gameWorld = default(World);

     if (entityRealms.TryGetValue(EntityId, out gameWorld)) {
        if (gameWorld.entityVectors.TryGetValue(EntityId, out entityVector)) {
           var heading = (Math.PI/180) * entityVector.Heading;

           switch (Direction) {
              case Direction.Forward:
                 entityVector.AddMovementX((float)Math.Sin(heading));
                 entityVector.AddMovementY((float)Math.Cos(heading));

                 break;
              case Direction.Left:
                 entityVector.AddMovementX(-(float)Math.Cos(heading));
                 entityVector.AddMovementY((float)Math.Sin(heading));

                 break;
              case Direction.Right:
                 entityVector.AddMovementX((float)Math.Cos(heading));
                 entityVector.AddMovementY((float)Math.Sin(heading));

                 break;
              case Direction.Backward:
                 entityVector.AddMovementX((float)Math.Sin(heading));
                 entityVector.AddMovementY(-(float)Math.Cos(heading));

                 break;
              default:
                 break;
           }
        }
     }
  }

```

**Rotate Model:**

```
  public static void RotateEntity (Guid EntityId, float Heading) {
     var entityVector = default(IEntityVector);
     var gameWorld = default(World);

     if (entityRealms.TryGetValue(EntityId, out gameWorld)) {
        if (gameWorld.entityVectors.TryGetValue(EntityId, out entityVector)) {
           entityVector.Heading += Heading;
        }
     }
  }

```

#1 I am trying to understand the rotation first of all. If `Heading` is increased or decreased by 2.5 per rt/lf arrow key press, how do I keep the resulting value as a true degree value?

#2 How can I use the `Heading` degrees as the facing to properly move the entity?

Btw, here are the `AddMovement` methods:

```
  public static void AddMovementX (this IEntityVector Vector, float X) {
     var newPosition = Vector.Location.X + (X * Vector.Thrust);
     Vector.Location = new Vector(newPosition, Vector.Location.Y);
  }

  public static void AddMovementY (this IEntityVector Vector, float Y) {
     var newPosition = Vector.Location.Y + (Y * Vector.Thrust);
     Vector.Location = new Vector(Vector.Location.X, newPosition);
  }

```

# Answer
> 1 votes
After quite a headache and a lot of fumbling about, I have finally solved this using the WPF libraries - `WindowsBase.dll`, `PresentationCore.dll` \- for vectors, rotation, translation, etc. Also some correction to handling facing:

```
  public static void MoveEntity (Guid EntityId, Direction Direction) {
     var entityVector = default(IEntityVector);
     var gameWorld = default(World);

     if (entityRealms.TryGetValue(EntityId, out gameWorld)) {
        if (gameWorld.entityVectors.TryGetValue(EntityId, out entityVector)) {
           var heading = default(double);

           switch (Direction) {
              case Direction.Forward:
                 heading = entityVector.Heading;

                 break;
              case Direction.Backward:
                 heading = entityVector.Heading - 180;

                 break;
              case Direction.Right:
                 heading = entityVector.Heading - 90;

                 break;
              case Direction.Left:
                 heading = entityVector.Heading + 90;

                 break;
              default:
                 break;
           }

           heading *= Math.PI / 180;
           var direction = new Vector(Math.Cos(heading), Math.Sin(heading));
           var translate = new TranslateTransform(direction.X * entityVector.Thrust, direction.Y * entityVector.Thrust);
           entityVector.Location = Vector.Add(entityVector.Location, new Vector(Math.Round(translate.X, 3), Math.Round(translate.Y, 3)));
        }
     }
  }

```

Also, removed the methods `AddMovementX` and `AddMovementY`.

---
Tags: c#, rotation, movement
---


# Question
Title: Scaling a GameObject for a progress bar representation
I am trying to implement a progress bar system for my game. I know that it could be done with Unity's OnGUI and scaling with width of the texture but I don't want it to be a GUI element because in my game we would have several progress bars for each specific item.

In the below image you can see two of the progress bars and they are textures mapped on to a plane.

The actual progress bar that needs to increase/ decrease in width is just a gameObject. I could just localScale and just scale it in the x direction of the gameobject but that scales in both directions. So scaling is not a solution. How do I make it work such that it I could control its width? Is there any other way I could implement this system? Or could I just use Unity's OnGUI for this purpose? Thing is this progress bars need to show up in the game on top of several gameOjects in the perspective camera view. So I am not sure if OnGUI would work for that. Any ideas?

I want something similar to what we see in games like LoL where they have health bars on top of the in game characters like in the image below

# Answer
> 1 votes
The easiest thing to do, I think, is asking your 3D artist to create a cube with the pivot point on the center of one of his faces instead of in the center of the cube. Than you'll be able to scale the cube along only one direction ( let's say his width) and obtain the effect you look.

Another option is to put a simple unity cube inside a parent empty game object, move the cube aside of the center of the parent, and then simply scale the parent object. Same final effect.

Hope it helps...

# Answer
> 2 votes
I would probably use a LineRenderer. You can manipulate the points.

> The Line Renderer \[...\] renders billboard lines that have width and can be textured. \[...\]

Otherwise, you can take the route you're currently going, but in addition to scaling it along local X, translate it along the local X as well in order to offset the difference.

---
Tags: unity, gui
---


title: Pathfinding with car steering

text:
# Question
Title: Pathfinding with car steering
Is there pathfinding algorithm which takes car steering into account?

I have large space where user can place cars (trucks actually) and other blocker objects. Objects can be placed vertically or horizontally oriented and have different sizes (may be 3x6 or 2x4 or other size). User needs to be able to select new location for any car - then I need to calculate how can that car move to selected location.

I have pathfinding working, and I can find paths with different size but only for square objects.

Update:

Pathfinding need to give only path that is possible with that type of car. For example on empty map with only one car, if user selects new location right next to its current location, car can't strafe or turn in place it has to either reverse and steer or do U turn or something. Also it must ensure that car orientation at end is what user requested.

# Answer
> 2 votes
There is!

You need to path find in a 3 dimensional space if the car is steering in a 2d space and use the third dimension as the cars angle. Then you could use A\* or any other graph path finding algorithm and you"re good to go. The algos I go with are usually probabilistic roadmap or rapidly exploring random trees to generate the graph and A\* to find a fast path.

Obviously you need to adjust the "collision space" or passable area differently for each angle of the vehicle you are moving. I usually use a low res 3d bit (2d for the plain and 1d for the angle) array to represent the passable area and then randomize vertices in the 3d-space made from the slices of adjacent 2d slices, each representing one specific angle. Since this is not 100% perfectly accurate (only 99%) I usually add a 2-3 bits thick border around obstacles to make it obvious the vehicle is not colliding with anything.

You need to know if there is a path between two vertices, for that you'll need to draw a trace line in that 3d space and check if it collides with 1 bits. This should be a question on it's own as there is a solution based on Bresenham's line algorithm.

Again to clarify, obstacles are calculated against the center of the "truck" in your case while taking the angle and shape of the track into account. Meaning that if the track is 5 units long and 2 units wide, and the center is less then two and a half units away from an obstacle, that area may be impassable depending on the angle of the track in that slice.

---
Tags: path-finding
---


# Question
Title: libGDX new TextureAtlas(filename) and new Texture(filename) drawing stale image data
I'm trying to draw an image using libgdx but no matter what I do, libgdx seems to insist on drawing a portion of an image I had loaded and used in an earlier game screen.

In my current game screen (class implements Screen), I have tried loading the image using both an atlas and loading it via the Texture class. However, when I draw the image in my render method, portions of an image that I had loaded previously are being displayed instead. Not the image that I am passing to the draw method!

I have tried both loading the image using a Texture Atlas and directly:

```
private TextureAtlas deckAtlas;
private TextureRegion aceHearts;
// In class constructor
deckAtlas = new TextureAtlas("deck.atlas");
aceHearts = deckAtlas.findRegion("ace-heart");

```

and:

```
Texture texture = new Texture("deck.png");
sprite = new Sprite(texture, 72, 0, 72, 100);

```

Depending on the method used above, I try to display by either:

```
game.batch.begin();
game.batch.draw(aceHearts, 100, 100);
game.batch.end();

```

Or:

```
game.batch.begin();
sprite.draw(game.batch);
game.batch.end();

```

where game is an instance of a class that extends Game and batch was initialized in that class's create method.
To start from the beginning, in my class that extends Game I call

```
setScreen(new MainMenu(this));

```

In Main Menu Screen, I load a skin using

```
skin = new Skin(Gdx.files.internal("uiskin.json"));

```

and create a bunch of Scene.2d UI widgets with that skin (the packed image that's loaded by the skin is contributing the image that is being drawn on my next screen when I don't want it to). Finally, I create the Screen in which I am having the above problems using

```
game.setScreen(new TableGame(game));

```

So to summarize, I am loading an image in a class that implements Screen, but that image never gets drawn to the screen. Instead, an image that I had used in the previous screen is being displayed instead. Any ideas why?

Thanks for any help.

I am using libGDX 1.3.1 (I think).

# Answer
> -1 votes
I think your code looks just fine, but the only thing that bothers me, is that you use the batch from Game class.

I think you should use new SpriteBatch for each new Screen and not using the one from Game class.

Or change your structure of code and have Game class which calls render function from LibGDX and from that render function call render functions from Screen class:

Game class:

```
//defining sprite batch and Screen object
private SpriteBatch batch;
private Screen screen = new Screen();
//RENDER FUNCTION
@Override
public void render(){
    screen.update(Gdx.graphics.getDeltaTime()); // CALLING THE UPDATE FUNCTION FROM SCREEN CLASS AND PASSING IN THE DELTA TIME
    screen.render(batch); // CALLING THE RENDER FUNCTION FROM SCREEN AND PASSING IN THE SPRITEBATCH
}

```

Screen class:

```
// defining the image
private Texture texture = new Texture("YOUR PATH");
private Sprite sprite = new Sprite(texture);

//RENDER FUNCTION
public void render(SpriteBatch batch){
    batch.begin();
    sprite.draw(batch,X,Y);
    batch.end();
}

//UPDATE FUNCTION
public void update(float deltaTime){
    // update stuff here
}

```

That's it! I hope that I was helpful and I strongly recommend you using the second way because the whole structure is much more organized. SORRY FOR BAD ENGLISH THOUGH!

---
Tags: android, libgdx
---


title: Errors when loading Assimp meshes

text:
# Question
Title: Errors when loading Assimp meshes
I am experiencing some oddities when loading meshes in Assimp. Some models render perfectly, while others are complete jumbles of triangles.

Some Example Images:

Teapot Correct \- Teapot Actual

Flower Correct \- Flower Actual

OBJ download links:

Teapot.obj \- Flower.obj

I've searched far and wide, and I cant seem to pin down the cause of this. I have noticed while debugging that the value of `ai_mesh->mNumVertices` differs from what Assimp Viewer or Blender display. `ai_mesh->mNumVertices` is *smaller* in the Teapot example by 156 vertices, and *larger* in the Flower example by 20 vertices. I've considered that Assimp post-processing may be causing the difference here. However, I'm using the EXACT same post-processing flags used in Assimp Viewer, copied directly from the source code. Here is my Mesh Loader:

```
mesh::mesh(aiMesh *ai_mesh, model* parent_model) : mesh()
{
    name_ = ai_mesh->mName.length != 0 ? ai_mesh->mName.C_Str() : "";

    // Get Vertices
    if (ai_mesh->mNumVertices > 0)
    {
        for (int ii = 0; ii < ai_mesh->mNumVertices; ii++)
        {
            aiVector3D ai = ai_mesh->mVertices[ii];
            glm::vec3 vec = glm::vec3(ai.x, ai.y, ai.z);
            vertices_.push_back(vec);
        }
    }

    // Get Normals
    if (ai_mesh->HasNormals())
    {
        for (int ii = 0; ii < ai_mesh->mNumVertices; ii++)
        {
            aiVector3D ai = ai_mesh->mNormals[ii];
            glm::vec3 vec = glm::vec3(ai.x, ai.y, ai.z);
            normals_.push_back(vec);
        };
    }

    // Get mesh indexes
    for (int t = 0; t < ai_mesh->mNumFaces; t++)
    {
        aiFace* face = &ai_mesh->mFaces[t];
        if (face->mNumIndices != 3)
        {
            std::cout << "[??] Mesh face with not exactly 3 indices, ignoring this primitive.\n";
            continue;
        }

        indices_.push_back(face->mIndices[0]);
        indices_.push_back(face->mIndices[1]);
        indices_.push_back(face->mIndices[2]);
    }
    material_ = parent_model->getMaterial(ai_mesh->mMaterialIndex);
}

```

And render function, just in case.

```
void mesh::render()
{
    material_->bind();

    glVertexPointer(3, GL_FLOAT, 0, &vertices_[0]);
    glNormalPointer(GL_FLOAT, 0, &normals_[0]);

    glDrawElements(GL_TRIANGLES, indices_.size(), GL_UNSIGNED_BYTE, &indices_[0]);
}

```

Thanks ahead.

# Answer
Well, this is awkward. I overlooked the fact that the Teapot model has FAR more vertices than 255 (the size of GLubyte). I changed my call to `glDrawElements` and my `indices_` vector to use unsigned integers, problem solved!
> 0 votes

---
Tags: opengl, c++, assimp, obj, model-loader
---


# Question
Title: What is the fastest way to know if the current coordinate in screen-space is odd or even in GLSL/GLES2 frag shader?
I want to make a post-effect where every second column of pixels is colored differently, and I want to implement this as a GLSL fragment shader on GLES2. The question is what is the most effective way to know if a fragment is indeed odd or even in the x direction?

My current ideas revolve around the following three approaches:

**1. Integer bit-wise operator**

```
//Pseudo code
bool even_w=((int)(viewport_pixels_width*screenspace_x))&1>0;

```

**2. Sinus**

```
//Pseudo code
float evenness_w=(sin(viewport_pixels_width*screenspace_x*M_PI)+1.0)*0.5;

```

**3. Texture**

```
//Pseudo code
bool even_w = lookupFromMyRepeating2x1CheckerTexture(viewport_pixels_width*screenspace_x);

```

All ideas and feedback are welcome!

# Answer
The way to discriminate that is to use the screen position intrinsic of GLSL `gl_FragCoord` (some call it a built-in variable). And pass it through a floating point function that will do the equivalent of a modulo in integers math. This way, you can use `2` as a divisor and the (floating point) alternation of the saw-dent-like ramps it will create (rising from 0 to 1.999..) will give you the factor you need, by using `1` as the cutoff. of course the ramps are not continuous, its discreete. Especially if there is no multisampling in your rendertarget (but the sample sub-position is given by another inrinsic anyway, so you get rounded coordinates for pixels).

Using this:

```
vec2 txc = gl_FragCoord.xy;
if (mod(txc.x, 2) < 1)
{
  // even
}
else
{
  // odd
}

```

should to the trick
> 3 votes

---
Tags: algorithm, glsl, performance
---


# Question
Title: Algorithm/ Logic of identifying a circle in Go game
I'm trying to create a 2 players Go-like game. Unfortunately I can't get the capturing system to act correctly. At the moment the system is half done, however I cannot think of a perfect way for it to recognize a circle correctly. This is the logic that I'm planning at the moment (let say it's currently White's turn):

1.Using the newest placed piece as the starting point, run a flood fill (Up, Down, Left, Right) code to find all the affected nodes/Black piece, and place them in a "suspects list".

2.Using the suspects list, find any White piece that is near them (Up, Down, Left, Right, UpLeft, UpRight, DownLeft, DownRight). Adds those pieces into a "circle candidate list".

3.Run through the circle candidate list and remove any piece that doesn't connect to at least 2 other candidates. Keep doing this until all candidate are connected to at least 2 other candidates or the number of candidates are less than 4 (which won't be possible to make a circle).

4.Using a recursive method checks whether we can make a circle using all the candidates. The last piece must be connected to the first one.

5.If a circle is identified, get all the nodes that are between the candidates, first checks from top-to-down then left-to-right. Records all the nodes that were identified in both checks as dead zones. Kill any Black piece inside the dead zone and any Black piece that is place inside there after this will automatically die.

Here's where the problem is, I noticed that 3 pieces that are next to each other will still be connected to 2 other piece. Which means the system will still see them as a legitimate candidate even if they aren't part of a circle. And secondly the way I use to check if there is a circle can easily fail if there are more than necessary pieces to make the circle since it could turn the wrong way and then unable to get back to the starting point.

I've been struggling with this capturing process for a week now, and tested a number of different ways. All of it will have a problem in certain scenario which resulted in a bug (either they're not capturing piece that should be captured, or capturing piece that should not be captured). So any help are greatly appreciated. Thank you.

# Answer
Instead of trying to recognize the circle, recognize the islands.
Every island is enclosed by a circle.
> 1 votes

---
Tags: algorithm, board-game
---


# Question
Title: Android OpenGL and non premultiplied textures
As I understand it; by default all bitmaps will will get the alpha channel premultiplied in Android if loaded using BitmapFactory.

**My setup:** I have a 32bit bitmap(.bmp) where the alpha channel has a gloss map and the rgb is a specular map.

**Issue:** I found out that I can load the bitmap without being premultiplied using the bitmap option:

```
opts.inPremultiplied = false;

```

**Result:** When I render the alpha channel of the texture like this in the shader:

```
gl_FragColor.rgb = vec3(texture.a);

```

The resulting mesh is all white and not shades of gray as expected.

I upload the texture with this method:

```
GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image, 0);

```

I have also tried using this approach

```
GLES20.glteximage

```

as well with the same result although I might have done something wrong there.

Can anyone spot where I have gone wrong or what else I need to do?

# Answer
It is very likely that your bmp loader does not load the alpha channel and fills it with a default value, as BMP with alpha channel is non-standard. Try using a .png file instead. From wikipedia:

"An integrated alpha channel has been introduced with the undocumented BITMAPV3INFOHEADER and with the documented BITMAPV4HEADER (since Windows 95) and is used within Windows XP logon and theme system as well as Microsoft Office (since v2000); it is supported by some image editing software, such as Adobe Photoshop since version 7 and Adobe Flash since version MX 2004 (then known as Macromedia Flash). It is also supported by GIMP, Google Chrome, Microsoft PowerPoint and Microsoft Word."
> 1 votes

---
Tags: opengl, android, textures
---


title: Quick sprite contouring solutions?

text:
# Question
Title: Quick sprite contouring solutions?
I want to be able to quickly outline sprites(mainly with black, but other colours too) without doing it manually, as pictured. What would be a good program/solution to do so?

Edit: I don't want it to happen at runtime, I just want to have the second version and I can scrap the first.

# Answer
> 3 votes
it's trivial, you can do it yourself. Assuming your sprites have alpha value 0 in unused areas, you can do the following (in pseudocode):

```
pixels_out = pixels
for y in pixels.height()
    for x in pixels.width()
        if pixels(x,y).alpha == 0,
            neighbour_in_sprite = false
            for y2 in [-1,0,1]
                for x2 in [-1,0,1]
                    if pixels(x+x2,y+y2).alpha > 0
                        neighbour_in_sprite = true
                        break
                if neighbour_in_sprite
                    break
            if neighbour_in_sprite
                pixels_out(x,y).color = [0,0,0]
                pixels_out(x,y).alpha = 255

```

It's pretty much, for every unused pixel in the 8-neighbourhood of a used pixel, mark it as silhouette and set the black colour and normal alpha .

---
Tags: graphics, sprites, graphics-programming, spritesheet, outline
---


# Question
Title: Displaying a particular sprite from spritesheet using Phaser
I am trying to make a card game using Phaser, the HTML5 JS framework. Because I'm a terrible artist and can't design my own, I'm using a free spritesheet of playing card images I found online. The problem is, I can't seem to figure out how to display individual cards using Phaser.

In the previous framework I used, I was able to create individual smaller sprites from the larger sprite sheet that I used. But I can't figure out how to do that in Phaser, if it's possible at all.

So I looked into loading the image as a spritesheet, but it seems that spritesheets are used for animation only and you can't really display a particular 'frame' of the spritesheet (please correct me if I'm wrong).

I think what I need to do is load the image as a tilemap, however, the particular image that I'm using did not come with a json file specifying the layout (nor could I find one that did). Being new to javascript I'm having trouble reading the Phaser source code to see how the json file should be formatted.

So in summary, what's the best way to display an individual card of a spritesheet of playing cards in Phaser given that I don't have a json file specifying the map data?

# Answer
```
var sprite = game.add.sprite(x, y, 'spritesheet_name');
sprite.frame = 0;

```

Spritesheets aren't limited to animations, that's just one way to use them. An animation is just a way to display different frames at different times. By manually setting the frame of a sprite, you can display a specific part of the spritesheet.
> 8 votes

# Answer
Phaser has support for two types of sprite sheet: "classic" ones, where every frame is the exact same size, and "texture atlases" which are created with the help of a third party app like Texture Packer, Shoebox or Flash CC and come with an associated json file.

You load the "classic" ones with `game.load.spritesheet` where you must specify the width and height of the frames, and optionally the quantity, i.e.:

`game.load.spritesheet('uniqueKey', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18);`

To load a texture atlas you can use `game.load.atlas`. You'll find plenty of examples of this in the Phaser Examples repo.

Once loaded create your sprite:

`var sprite = game.add.sprite(x, y, 'spriteSheetKey');`

This tells Phaser to use the image with the key `spriteSheetKey` as its texture. By default it will jump to frame 0 of the sprite sheet, but you can change it with `sprite.frame` to any other valid number.

If the sprite was using a texture atlas it's easier to change frame based on the frame name: `sprite.frameName = 'card4'` where the frame name is exactly as specified in the texture atlas json file (open it up and look at it to see!).
> 16 votes

---
Tags: html5, card-game, phaser
---


title: No sound in android using Phaser

text:
# Question
Title: No sound in android using Phaser
I have developed a simple game using Phaser. It's work perfect on ios webkit, but on android there is no sound. What causes this problem on one platform but not the other?

We are using this code to load:

```
this.load.audio('game_audio', 'audio/bgm.mp3');

```

Playing:

```
this.music = this.add.audio('game_audio');
this.boom.play()

```

# Answer
> 2 votes
This issue is almost certainly codec / sound format related, but without knowing how your `bgm.mp3` file is encoded it's really hard to tell. Maybe the encoding bitrate is too high, or the device can't handle mp3 files and needs ogg instead? You'll have to experiment I'm afraid as it's hard to say exactly from the post.

---
Tags: android, html5, phaser
---


# Question
Title: How to generate a "loop room" in a platformer game (by Unity)?
I want to build a level with a room whose left edge is linked to right edge in a 2D platformer game in Unity.

My goal is let all objects disappear in one side will appear in other side of the room. Just like this: Both sides should have collision with other objects.

Right now I'm doing this by cloning objects on the other side, but it is too complicated. Is there any other good way to solve this?

# Answer
> 1 votes
My solution would me to create 2 identical objects that are spaced apart by the width of the screen.So when the first object is in the middle of the view (for example left one), the other object would be screen width apart from the first object i.e. off the view. When you move the first object the second one moves along with that object, keeping the space between them the same. So when hte first object disappears from the view second object will appear.Just a suggestion :)

# Answer
> 0 votes
If your room take up the whole game screen (a bit like your image), there not much you can do, because you do need to have part of that orange circle both on the left and on the right of the screen.

If your world is large and you platformer center its view on the character, there's more hope. Let's say your world has a width of `h`. For example, split your world in two parts, at about the x-distance `h/2`. Whenever the character is in the left part, leave the object overlapping the vertical side with coordinates at about `0`. Whenever he is in the right part, add `h` to their x-position.

Of course this creates a lot of computation if the character crosses the side a lot, so it's improvable. For example you could split down even further, and have the changes made only when the character crosses the `x`-position of `-h/4` to teleport him/her at `3*h/4` and when he/she crosses `5*h/4` to teleport him/her at `h/4`.

---
Tags: unity, 2d, platformer
---


# Question
Title: Why do my images take 200 MB of RAM when they are ~20KB on disk?
I am creating an Android game using libGDX. When I load my nine images it takes 200 MB of RAM. But the images are 10 to 17 KB each. Why the discrepancy? Here is where I create textures from those images:

```
public static HashMap<String, Texture> ground = new HashMap<String, Texture>();
for (int i = 1; i < 10; i++) {
  ground.put(
  "ground" + i,
    new Texture(Gdx.files.internal("groundImages/ground" + i + ".png"))
  );
}

```

# Answer
> 10 votes
The PNG files are small because they are compressed. When the images are loaded into memory they are uncompressed and therefore take up more space.

---
Tags: java, textures, libgdx
---


# Question
Title: How can I efficiently render lots of 2D quads?
I have lots of 2D quads. I write their local vertex position info to a buffer (accompanied with a world transform matrix) which gets sent to the render thread.

I then pass the world transform matrix as a uniform into the vertex shader which applies itself to each vertex and works fine. I however have to make a call to `glDrawElements()` for each quad I want to render because each one has a different world transform.

What is the most efficient way for me to render all of these quads? Should I do what I'm already doing, or should I calculate the world position for each vertex on the CPU before I write them to the buffer, so I can attempt to batch more quads into a single `glDrawElements()` call? Or is there another approach?

# Answer
> 2 votes
You definitely want to use instancing.

Your quads are instances: constant data (e.g. 4 vertices, bound texture) but with a few different parameters (e.g. world space matrix). Your world space matrices will be the instance data: one for each instance. It's a quite elegant and standard solution.

You can have all sorts of data as instance data, in the above case this means applicable to all four vertices of the quad. Examples: size of the quad, texture index, colour tint, transparency values, etc.

Per-vertex data could be your unit quad { (0,0), (1,0), (0,1), (1,1) } with indices: { (0,1,2),(2,1,3)} for CCW ordering.

# Answer
> 2 votes
I second instancing.

For the sake of extra information: Converting quads to world-space on the CPU.

If you can support it, you could also offload that work to the GPU through a geometry-shader. A couple arrays, 1 for the vertices of each quad, 2 for the transform marix of each quad, and then compute the world coordinates based on that (or some similar approach.) Since the geometry shader comes before the vertex shader step, it would fit right in.

You could also use a compute-shader to offload cpu work, if it's to much.

You could also avoid local coordinates. Local coordinates are nice for many reasons. If you don't need those benefits, or use them rarely, you could just use world coordinates and there would be no conversion to worry about. Aside from the rare conversion to local. That's going to be very dependent on what you're doing though.

---
Tags: opengl
---


# Question
Title: Shadow mapping. I don't understand what to do after creating the depth texture
I'm taking an intro to computer graphics course, so this is something we haven't touched on.

I am reading this tutorial http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/ but I cant figure out what to do after creating the depth texture. The depth texture is from the lights point of view (directional light). I sent the depth texture to my post process shader where I want to apply the shadows. The depth texture:

From what I understand from the article, I also need the position texture from the light's point of view.

The position texture:

And then the article determines if the current pixel is visible from the lights point of view like this:

```
float visibility = 1.0;
//ShadowCoord is the position of the vertex as seen from the light
if ( texture2D( shadowMap, ShadowCoord.xy ).z  <  ShadowCoord.z){
   visibility = 0.5;
}

```

Here is what I end up with:

Im not sure, but I believe my position texture is wrong?

**Edit**: Here is how I create the position relative to the light texture in my shader:

```
positionSunPOV = (biasMatrix * sunMVP * vPosition).xyz;
// biasMatrix is the matrix that changes the coords from [-1,1] to [0,1]
// sunMVP is the model view projection matrix for the sun than I passed in
// vPosition is the position of the vertex

```

Here is how I create sunMVP:

```
SunDir = vec3(0,30,-30);
sunProjectionMatrix = ortho(left, right, bottom, ytop, nearO, farO);
sunViewMatrix = lookAt(SunDir, vec3(0,0,0), up);
sunModelMatrix = mat4(1.0);
//sunMV = mult(sunViewMatrix,sunModelMatrix);
sunMVP = mult( sunProjectionMatrix, mult(sunViewMatrix,sunModelMatrix) );

```

# Answer
> 2 votes
First, from the picture it seems that in fact your light is not a "directional" light but a spotlight because you are using perspective projection, not an orthographic one (If not, then it is just the picture :) ). It is just a little thing, it should work more-or less the same.

The important thing is, you don't render the positions from the light's point of view. From the light's point of view, you have the shadow map.
You retrieve the position from the world position of the pixel (so you have to keep a texture of world positions, or retrieve the position from the main camera's depth buffer), then transform it by the light's viewProjection matrix (sunMVP in your code) in the fragment shader, then by taking the .z value of that transformed position and dividing it by .w, you get the real Depth of that pixel from the light's point of view, I call it the **realDistance**. The value which you sample from your shadow map will be the **occluderDistance**. If occluderDistance is less than realDistance, then it is occluded.

So in the pixel shader you have to do something like this:

```
float4 worldPosition = texture2D(WorldPosTexture,tex.xy);
//you can also retrieve world space position from depth buffer, but that's out of scope here.
float4 positionFromLight = worldPosition * sunMVP;
float realDistance = positionFromLight.z/positionFromLight.w;

if(realDistance > texture2D( shadowMap, ShadowCoord.xy ).z)
{
 //shadow
}
else
{
 //light
}

```

You might need to switch to `realDistance < texture2D( shadowMap, ShadowCoord.xy ).z`, it depends on what your depth buffer looks like. It can be 0.0-1.0 (close-far), or 1.0-0.0 (close-far).

Sidenote: A world position texture should look something like this:

---
Tags: fragment-shader, shadows, shadow-mapping, depth-buffer, deferred-rendering
---


# Question
Title: How can I tell if a set of tiles form an enclosure?
I have this tile-based game I've been messing around with and I want to have a way to check if a set of wall tiles make an enclosed space.

Here's some more details: I have a tile map. Each tile has an ID. If you have a set of IDs like so:

```
0,0,0,0,0
0,1,1,1,0
0,1,2,1,0
0,1,1,1,0
0,0,0,0,0

```

0 is grass, 1 is wall, and 2 is floor. Assuming these have a spot in a 2d array, how can I find and confirm if whether or not the floor tile is surrounded by walls. This method has to be scalable as well. So if the floor area is 2x2 it would still work.

I've already tried implementing a way to check it, but I failed on my first couple of tries. Any recommendations?

# Answer
You could use a modified Flood Fill starting from a floor tile to check for the presence of grass tiles. In this case, the wall would count as a boundary and floor tiles would count as open space. If at any point during the flood fill you reach a grass tile then you know that the floor is not surrounded by walls.
> 2 votes

---
Tags: c++, tiles, tilemap
---


title: Box2D pixels to meters , LibGDX

text:
# Question
Title: Box2D pixels to meters , LibGDX
I am confused . what shall I set the orthographic camera viewport in libGDX when I use box2d , in one tutorial I saw that he divided his viewport numbers to 32 because 1meter =32 pixel , but I think it will make the images to be displayed by lower quality , so can anybody explain me what viewport shall I set ?

# Answer
I think you need to find the needed ratio between Texture size and meters. I would probably use 100px:1m. Then, when you are setting the fixture sizes, multiply the texture size with the ratio.

Try something like this:

```
//RATIO
private float ratio = 1/100;

// TEXTURE
private Texture texture = new Texture(YOUR TEXTURE PATH);

private float fixtureHeight = texture.getHeight() * ratio;

```

So now, if your player will be 200px heigh, then ,in box2d, it will be 2 meters high.
> 2 votes

---
Tags: libgdx, box2d
---


title: Fullscreen triangle pass and texcoords

text:
# Question
Title: Fullscreen triangle pass and texcoords
So I have a fullscreen triangle shader like this:

```
#ifndef FULLSCREEN_TRIANGLE_VERTEX_HLSL
#define FULLSCREEN_TRIANGLE_VERTEX_HLSL

// Variation on Timothy Lottes FXAA vertex shader, for CCW frontface
float4 vs_main(uint VertexID: SV_VertexID) : SV_Position
{
    return float4(float2(((VertexID << 1) & 2) * 2.0f, (VertexID == 0) * -4.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);
}

#endif

```

This helps me during deferred shading, since I can just do like this in the pixel shader:

```
float4 ps_main(float4 position : SV_Position) : SV_Target0
{
    float ssao = 1.0;
    if (gUseSSAO)
    {
        ssao = gSSAOTexture[uint2(position.xy)].r;
        ssao = (clamp(1.0 - (1.0 - ssao), 0.0, 1.0) + 0.1) / (1.0 + 0.1);
    }

    return gDiffuseTexture[uint2(position.xy)] * ssao * gAmbientLight;
}

```

SV\_Position automatically gives me the screenspace position of the pixel. Now some of my alghorithms require texture coordinates. I know this is simply `(screenspacePosition.xy / textureSize.xy)` but I want to avoid those instructions in my pixel shader. Is there some system-provided value (like SV\_Position) or any neat way to enhance the fullscreen vertex shader to provide me with texture coordinates aswell?

# Answer
> 1 votes
I do it like this, so no divide in the PS. Vertex Shader code follows:

```
struct VertextoPixel
{
    float4 pos              : SV_POSITION;
    float2 tex              : TEXCOORD0;
};

VertextoPixel main(uint vI : SV_VERTEXID)
{
    float2 inTex = float2(vI%2,vI%4/2);
    VertextoPixel Out = (VertextoPixel)0;
    Out.pos=float4((inTex.x-0.5f)*2,-(inTex.y-0.5f)*2,0,1);
    Out.tex=inTex;
    return Out;
}

```

---
Tags: directx11, hlsl
---


title: How to implement a Trail using Cocos2dx

text:
# Question
Title: How to implement a Trail using Cocos2dx
I'd like to implement a trail (like the white circles in Angry Birds) that chase my sprite. I already used CCMotionStreak, but the trail texture is "stretched" instead.

Anyone has an idea how to make this?

# Answer
There are a few ways to do this.

One would be to continuously store your sprite's position points in an array that's updated to hold the last 20 positions or so depending how many you need for your trail. Then you can simply apply white circle sprites (or whatever you want the trail to be made of) on to only the current points in that array or every other current point in that array depending on the spacing you want.

If you are using the update method to store your sprite position points, remember to fix your time step or the position points might not be evenly distributed.
> 1 votes

---
Tags: android, cocos2d-x, motion
---


# Question
Title: Do I need to learn any physics if I use a physics engine?
Complete novice out here. Of course I know basic physics like mass and inertia. I don't want to make an engine I just want to make a game and use a physics engine made by someone else.

Do I need to learn any physics if I plan to use a physics engine?

# Answer
> 3 votes
Bare minimum you need to know how the physics SYSTEM works within the engine. Most of these may sound daunting but it's really not that difficult and you CAN simply stumble through things but it will make it significantly easier if you understand these going in.

* What is a `RigidBody`?
* What is a `Collider`?
* What is the relationship between the two?
* How is it different when a collider is used as a `Trigger`?
* What callbacks get made, when, and which object is it called upon?
* What is the significance of something being `Kinematic`?
* How can you manually update the position, direction, etc of a GameObject that is currently under the influence of physics?
* What's the difference between `Drag`, `Angular Drag`, `Friction`?
* What influences `Bounciness`?

These are extremely helpful. Knowing these you should be able to get around the physics system in Unity pretty well for most tasks.

Other things to consider:

* Vector Math - It really does help to fully understand direction, magnitude, normalizing, etc...
* At least on a conceptual level it's a good idea to have an understanding of `Velocity` and `AngularVelocity`.

Knowing a specific formula or in-depth physics knowledge isn't necessary under a great many circumstances. However, it IS possible that you would need to know some in-depth mechanics in order to accurately replicate real life.

I would recommend starting here:

1. http://docs.unity3d.com/Manual/RigidbodiesOverview.html
2. http://docs.unity3d.com/Manual/CollidersOverview.html

# Answer
> 1 votes
From my personal experience, some basic physics knowledge can help a lot to tune your game.

Lets say that you want to create certain physical effect in your game e.g. players can push boxes. Of course, you need to tune certain parameters to make this effect behave as you want, so that the boxes neither violently fly in every direction neither are almost impossible to move.

You can try trial and error, but besides being a boring way to tune parameters, it will make your code brittle: if something goes wrong, you won´t even know why.

On the other hand if you know how physics work, you can easily do the math and plug in the values to achieve the desired effect.

**TL;DR: If you want to provide any physical effect in your game, it helps to learn the basics.**

# Answer
> 0 votes
I think it's enough for you to know how gravity and forces work, although you actualy don't have to know these, because physics engine does everything for you(ESPECIALY UNITY).

Like the first komment says, just play around and learn how to use the engine.

---
Tags: c#, unity, physics, physics-engine
---


title: System.StackOverflowException error

text:
# Question
Title: System.StackOverflowException error
**Hi all!** I have a one problem. I trying to create 2D cave generation system in C# with XNA game studio, but then I running program I getting **"System.StackOverflowException"**. As you can see in this image:

And I get this after I try to create new object from it own class. I in short explain how my cave generator works.

My map is containing ID’s (integers) of the different types of cells(like wall, water or empty Space).

First off all my "Map" Class creates filled with walls map and after that, in center of the map, it creating "Miner" object. It digs map and makes caves. But here is one problem, I wan't to create more miners. So then my miner digging map it in some place must create other miner, but I getting **"System.StackOverflowException"** Exception. Please help me... And thanks anyway. :)

Here is my miner code:

Miner.cs

```
public class Miner
{
    Random rand = new Random();

    public bool active { get; set; }
    public int x { get; set; }
    public int y { get; set; }
    public Map map { get; set; }
    public int minersCount { get; set; }

    public Miner(Map map, bool active, int x, int y)
    {
        this.map = map;
        this.active = active;
        this.x = x;
        this.y = y;
        minersCount = 1;

        if (active)
        {
            StartDigging();
        }
    }

    bool IsOutOfBounds(int x, int y)
    {
        if (x == 0 || y == 0)
        {
            return true;
        }
        else if (x > map.mapWidth - 2 || y > map.mapHeight - 2)
        {
            return true;
        }
        return false;
    }

    bool IsLastMiner()
    {
        if (minersCount == 1)
        {
            return true;
        }
        return false;
    }

    public void StartDigging()
    {
        if (active)
        {
            int dir = 0;
            bool needStop = false;
            int ID = -1;

            while (!needStop && !IsOutOfBounds(x, y))
            {
                while (dir == 0)
                {
                    dir = ChooseDirection();
                }

                if (!AroundIsNothing())
                {
                    while (ID == -1)
                    {
                        ID = GetIDFromDirection(dir);
                    }
                }
                else
                {
                    if (!IsLastMiner())
                    {
                        needStop = true;
                    }
                }

                if (ID == 1)
                {
                    DigToDirection(dir);
                    dir = 0;
                }

                if (ID == 0 && IsLastMiner())
                {
                    MoveToDirection(dir);
                    dir = 0;
                }

                TryToCreateNewMiner();
            }
        }
    }

    public void TryToCreateNewMiner()
    {
        if (RandomPercent(8))
        {
            Miner newMiner = new Miner(map, true, x, y);
        }
        return;
    }

    bool AroundIsNothing()
    {
        if (map.map[x + 1, y] == 0 && map.map[x, y + 1] == 0 &&
            map.map[x - 1, y] == 0 && map.map[x, y - 1] == 0)
        {
            return true;
        }
        return false;
    }

    void MoveToDirection(int dir)
    {
        if (dir == 1)
        {
            x = x + 1;
        }
        else if (dir == 2)
        {
            y = y + 1;
        }
        else if (dir == 3)
        {
            x = x - 1;
        }
        else if (dir == 4)
        {
            y = y - 1;
        }
    }

    void DigToDirection(int dir)
    {
        if (dir == 1)
        {
            map.map[x + 1, y] = 0;
            x = x + 1;
        }
        else if (dir == 2)
        {
            map.map[x, y + 1] = 0;
            y = y + 1;
        }
        else if (dir == 3)
        {
            map.map[x - 1, y] = 0;
            x = x - 1;
        }
        else if (dir == 4)
        {
            map.map[x, y - 1] = 0;
            y = y - 1;
        }
    }

    int GetIDFromDirection(int dir)
    {
        if (dir == 1)
        {
            return map.map[x + 1, y];
        }
        else if (dir == 2)
        {
            return map.map[x, y + 1];
        }
        else if (dir == 3)
        {
            return map.map[x - 1, y];
        }
        else if (dir == 4)
        {
            return map.map[x, y - 1];
        }
        return -1;
    }

    int ChooseDirection()
    {
        return rand.Next(1, 5);
    }

    bool RandomPercent(int percent)
    {
        if (percent >= rand.Next(1, 101))
        {
            return true;
        }
        return false;
    }
}

```

As you can see then miner digging, he have about 8% chance that will create new miner. But then it creating it I getting error. New miner is creating at " TryToCreateNewMiner()" method.

# Answer
> 1 votes
Your TryToCreateNewMiner function can call it again. If your RandomPercent calculator keeps returning true, the callstack gets deeper and deeper.

TryToCreateNewMiner-\>Miner-\>StartDigging-\>TryToCreateNewMiner

---
Tags: objects, obj, exceptions
---


# Question
Title: What are some rarely-mentioned networking models/strategies?
I've been thinking about multiplayer and networking a lot lately, and I've found oodles of information, but I feel like there might be some standard models or strategies for networking that I haven't seen.

* There's the obvious client-server model, using the client as a terminal that sends keystrokes and recieves location information about the other entities.
* There's a point to point model, I believe - how two clients can play a game without the setup of a dedicated server (seen in LAN a lot).
* There's the client prediction strategy where the client is allowed to take control of the player while it waits for latency to bring back the server's actual position for the player - keeping a log of keystrokes to make the correction seem smooth.
* In cases where the servers are overloaded, I've seen a strategy that dedicates some of the work like AI to clients. I've seen it in the DayZ mod... Clients take control of some zombies when they get close.

Are there any glaringly obvious or rarely seen strategies or models, errors in the brief descriptions I've listed above, and/or additional reading into the deep parts of this topic?

# Answer
I think that no matter what strategy you plan to use, you need to consider methods like:

* KISS (Keep It Simple Stupid)
* DRY (Don't repeat your self)

Read books like:

* Clean code

Simple non repeated code tends to run clean and smooth, use alot of benchmark tests

Divide the system's node value with 20 and set a max time for execution, eg. first node max 200 ms, second node max 100 ms, third node 5 ms. etc. That way you get clean and fast code, i use this method with web services and most calls to the service is almost always less than 200 ms.
> 1 votes

---
Tags: networking, multiplayer
---


# Question
Title: How do I convince my team to use less VO?
I am a firm believer in using voice over (VO) only for necessary elements such as game narrative, and here and there to drive game play (e.g. instructions coming in over intercom, that sort of stuff). I think that game design should speak for itself, and generally, when lots of VO instructions are needed to drive game play, good design is lacking.

Unfortunately, my team doesn't really consider this, and feels that everything needs to be commented on by the main character's companion. As a result, I (sound designer) got a huge script in which I had virtually no say, with in my opinion lots of useless lines. Some examples:

> *When there's only one tree in the scene with a very obvious squirrel in it.*
>
> "Look at that squirrel in the tree!"

-

> *In a room with one door.*
>
> "I wonder what's behind that door."

-

> When facing a lot of bad guys.
>
> "Those are a lot of bad guys."

I feel we're dumbing down the player, and taking away lots of attention from the actual environment and player's initiative. However, whenever I mention this to the script writer or lead director (who is partially responsible for the script to), they're quite protective about it. I feel I have to ask line-by-line if this is really necessary, and this is not good for the atmosphere or productivity.

How can I convince my team that something more fundamental is wrong with the script?

**Edit:** Does someone have some good examples of games that use the above in a bad way, that I can use to demonstrate my point?

# Answer
Do playtesting and see how the testers react to it. Possible complains the testers could have:

* Unnecessary or even misleading voiceovers distract from the gameplay
* Bad or inappropriate voiceovers break immersion
* Voiceovers which are repeated multiple times become annoying.
* Important voiceovers aren't understood because the player is distracted when they play (like by other sounds which play at the same time or because something important happens gameplay-wise)

When any of these points occur in the test protocols, you have an argument.

Alternative, appeal to their wallet. Present a cost/benefit analysis. Good voice actors and studio hours aren't cheap, so you could try to argue that the cost involved with the voiceover script is unjustified and lots of budget could be saved by cutting any unnecessary dialog.

However, keep in mind that dialog has use beyond gameplay. Nowadays, many good games try to reach the player emotionally by having a story with interesting characters. To make a character interesting, you have to give them dialog which gives them depth beyond a mere game mechanic. Just think about memorable NPCs from games like Portal (GlaDOS, Wheatley), Bioshock Infinite (Elizabeth) or Mass Effect (all the selectable companion characters). They have lots and lots of voiceover where they just emote to what happens in the game. It often isn't really relevant for understanding gameplay or plot, but it makes them feel more like persons and less like tools. Without these lines, the player wouldn't form an emotional connection to them.
> 8 votes

# Answer
This is a generic answer to "how do I get other people to do things my way when I don't have a lot of power in this situation" but here goes:

KISH: Keep It Super Helpful. Make it seem like you are totally on their side and you'll bust a gut to make it happen... but make sure you don't end up with responsibility for all the bad stuff that you foresee. Let them figure out that they're going to be carrying the risk.

So "I worked out a rough amount of studio time we're going to need for this, did a quick ring round the agencies... looks like you're talking $X for the talent. You'll need a dialog freeze Y weeks before beta. I talked to the designers; they're pretty sure they'll have it all by then, but we need to book Z weeks in advance and that only gives us W weeks to get the scenes written and then no more major re-writes or you're looking at paying most of that all over again... Shall I get them booked for you?"

Or "I thought I'd rough this stuff out for a few scenes we have video of but using people I nabbed in the office for the voices; I can't work out how it's going to not sound like we're treating the player like a baby. Could you take a look and help out? Hey! Maybe you could do some of the voices and show me what it should sound like?"

Let them run with it. Try to do the best you can at your job, but if you feel you are getting responsibility for risks you don't think you can properly handle, negotiate some way that you can keep the responsibility off your shoulders... like "We're going to need to do some short bits ready for alpha-testing, see what the testers think, because you never know how it's going to sound until it's all put together" -- this tactic means that you are not guaranteeing quality -- but remember: always appear/be Super Helpful.

Hopefully your boss will recognize the risks and call it off, but there's always a risk that you'll still have to do it. Maybe having figured out how to slough off the risks it actually works OK, because you are all actually managing the risks of it being rubbish, costing a lot, limiting the designers' freedom and so on and so you don't end up with those problems. Maybe it does get done and it is rubbish, but at least you dodged the blame.

But whatever happens, you stand a good chance of being the good guy. However, if it goes ahead and it's rubbish and you stood in its way, people won't think "hey, that guy really got this one right, let's listen to him more in future," they'll think "hey, that guy was a major pain; had he been more supportive perhaps this would have been great" and you will have lost in all respects.
> 2 votes

---
Tags: game-design, sound, voice
---


title: LibGDX Box2D TileGame Efficiency

text:
# Question
Title: LibGDX Box2D TileGame Efficiency
I am trying to implement Box2D into my top down tile game in LibGDX. Each world consists of a set of chunks, and each chunk is 16 tiles wide/long. The maximum/minimum chunks loaded at one time is 9 (a 3x3 set of chunks with the player in the middle). This means that there are 2304 tiles active at all times.

I have tried creating a Static box shape for each of these tiles but performance was understandably terrible. I then tried creating a box shape for each of these tiles that are solid. Performance was still terrible because at one time there was 500-1000 individual boxes.

One partial solution I found to this is reducing the chunk size. At chunk size 8 with boxes around only solid tiles performance was 60 fps on mobile devices, however this was only sustained when the chunks that were loaded did not contain many solid tiles so this isn't really a solution.

I then came across a potential solution which would join all solid adjacent tiles within a chunk, so that instead of having a box for each individual solid tile, there would be a irregular polygon for each set of connected solid tiles. This solution appears to be the best, however what would happen when I want to destroy a solid tile. I would then have to recalculate all of the tile connections within that chunk and recreate another irregular polygon. To get around this, I then thought of dividing the chunk up into 4x4 sections. Each of these sections would handle their own irregular polygon so that when a tile was destroyed only that section would need to be updated and recalcuated. This however increases the number of bodies in the box2d world compared to the previous solution where there is just 1 body for each group of solid tiles.

I am looking for any other ideas that might help.

On a side note: The only reason I am using box2D is so I can achieve a nice lighting effect with shadows and everything with box2DLights. If there are any substitutes of this library that you know of please let me know!

# Answer
I don't know if this is going to work, but if I was you, I would only use one chunk at a time and that is the number of tiles that are visible. So something like 32x32 chunk should be fine, it depends on your viewPort and tile seizes. That way the performance should be much better.
> 1 votes

---
Tags: android, libgdx, box2d, performance, tilemap
---


# Question
Title: What is the meaning of the row "opposite" the translation column?
Usually, I do my matrix multiplication like this:

```
[1 0 0 dx] | [px]   [px + dx]
[0 1 0 dy] | [py]   [py + dy]
[0 0 1 dz] | [pz] = [pz + dz]
[A B C  1] | [1]    [1]

```

Where the translation is along the right-hand edge of the matrix.

Once, I forgot about that and put them on the lower line instead, on the places marked as `A B C` above.

What did that do to the resulting points? With the upper-left 3x3 being an identity matrix, and the translation being zero, nothing happened to my point

```
[1 0 0 0] | [1]   [1]
[0 1 0 0] | [1]   [1]
[0 0 1 0] | [1] = [1]
[1 2 3 1] | [1]   [7]

```

except that 1 we always use in fourth place gets changed. Does this mean further multiplication with the point results in a mess? What am I doing by changing the bottom row?

# Answer
The fourth column (or row, depending on your preferred convention) is used for projection. For example, the following page gives a good overview of perspective projections in Direct3D: Projection Transform (Direct3D 9) and the following for orthographic projection.
> 2 votes

# Answer
The 3-tuple diagonally opposite the translation tuple in a 4x4 transformation matrix (in other words, the bottom row in your example, but note that it could be the right column if you are multiplying you vertices on the right instead, which is another equally valid convention) usually isn't used. It will have non-zero values when the matrix is used to represent certain kinds of *projection* (such as perspective projection).

It's important to remember that a 4x4 matrix is a more general mathematical concept than a "3D transformation," and that not all permutations of re-presentable 4x4 matrices have corresponding geometric interpretations.

In other words, the fact that the right row "contains the transformation" is more of a happy accident of the way the math works out and *not* an intrinsic property of a 4x4 matrix in general.
> 2 votes

---
Tags: 3d, matrix
---


# Question
Title: How to pass a turn to AI and draw its move in a game?
I am writing a simple game for 2 players, where they have to make turns after each other (select a few objects to remove from the screen) and press "End turn" at the end to pass the turn to another player.

The turns are switched in `onClick` method on a `onClickListener`, attached to the button "End turn". And it works fine for the case of 2 humans playing (on the same device). But if a person plays with the computer, the AI calculates and makes its move in the same `onClick` method. Thus, its move are not drawn on the screen and the player sees as if after his move the board was redrawn immediately with the changes made by the computer's move (objects removed). How can I make is so automatic moves are drawn as in case of human play - the objects are selected by the AI and then removed (at this time the button "End turn" would be disabled)?

# Answer
> 0 votes
The exact answer to this is going to be pretty specific to the way you've designed things.

Essentially the strategy is to make the AI use the same methods that the player does. It shouldn't just run everything in a single tight loop. Break the AI's decisions and actions into discrete parts. Then, using something like a decision tree or behaviour tree structure, have the AI perform these decisions and actions with some delay between each. During the delays the AI should be relinquishing control to the rendering and UI threads.

# Answer
> 0 votes
To make the moves of the AI more noticeable, you could animate them.

Instead of removing the objects immediately, you could, for example, fade them to alpha over the course of a second. You could also do something more flashy like drawing a destruction animation or having them explode with a particle effect, depending on what's appropriate for the theme of your game.

---
Tags: android, multiplayer
---


title: Unity - Can't Shoot While Moving

text:
# Question
Title: Unity - Can't Shoot While Moving
Shooting does nothing while moving, but it works perfectly fine while standing still in my Unity project. As far as I can tell no one else has this problem. I just used the Character Controller first person controller. I didn't bother providing the other scripts because they are irrelevant to the problem

Below is my shooting code.

```
function Update () {
//Shooting
if (Input.GetButton("Fire1")) {
    //Fire rate check
    if ((Time.time - lastFire) > fireRate && ammo > 0) {
        audio.clip = shootSound;
        audio.Play();
        var mf = Instantiate(muzzleFlash, muzzle.position, muzzle.rotation);
        Destroy(mf, flashLength);
        //Lose ammo
        ammo -= 1;
        var hit : RaycastHit;
        //if the player hits something
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), hit)) {
            //if they're an opponent
            if (hit.collider.tag == "Opponent") {
                hit.collider.gameObject.SendMessage("Damage", attack);
            }
        }
        lastFire = Time.time;
    }
    if ((Time.time - lastFire) > fireRate && ammo <= 0) {
        audio.clip = emptySound;
        audio.Play();
        lastFire = Time.time;
    }
}
}

```

I added Debug.Log after `if (Input.GetButton("Fire1")) {` and it only got called if I wasn't moving the player. I later made a very short program, the only scripts being:

```
#pragma strict

function Update () {
    if (Input.GetButton("Fire1")) {
        Debug.Log("FIRE");
    }
}

```

and

```
#pragma strict

function Update () {
    if (Mathf.Abs(Input.GetAxis("Horizontal")) > 0) {
        Debug.Log(Input.GetAxis("Horizontal"));
    }
}

```

The script only printed FIRE when the horizontal axis was 0.

# Answer
As stated by kprovost7314, the problem was with my computer's mouse settings, to fix it just turn the mouse delay off in mouse settings.
> 0 votes

# Answer
I have a sneaking suspicion that your raycast is hitting the player's collider and stopping there. Try offsetting transform.position along the forward vector far enough that it doesn't hit it.
> 0 votes

---
Tags: unity, javascript
---


# Question
Title: Isometric 2D game without tiles. Is there a solution?
Is it possible to create an isometric view of the game without the use of tiles?

I've already searched in stackoverflow.com and gamedev.stackexchange.com, but I could not find a simple solution for isometric maps using Corona SDK.

My goal is to create something like this picture: KRu.jpg

Do you think the game is made with tiles or not? Is using tiles the only solution for this kind of game?

Problems that I do not understand: – Overlapping objects that are farther – Change overlapping sprite when it moves around the map. When an object moves, some of its facilities will be closed, others are not. What is the logic of such a task? – The logic of the movement of objects along a path with no tiles

I do not want to reinvent itself what must have already decided.

If the tiles can not be avoided, I ask once again to leave links to materials that will solve the problem of isometry in the Corona SDK.

# Answer
These are 100% tiles/sprites or whatever. Noone draws that kind of detail with code.

Also it is not isometric, this is isometric:

The grid in your example seems to be a simple top-down square grid. Here is another example of a 2D top down square grid:

Do you see the difference?

Here is a great tutorial series to creating a game in that style: http://that-guy.net/articles/page3/ Start from page 3 and move through them one by one.
> 4 votes

# Answer
You can develop the game as a 3D game, but have a fixed camera angles and use "upright" sprites. A game that pulls this off is Bastion:

The animations are very smooth and well-done, but they still use sprite sheets.
> 2 votes

# Answer
This can be done in a variety of ways, most requireing use of a 3D engine.

In one of our prototype engines we did it by using a custom 3D engine based on LibGDX that used orthographic projection to get isometric view. Each "tile" was then rendered as a 3D cube with textures, so we had to create content for the textures. The seams required extra love in the form of seam sprites that made the transitions look better. This would not allow us to "rotate" the scene though.

There were no "tiles" in our engine, but it was kind of tile'ish. Other engines might abandon cubes in flavor of arbitrary 3D geometry and models instead. For a game-engine this is a perfectly valid idea. It all boils down to the look you want and the pipeline for content production you want. (and of course the platform you will deploy to).
> 0 votes

---
Tags: tiles, isometric, corona-sdk
---


# Question
Title: In Pygame, how can I check if an object is touching a color?
Is there a way to tell if a sprite is touching a specific color on the screen, maybe given as a hex code. I know you can do `pygame.sprite.collide` for sprites, but how can you do this for a specific color on the whole screen?

# Answer
Without knowing more about your game and why you want to do this, you might go about it this way:

At initialization, for every graphic drawn in your game, run it through a filter to find if they have that color in them at all. If it does, set a flag "hasThatColor" on the sprite and make a copy of them where you clear all pixels except the ones in that color.

In the main loop of your game during collision detection, look for the flag "hasThatColor" and if that flag is set, collide using the alternative sprite. It will of course only hit when a pixel is there of that color.
> 1 votes

---
Tags: pygame, color
---


# Question
Title: OpenGL not rendering full scene, it is a mystery
I am trying to draw a scene in the sort of style of mock vector graphics. I've helped on a 2D game before with GLSL, but I tried to keep a simple approach to this project since I'm working by myself, and I want to get the mechanics down before I have to fiddle too seriously with the graphics.

My problem is, for some befuddling (but probably simple) reason, not all of my scene is being rendered. Let me try to explain with my code ...

```
public class Game
{
    public static GameWindow gamewindow;

    ...

    public delegate void drawhandler(object sender, FrameEventArgs e);
    public static event drawhandler draw;

    public Game()
    {
        gamewindow = new GameWindow();
        gamewindow.Load += load;
        gamewindow.Resize += resize;
        gamewindow.UpdateFrame += update;
        gamewindow.RenderFrame += render;
        gamewindow.Run(60.0);
    }

    GameState.Ship ship;
    GameState.Space space;
    Camera camera;

    void load(object sender, EventArgs e)
    {
        gamewindow.VSync = VSyncMode.On;
        gamewindow.Width = 8*190;
        gamewindow.Height = 8*120;

        camera = new Camera(new PointF(0,0), new SizeF(gamewindow.Width, gamewindow.Height));
        space = GameState.Space.fromrandom(...);
        foreach (Physical p in space.bodies)
            if (p.GetType() == typeof(GameState.Ship))
                ship = (GameState.Ship)p;

        camera.lookat = ship.position;
    }

    void resize(object sender, EventArgs e)
    {
        camera.viewsize = new SizeF(gamewindow.Width, gamewindow.Height);
        GL.Viewport(0, 0, (int)camera.viewsize.Width, (int)camera.viewsize.Height);
    }

    void update(object sender, FrameEventArgs e)
    {
        ...
    }

    void render(object sender, FrameEventArgs e)
    {
        GL.Viewport(0, 0, (int)camera.viewsize.Width, (int)camera.viewsize.Height);
        GL.ClearColor(Color.Black);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.MatrixMode(MatrixMode.Projection);
        GL.LoadIdentity();

        //GL.Ortho(0, vw, 0, vh, 0.0, 4.0);
        camera.setortho();

        GL.MatrixMode(MatrixMode.Modelview);
        GL.LoadIdentity();

        if (draw != null)
            draw(this, e);

        gamewindow.SwapBuffers();
    }
}

```

So what happens is that the scene "space" is randomly created when loading. In order to draw the objects in "space", I do this:

```
public class Space
{
    public List<Physical> bodies = new List<Physical>();
    ...

    public Space(List<Physical> bodies)
    {
        this.bodies = bodies;
        init();
    }

    void init()
    {
        ...
        Game.draw += draw;
        ...
    }

    ...

    void draw(object sender, FrameEventArgs e)
    {
        foreach(Physical body in bodies)
            body.draw(sender, e);
    }

    ...
}

```

And finally, to draw the hero's ship in that list:

```
public class Ship : Physical
{

    ...

    public override void draw(object sender, FrameEventArgs e)
    {
        GL.PushMatrix();
            GL.Color3(color);
            GL.Translate(position.X, position.Y, 0);
            // HACK debug thrust vector
            GL.Begin(PrimitiveType.Lines);
                GL.Vertex2(0f,0f);
                GL.Vertex2(velocity.X*100, velocity.Y*100);
            GL.End();
            //
            GL.Rotate(rotation, 0, 0, -1);
            GL.Scale(SCALE, SCALE, SCALE);
            GL.Begin(PrimitiveType.LineLoop);
                GL.Vertex2(-1.0f, -1.0f);
                GL.Vertex2(-0f, 1.0f);
                GL.Vertex2(1.0f, -1.0f);
                GL.Vertex2(-0.0f, -0.5f);
            GL.End();
        GL.PopMatrix();
    }

    ...

}

```

Simple enough, this works as expected. The only other things I am drawing are "planets", which are simply circle line loops. Now let's draw a quad right in the middle for the hell of it ...

```
GL.PushMatrix();
    GL.Color3(Color.Orange);
    //GL.Translate(0, 0, 0);
    GL.Begin(PrimitiveType.Quads);
        GL.Vertex2(-50.0f, 50.0f);
        GL.Vertex2(-50.0f, -50.0f);
        GL.Vertex2(50.0f, -50.0f);
        GL.Vertex2(50.0f, 50.0f);
    GL.End();
GL.PopMatrix();

```

I'll put this after I invoke the "draw" event and before I swap buffers in the render method. Upon running, nothing changes!

I am almost certain that I am making a trivial mistake, but stepping through the code line by line I can find no error. I appreciate any advice in advance.

# Answer
Thanks to Lennart Rolland, I found out that the third-party font library I was using (QFont) had a bug in the way it manages its matricies. By moving my quad around in the drawing code, I was able to see where it got mangled. Thanks again for the help!
> 0 votes

---
Tags: c#, opengl, rendering, transformation, opentk
---


title: Shipping images with a C++ program

text:
# Question
Title: Shipping images with a C++ program
I've done hobby development in Java for a couple of years now, and I've just started learning C++. I understand syntax fairly well, but I'm extremely confused as to many structural facets of a typical program, namely shipping images/textures with the executable. Do I extract them to a data directory? Or do I encode them into the executable? And if the latter is the case, how do I include them in the compilation process? I'm sorry to ask such a basic question, but I'm having a particularly hard time finding the answer on Google.

# Answer
> 2 votes
Where to put the data depends on what the data is and how large it is.

You can embed the data in the executable and then just reference the byte array when you need it. This has the upside that the data is loaded in memory automatically but it will remain in memory until the game is exited. The data also cannot be changed unless you recompile the entire executable/dynamic library.

The other option is putting it in the file system under a data folder. This requires using an installer which is essentially a self-extracting compressed archive or a downloader. This also allows shipping and using DLLs and makes changing the assets easier by just changing those with an updater.

---
Tags: c++, image
---


title: Animating Two Objects' Interaction?

text:
# Question
Title: Animating Two Objects' Interaction?
I want to animate a character who could be doing any number of things.

Say for example, I want the character to get into bed, under the covers. Do I animate the character and the sheets moving together? Separately? If separately do I need to call both animations simultaneously to ensure it fits together properly?

Or, if two characters are going to hug. Do I animate them hugging or just animate them separately hugging and try to align them in-game?

# Answer
You animate them separately, as if they were together, and position them together in game. For 2D, you can use something like spine, which lets you animate all the parts of a character. Then, for the hugging example, you just animate a character hugging the air, and in game ensure that the character is positioned properly.

At least this one way you could do it. I'm sure there are others, like per rendered cutscenes. (That isn't suitable for basic interactions though!)

Let me provide you with some examples. A player throws a ball; because the ball needs to be detached, you animate the character and bind the ball to the hand, until the frame where the ball is released. You then apply physics to the ball.

A player gets out of bed; this is tricky because I don't know what you want this to look like. In an advanced 3D game you might want to simulate it, but in a little 2d game you could just have the player being animated to get up.

Hope this has helped.
> 0 votes

---
Tags: animation, skeletal-animation
---


# Question
Title: Raycast algorithm fails to collide with diagonal walls in specific locations
I'm having a problem with my ray-cast algorithm in a 2D tile-based universe. I feel the situation would be best explained with a picture, so here it is:

The ray, represented by the blue line, is passing "through" the wall to hit its target when the wall passes through a point where the quantized line moves diagonally and the wall is perpendicular to it. The raycast function is as such:

```
def raycast(pos, direction, level):
    dx, dy = direction
    t=0
    x, y = pos
    obj=None
    while not obj and t < 5000:
        t+=1
        x+=dx
        y+=dy
        obj=level.get_at((round(x),round(y)),True)
        pass
    return obj

```

Is there a simple, efficient way to eliminate this kind of edge case?

# Answer
> 1 votes
The simplest thing to do given your existing code, assuming there are no other complications, is to check both on the dx step and the dy step.

```
def get(x, y):
    # minimize code duplication
    return level.get_at((round(x), round(y)), True)

while t < 5000:
    t += 1
    x += dx
    obj = get(x, y)
    if obj: break
    y += dy
    obj = get(x, y)
    if obj: break

```

This has a tiny cost: it may unnecessarily check the same tile twice. If you later need to deal with this (e.g. an effect that applies to all tiles in the path of the ray) then you can just check if the rounded coordinates changed or not before doing anything.

If for whatever reason you need a more general and precise solution, you might be interested in my answer discussing a 3D voxel raycasting algorithm, which precisely simulates a ray with arbitrary origin and direction and reports every time it passes through a face of a voxel (moving from one tile to another). The algorithm shown can be applied to 2D simply by changing the 3D vectors to 2D and removing the conditions for the Z direction.

---
Tags: algorithm, raycasting
---


# Question
Title: What is scripting, and what is a scripting API?
What is scripting, and what is a scripting API? Is scripting the process of writing the game program, and is the scripting API (such as the Unity scripting API) the API provided by the game engine, which we use to create games?

# Answer
> 2 votes
Some of the answers are very convoluted, so I will make it brief.

Programming languages can be divided in two categories: **compiled and interpreted**.

In **compiled languages** (e.g. C) **the source code go through a compiler and produces an executable file** that can be run on a compatible machine.

In **interpreted languages** (e.g. Javascript) **the source code go through an interpreter at runtime**, executing it on the spot.

Therefore **an script is the source code for an interpreted language**. That means that the code needs an interpreter to be run.

In the context of games, some engines provide an API that represents the language that you write to use the functionalities of that engine.

Answering your question, usually games are written in compiled languages, limiting the scripts to very specific behavior (e.g. AI).

# Answer
> 1 votes
The principal difference between a script or a program is that the script is completely dependent of the API its scripting engine exposes to it.

If I code a game in C++ using a C++ game engine, I'm not doing any scripting, my resulting binaries are standalone and are not limited by the engine's API. I can use the virtual filesystem (if any) of the engine to read files, or I can completely bypass it and use calls to the operating system API.

Usually, when the game engine support scripting, I only can do what the scripting language syntax + game engine API allow.

Given that definition, If I'm coding a game engine and I want to support scripting, simply distribute a Python installer with the game engine and an API to allow the scripts to interact with the game engine may not count as scripting, as a Python program can do pretty much what a standalone program can. To adjust to my definition of scripting, a modified version of Python may be required, with many modules removed or somehow not allowed to use, then you can say the user of the engine is doing scripting, and not a full program that interact with the engine.

The javascript running in your web browser is a better example of what I have for scripting. You can do almost everything with it but I challenge you to write/read a file to the filesystem or use any of the OS APIs. It is completely restrained to what the browser engine allows It to do. It results convenient to the developer and protects the user.

There are game engines that have their own scripting language and others that implements an existing one.

# Answer
> 0 votes
Scripting for games can range from simple operations with home grown languages to writing the entire game in high level languages like Lua or C#.

If we take a car analogy, a game engine is like a real engine, and scripts are everything else. Scripts are the fuel, body, wheels, steering, paint job and so on. Scripts are what make the engine run, and tell it how to run. Even though a car may have the same engine, they can drive and look completely different. Which is how we can have the same game engine under the hood, but have completely different games on the outside.

Scripting APIs are the connection points with the game engine that allow us to control it. API stands for Application Programming Interface. It's the interface between the game engine and the scripting language. These APIs go both ways, they allow us to get information from the game engine and allow us to provide information/instructions to the game engine.

Some engines are flexible enough that they give you the power to create an entire game with scripts alone. Some engines are just part of the solution and are available to build upon to create a game.

# Answer
> 0 votes
First, what are our goals? We want a lot of people to use the engine as effectively and as quickly as possible to prototype and make full blown games.

* Ease of use -\> We need to abstract complexity
* Time needed to add and test a change -\> We would like to avoid compilation
* Debugging -\> We don't want people to touch our tested code; we need them to write their code separately from ours.
* Learning curve -\> We may not want our users to need to know C++ for various reasons and prefer they'd use a simpler language.

I think a more precise metaphor would be this:

The Engine, the body, the lights of the car and all that stuff you probably should never touch (if all you want is to get somewhere) are the Engine.

The API is the keyhole in the starter, the wheel, the break pedal, the stick, the gas pedal, the clutch and little plastic handle that you use to turn on the lights and the one for the windscreen wipers and air-conditioner's knob and the radio buttons are the API.

You don't need to know anything about the Engine, air-conditioning, radio signal or the light bulb in your headlights to get the car running, playing music, air-conditioned and functioning really well enough to get yourself from point A - to point B. You also don't need to build anything new or modify any of the parts of the car itself.

So the car is like the Engine, the Scripting API is like all the controls you take for granted when you ride the car that help you forget how complex the technology behind them is, **abstraction**.

So in short, a scripting API is an hopefully easy way, to control a very complex system you possibly have little to no knowledge of by the use of abstraction, a preferably easy to learn interface and sparing you the need to build these services yourself.

You can however still modify things "inside" with some Engines depending on the contract between the company (creator) and the end user.

# Answer
> 0 votes
If a game uses scripting, it means it has a system of reading in a secondary language and converting that code into something it can run. For example Legend Of Grimrock, the main engine is written in C/C++, but it uses Lua as a scripting language to manage in-game events and monsters.

The main purpose of scripting is to be able to change a game's behaviour without having to recompile the game itself. This is especially useful for things such as monsters' stats - you wouldn't want to recompile the entire game engine every time you changed a spider's attack stat.

A scripting API (application programming interface) is the way a scripting language interfaces with a game engine. The game engine exposes functions that can be called from the scripting language to do things like spawn monsters, give the player items or just display messages for the player to read.

---
Tags: scripting, terminology
---


# Question
Title: Variable Variables in unity using JavaScript?
I'm working on a custom built save system for a project a friend an myself are working on. Currently all variables that are saved to file, are stored as static variables in a global variables script file. The current save system involves running through each variable individually and saving it a line on a document, completely hard coded and very annoying to expand upon with new variables and elements in the game. I've decided to look into serialization of the global variables file, however static variables are not serializable. My solution is to use a getter and setter function, that is called instead of the direct GV.whatevervariable, that we currently use.

Ive been looking for something that allows me to store a variables name inside of another variable and then call it.

for example, say the variable in the GV script is A , the function would look like

```
static function getter(vget){
    return GV['vget'];
 }
 var A : string = "testcode"

```

where the call code would look like:

```
 var stuff : string = GV.Getter("A");

```

the problem with this though is that I keep getting "system.type does not support slicing" I currently cannot think of any other way to do this, and would really prefer not to hard code a getter and setter for each variable.

# Answer
> 1 votes
I don't quite understand why you need to do this, but seems like a convoluted way to retrieve values.

I assume that you need to retrieve both the value and the name of the variables in order to serialize and deserialize.

I think it would be easier to make the variables non static and just handle them like usual (maybe you could use some kind of singleton to handle this) but since I am no expert and don't fully understand your problem, lets try an alternative.

What if you store the variable name-value in either a Dictionary or an array of arrays? Then you could use an Iterator to access every value in the Dictionary/array easily.

That would be the most flexible solution since you only would need to add the pairs key/value into the dictionary, having the flexibility to add/remove variables at will.

---
Tags: unity, javascript
---