# Question
Title: Efficient approaches to updating adjacent grid tiles when one tile is disabled?
I'm trying to update the surrounding grid of tiles if one of them is disabled (not removed). For example, imagine we have a grid of tiles each with x representing one texture:

```
x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x

```

Now if some of these tiles are disabled, I need to update the surrounding tile textures to a different texture:

```
x, x, x, x, x, x
x, y, y, y, x, x
x, y,  , y, y, y
x, y,  , y,  , y
x, y, y, y,  , y
x, x, x, y, y, y

```

I'm trying to find the most efficient way of doing this. At present all of the tile data is stored in a dictionary with the key as a vector2.

I'm using C#/Unity 3D, however, I'm not necessarily looking for code but more or less logic on how to do this efficiently so I can program it in.

Any suggestions, examples, or what not would be helpful.

Thanks.

# Answer
The only way seems to look up the direct neighbors of the tile you disabled.

```
void DisableTile(Vector2 tileLocation)
   {
     tiles[tileLocation].Disable();
     if(tileLocation.X > 0) //if the neighbor on the left exists
     {
        tiles[new Vector2(tileLocation.X-1, tileLocation.Y)].RespondToNeighborDisabled(tileLocation); //update it
     }
     //repeat this process for all possible neighbors. (there should be 10 of those)
   }

```

A good way would be to implement a function like this on your tile entity, and to call it for all neighboring tiles when you disable or enable a tile :

```
void RespondToNeighborDisabled(Vector2 neighbor)
{
  if(this.Disabled) return;

  if(this.X < neighbor.X)
  {
     //the updated neighbor was to my right.
  }
  else if (this.X == neighbor.X)
  {
     //the neighbor was above or below me
  }
  else
  {
     //the updated neighbor was to my left
  }
  //etc.
}

```
> 0 votes

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


# Question
Title: How do I upscale my scene to a larger viewport?
I want to:

1. Render my scene to a small viewport (some divisor of the full screen size).
2. Stretch the rendered image to cover the full screen size.

For example I want to render a complex, very slow scene at 960x520 and then stretch the resulting image over a full 1920x1040 screen.

`Texture2D.LoadTextureFromTexture()` can achieve that result, but is incredibly slow (far, far too slow for gaming). Similarly, `Device.CopySubresourceRegion()` or `Device.CopyResource()` copies the pixels exactly based on the size of the image, so they don't stretch at all and a 960x520 image will simply take up a corner of the full screen.

I could render the texture onto a quad, but I wanted to know if there was a way to do this programmatically before writing a shader just to stretch an image.

# Answer
> 2 votes
You've basically already answered your question:

1. Render your scene to a texture of the desired size.
2. Render a full-screen quad with that texture applied.

You only need a very simple shader to perform step 2.

---
Tags: directx10, sharpdx
---


# Question
Title: Creating and joining a multiplayer game over a LAN
I'm trying to create and join a multiplayer game that has been created from a custom UDK installation.

It works correctly when two (or more) instances of the game are created on the same computer and are connected over localhost by running the following commands:

```
udk.exe server map_name
udk.exe 127.0.0.1

```

The problem comes when trying to connect to the game server over a LAN (with the command `udk.exe server_ip_address`); the clients are unable to connect and the default map is loaded. The server log reports a client disconnection from the computer trying to connect. The client log reports the error, `Error: Can't start an online game that hasn't been created`.

Both computers are able to ping each other, as well as both having their firewalls disabled. Many combinations of the command-line arguments for starting the server have been tried. Creating an installer from the server machine and installing a fresh copy of the game on the client has also been tried.

Any solutions on how to solve this issue would be appreciated.

# Answer
> 0 votes
I've finally found the correct answer, thanks to this thread on Epic's forum: http://forums.epicgames.com/threads/735202-Multiplayer-testing-problems-Solved

In order to play a networked game, the following files need to be identical on every client and also the server.

* GameUniqueID in Binaries\UnSetup.Game.xml
* UDKGame\Script\\\*
* UDKGame\Content\\\*
* UDKGame\Config\\\*

---
Tags: networking, multiplayer, udk
---


title: Ray picking and bounding boxes in Java

text:
# Question
Title: Ray picking and bounding boxes in Java
How do I check which bounding boxes (of different types) a ray, sent from the camera through the mouse-click coordinates, intersects with first in Java (and where)? I have arrays (box\_X, box\_Y, box\_Z, box\_X2, box\_Y2, box\_Z2) that store the coordinates and size of each box.

I don't understand very complex math (matrices, definitely nope). I am doing this from scratch so that I can better understand it and because there is a certain priority I want to use when picking objects (UI \> Entities \> Items \> Objects \> Terrain).

Thank you for your help!

Edit #1: So, I finished the code. Pasted it below so you guys can point out obvious errors in it for me. Or possibly, ways to do this easier. I have a feeling that there's something I'm missing, so...

```
private static int[] getIntersect(Vector3f ray) {
    int coords[] = new int[4];
    boolean planes[] = new boolean[6];
    Vector3f norm = null;

    Vector3f origin = new Vector3f(Disp.camX, Disp.camY, Disp.camZ);

    // Check which direction the ray is going.
    for (int plane = 0; plane < 6; plane++) {
        if (plane == posxy) {
            norm = new Vector3f(0f, 0f, -1f);
        } else if (plane == posxz) {
            norm = new Vector3f(0f, -1f, 0f);
        } else if (plane == posyz) {
            norm = new Vector3f(-1f, 0f, 0f);
        } else if (plane == negxy) {
            norm = new Vector3f(0f, 0f, 1f);
        } else if (plane == negxz) {
            norm = new Vector3f(0f, 1f, 0f);
        } else if (plane == negyz) {
            norm = new Vector3f(1f, 0f, 0f);
        }

        if (Vector3f.dot(ray, norm) < 0) {
            planes[plane] = true;
        }
    }

    norm = null;
    boolean solved;

    // Calculate intersections

    // First, choose the type of object to find collisions with.
    for (int type = 0; type < 5; type++) {
        solved = false;
        // Next, loop through layers.
        for (int dist = 0; dist < 70; dist++) {
            int pos[] = new int[3];
            float t = 0f;

            // Check for intersections on the planes
            for (int plane = 0; plane < 6; dist++) {

                // Skips calculation if the plane is not in the right direction.
                if (planes[plane] == true) {
                    int axis = 0;

                    // Set the normal to be correct.
                    if (plane == posxy ) {
                        norm = new Vector3f(0f, 0f, -1f);
                        axis = 2;
                    } else if (plane == posxz) {
                        norm = new Vector3f(0f, -1f, 0f);
                        axis = 1;
                    } else if (plane == posyz) {
                        norm = new Vector3f(-1f, 0f, 0f);
                        axis = 0;
                    } else if (plane == negxy) {
                        norm = new Vector3f(0f, 0f, 1f);
                        axis = 2;
                    } else if (plane == negxz) {
                        norm = new Vector3f(0f, 1f, 0f);
                        axis = 1;
                    } else if (plane == negyz) {
                        norm = new Vector3f(1f, 0f, 0f);
                        axis = 0;
                    }

                    // Calculate the point of intersection
                    t = ( dist - Vector3f.dot(origin, norm) ) / Vector3f.dot(ray, norm);
                    ray.setX(t * ray.getX());
                    ray.setY(t * ray.getY());
                    ray.setZ(t * ray.getZ());
                    pos[0] = (int) ray.getX();
                    pos[1] = (int) ray.getY();
                    pos[2] = (int) ray.getZ();

                    // Check if there is a collidable item of the type in the coordinates. If is, save the type and coordinates, then break out of the loop.
                    if (isCollidable(pos, type)) {
                        coords[0] = pos[0];
                        coords[1] = pos[1];
                        coords[2] = pos[2];
                        coords[3] = type;
                        solved = true;

                        break;
                    }
                }
            }

            if (solved) {
                break;
            }

        }
        if (solved) {
            break;
        }
    }

    return coords;
}

```

Edit #2: I actually found something myself. That t needs to be converted to coordinates via **p**(t)... And it's corrected.

# Answer
> 1 votes
We'll, to do that your going to need a basic understanding of Vectors. I'm not going to be able to provide a decent explanation of those, but there should be sources online for you so I'll leave you to your own devices there.

But first, in the fallowing equations:

1. **Bold** face text represents vectors (x, y, z, w)
2. non-bold face text represents scalars

So, on to the math, first we need to cover the intersection of a plane:

Consider a ray defined as: **p**(t) = **p**.origin + t **d**

where **p**(t) is a new point given the parametric distance t, p.origin is where the ray starts, d is the vector representing the ray's direction, and t is a parametric distance along the ray.

Now consider a plane defined as: **p** . **n** = d

Where **p** is a point on the plane, **n** is the planes normal, d is the offset from the origin (much like the c in `y = mx + c`), and the '.' is a dot product. Note: The **p** in the equation of the plane is not the same as the rays **p**, but they can be substituted.

So, we're looking for the point on the ray is a point on the plane. if an arbitrary point on the ray is **p**(t), and the **p** is an arbitrary point on a plane, then we are looking for:

**p**(t) . **n** = d

**p**(t) could be found if we knew what t was. so if we substitute the **p**(t) for "**p**.origin + t **d**", you get:

(**p**.origin + t **d**) . **n** = d

Which becomes:

t = ( d - (**p**.origin . **n**) ) / ( **d** . **n** )

If there is no intersection, then "**d** . **n**" will result in 0. So that's where you check if you want to see if they actually intersect.

so then your intersection point is, **p**(t), that's it. You can find t with the above equation. And that's how you find the intersecting point of a plane.

So, now we move to box. It's really just 6 different planes, right? Each planes normal goes along one of the axis (x+, y+, z+, x-, y-, z-), and you can find a corner point for each side, so you have the planes all-ready. That mean's, you can test each plane, and wherever t is the smallest is the closest intersection.

Once you have where the ray intersects with the AABB, you can test to see if that "intersection" point on the plane is actually inside or on the AABB. ( eg. p(t).x \<= AABB.max.x and p(t).x \>= AABB.min.x ) If that checks out for the X, Y, and Z, axis on any given plane, you have an intersection.

So, that's how you find if an cube intersects a ray, and where it intersects. To see if one AABB intersection is closer than another, you can compare 't' in each intersection. The closer t is to zero, the closer the AABB.

---
Tags: java, 3d, mathematics, raycasting
---


# Question
Title: How to program an enemy to attack when someone gets near it?
Like in free-roam RPGs, like Skyrim, I want to make a super-rudimentary screen with just two objects: player and enemy. The enemy will walk around randomly through AI algorithms, and will only fight back gracefully when the player gets near them, and when the player runs away past a certain distance it will continue its AI walking cycle. How do I do this?

Any guidance would be nice.

# Answer
> 2 votes
Here is a simple pseudo-code implementation that might give you some guidance, given the details you've described:

```
if ( length(playerPosition - enemyPosition) < enemyAttackRadius)
    enemy.attackPlayer()

if (enemy.isAttacking() && length(playerPosition - enemyPosition) > enemyDisengageRadius)
    enemy.stopAttacking()

```

# Answer
> 1 votes
Here's one basic way to implement it.

```
if (distance from player to enemy < attack_distance)
{
   enemy_target = player_position;
}
else if (distance from enemy to enemy destination is small)
{
   enemy_destination = random_destination();
   enemy_target = enemy_destination;
}
else
{
   enemy_target = enemy_destination;
}

if (enemy can attack player)
{
  attack();
}
else
{
  move enemy towards enemy_target;
}

```

For this implementation, your game state consists of three positions - one each for the current position of the player and enemy, and one for the current enemy destination, which should be initialized to the enemy's position.

# Answer
> 0 votes
You can create an area/bounding box bound to the NPC, when player enters in the box, you start processing the data

The suggestions in the other answers are checking constantly checking the distance of the player and the NPC, while your game is small this is fine, but that can become slower and slower as you add NPCs.

So create an areabox class, and apply to all your NPC. Create events on the areabox, or thresholds inner boxes, on which you can attach other events, like: if is in this area : give up. This way you can also handle the NPC orientation cause I'm pretty sure you don't want it to attack if NPC is giving shoulders to your player.

Now depending what GL library you are using(OpenGl/DirectX), collision detection can be generalized and is way cheaper to run, also you don't need to do the math on the position all the time

```
//Pseudo code:
function OnAreaColisionEvent(){
tryToAttack = true; // or whatever
};

function OnGiveUpAreaCollisionEvent(){
  stopChasing = true;
  ReturnToPatrol();
}

function InAttackAreaEvent(){
  if(closeEnough){
    performDamage();
  }
  else{
    runToPlayer();
  }
}

```

**UPDATE**
follow this link for more detailed info on how to speedup collision detection Opengl Collision detection methods

---
Tags: ai
---


# Question
Title: Color bleed on voxel edges when using anti-aliasing
My Minecraft-like game uses a texture containing four block IDs in each pixel (RGBA). These IDs are used in the shader to determine what color each whole block should be.

I'm having an issue with anti-aliasing because WebGL is assuming that vertices are flat with the texture, which isn't the case. As you can see from this image, green pixels are visible on the edges (as the next pixel on the texture is green):

With anti-aliasing:

Without anti-aliasing:

Here's my code:

```
gl.activeTexture(gl.TEXTURE1);

var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, float32Array);

gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);

gl.bindTexture(gl.TEXTURE_2D, texture);

var z = gl.getUniformLocation(material.program, "uSampler");
gl.uniform1i(z, 1);

```

Does anyone know how I would solve this? From what I've read, is this something that overdrawing would fix? Thanks.

# Answer
> 1 votes
If you don't combine your faces into a single manifold / submesh i.e. by setting up your triangle lists appropriately, that's exactly what happens. This can be seen between individual voxel columns in Minecraft, when heading underground (at least in older versions, you could see the blue sky peeking through when approaching the surface from underground).

You can either:

* combine all faces (presumably separate faces are a requirement for you, however)
* expand each face to intersect ever so slightly, to prevent this from occurring.

---
Tags: opengl-es, glsl, voxels, webgl, antialiasing
---


title: glIsBuffer unexpected result

text:
# Question
Title: glIsBuffer unexpected result
```
static void BindBuffer(BufferTarget target, GLuint buffer)
{
    if(!glIsBuffer(buffer))
        throw runtime_error("This is not a buffer. WTF?");

    glBindBuffer((GLenum)target,buffer);
    check_gl_error();
}

```

In my app, this always throws the exception. However, if I remove the `glIsBuffer()` check, everything works fine. Suggestions?

**Update**

Okay, turns out that glIsBuffer() returns false if the buffer is not bound. Is this expected behavior? If so, how do I check if a buffer handle is valid before attempting to bind it? calling glBindBuffer() then checking for an error seems like a stupid way to accomplish this.

**THE NEW QUESTION**

I'd start a new thread, but seems silly since it's directly related to the original post:

Is there a way to determine if a handle refers to a GL object (buffer, program, shader, etc) without trying to bind it first? Is it really recommended practice to bind it, then check for an error?

# Answer
To understand this we must look at how a buffer object is initially specified.

1. First of all we call glGenBuffers to create a name for the object.
2. Then we call glBindBuffer to bind the object to the GL context, and this also associates it with a buffer type via the target parameter.
3. Finally we make our initial glBufferData (or optionally glBufferStorage with GL4.4) call to specify it's storage.

Looking over the glIsBuffer documentation, particularly this part:

> A name returned by glGenBuffers, but not yet associated with a buffer object by calling glBindBuffer, is not the name of a buffer object.

It seems clear that both 1 and 2 must be done before glIsBuffer will return GL\_TRUE. However, once that condition has been satisfied, glIsBuffer for the same name will **always** return GL\_TRUE, even if that buffer name is not currently bound, and until glDeleteBuffers is called for the name (or the context is destroyed and recreated).

This makes sense because all that glGenBuffers does is give you an unused buffer object name. The name hasn't been associated with a buffer object yet; you're free to do anything you want with it, including not even use the name. The association of a name with a buffer object happens during the first glBindBuffer call that uses the name: we're using that name now, so it's no longer free, so glIsBuffer can return GL\_TRUE for that name.

This behaviour is also documented for glGenBuffers:

> No buffer objects are associated with the returned buffer object names until they are first bound by calling glBindBuffer.

Note that the documentation is consistent for both - it's the **first** binding that creates the association, so it's only the **first** binding that is required for glIsBuffer to return GL\_TRUE.

In other words, and unless you've got a driver bug, the following tests should run as expected:

```
GLuint testBuffers[2] = {0, 0};
GLboolean isBuffer[2] = {GL_FALSE, GL_FALSE};

glGenBuffers (2, testBuffers);  // just generate names; they're not buffers yet

isBuffer[0] = glIsBuffer (testBuffers[0]);  // returns GL_FALSE
isBuffer[1] = glIsBuffer (testBuffers[1]);  // returns GL_FALSE

glBindBuffer (GL_ARRAY_BUFFER, testBuffers[0]); // this is a buffer now
glBindBuffer (GL_ARRAY_BUFFER, testBuffers[1]); // this is a buffer now
glBindBuffer (GL_ARRAY_BUFFER, 0);  // no binding

isBuffer[0] = glIsBuffer (testBuffers[0]);  // returns GL_TRUE
isBuffer[1] = glIsBuffer (testBuffers[1]);  // returns GL_TRUE

```

It seems evident that you're calling your `BindBuffer` function as part of your buffer object creation, so it's happening in-between steps 1 and 2 above; if that's the case then yes, it's expected that your initial glIsBuffer call is going to return GL\_FALSE.

Personally I'd advise that you refactor your buffer object creation. The 3 steps (glGenBuffers, glBindBuffer, glBufferData) can be combined into a single function. Save your own `BindBuffer` call for subsequent (i.e. post-creation) use instead, as use of it for creation (if I'm right) is the root cause of your problem.
> 6 votes

---
Tags: opengl, c++
---


# Question
Title: How does the Direct3D 9 rasterizer determine triangle coverage?
I'm working on a software rasterizer to use in my project. I have implemented one that works well, however, often my rasterizer under or overestimates triangle coverage. I need perfect emulation of the hardware rasterizer. I'm using the exact same rasterization rules from MSDN (including the top-left rule).

How does the Direct3D rasterizer determine which pixels are covered by a triangle? What's the algorithm being employed? Does it rasterizer use the pixel center coordinate or the pixel's top-left coordinate when determining triangle coverage?

When I use the pixel's top-left coordinate I get better results. I've also been determining the planes perpendicular to the triangle's edges, then admitting pixels if their coordinate is "behind" each plane.

# Answer
> 4 votes
If you pretend a pixel is a square (see *A Pixel is Not a Little Square*), then the center of that square is the pixel coordinate. This is documented in Direct3D 9's rasterization rules (emphasis mine):

> Direct3D uses a top-left filling convention for filling geometry. This is the same convention that is used for rectangles in GDI and OpenGL. In Direct3D, the center of the pixel is the decisive point. **If the center is inside a triangle, the pixel is part of the triangle.** Pixel centers are at integer coordinates.

For pixels that are part of the triangle, pixels on the top edge and the left edge are filled. Pixels on the bottom and right edge are not. A top edge is completely horizontal, otherwise it does not exist.

You may want also peruse the documentation on mapping pixel coordinates to texel coordinates in D3D9 and, should you ever consider moving to D3D10+, take a look at the modern rasterization rules.

It's also worth noting that you will see variation in this behavior from hardware to hardware (although usually that variation is minimal). It could be that that explains your discrepancies, and it also means it will be extremely difficult for you to achieve a 100% match to a hardware-based rasterizer from D3D; consider using the reference device when doing your testing.

---
Tags: c++, directx9, pixel, software-rendering, rasterization
---


title: Windows Events lag behind

text:
# Question
Title: Windows Events lag behind
I'm making a simple openGL application and so far I can get the window to display, the update/render loop work, and it processes windows events (like WM\_QUIT and WM\_MOUSE). I've found though that there is a noticeable lag between, say, pressing the space bar, and receiving the event in the WndProc function (in this case, WM\_KEYDOWN.) Is this a result of using WndProc and not some fancy direct input system? Is there a better way of getting, say, the mouse position?

I can even tie one of my objects to draw itself at the current mouse position (updated in that same WndProc function) and while it does so fine, to the proper coordinates, it's always behind the mouse. I can post some code if you guys are interested but it's about the most standard update loop / event processing code out there.

Thanks for the help!

EDIT: Since you're curious, here's the main():

```
int main(int argc, char **argv){
  MSG msg;

  if (!createEngineWindow("Expanse")){
    destroyEngineWindow();
    return 1;
  }

  ShowWindow(hWnd,SW_SHOW);     // Show The Window
  SetForegroundWindow(hWnd);    // Slightly Higher Priority
  SetFocus(hWnd);             // sorry, other windows

  initGL();
  startup();

  updatePreviousTime=updateCurrentTime
                    =renderPreviousTime
                    =renderCurrentTime
                    =static_cast<float>(clock())/CLOCKS_PER_SEC; // start the stopwatches
  while (!done){
    previousMousePosition=mousePosition;

    while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)){
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
    updatePreviousTime=updateCurrentTime;
    updateCurrentTime=static_cast<double>(clock())/CLOCKS_PER_SEC;
    uDT=updateCurrentTime-updatePreviousTime;
    updatePhase(uDT);

    if (updateCurrentTime>0.01 && uDT>0.01){ // ignore the first few frames
      double framerate=1.0/uDT;
      averagedFrameRate=Lerp<double>(averagedFrameRate,
                                     framerate,
                                     0.3);
    }

    renderPreviousTime=renderCurrentTime;
    renderCurrentTime=static_cast<double>(clock())/CLOCKS_PER_SEC;
    rDT=renderCurrentTime-renderPreviousTime;
    renderPhase(rDT);

    SwapBuffers(hDC);
  }

  cleanUp();
}

```

And the WinProc, which handles the DispatchMessage thing (or TranslateMessage, or something.)

```
LRESULT CALLBACK WndProc(HWND hWnd,       // Handle For This Window
                         UINT uMsg,       // Message For This Window
                         WPARAM wParam,   // Additional Message Information
                         LPARAM lParam){  // Additional Message Information

  switch (uMsg){
    case WM_CLOSE:        // Did We Receive A Close Message?
      PostQuitMessage(0); // Send A Quit Message (we're going, hold on already.)
      done=true;
      return 0; // Jump Back
    case WM_ACTIVATE:
      if (!HIWORD(wParam))  // Check Active state
        windowActive=true;  // Program Is Active
      else
        windowActive=false; // Program Is No Longer Active
      return 0;

    case WM_MOUSEMOVE:
      if (!ignoreMouseMove)
        mouseMove(LOWORD(lParam),
                  HIWORD(lParam));
      else
        ignoreMouseMove=false;
  }
  return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

```

and the window creation:

```
bool createEngineWindow(string title){
  int PixelFormat;    // Holds The Results After Searching For A Match
  WNDCLASS wc;        // Windows Class Structure
  DWORD dwExStyle;    // Window Extended Style
  DWORD dwStyle;      // Window Style

  // Window Sizing and Position
  screenWidth=GetSystemMetrics(SM_CXSCREEN);
  screenHeight=GetSystemMetrics(SM_CYSCREEN);
  RECT WindowRect;
  WindowRect.left=(long)0;
  WindowRect.right=(long)screenWidth;
  WindowRect.top=(long)0;
  WindowRect.bottom=(long)screenHeight;

  // Windows Style
  hInstance=GetModuleHandle(NULL);  // Grab An Instance For Our Window
  wc.style=CS_OWNDC |               // We want our own device context
           CS_DBLCLKS;              // We want double clicks too
  wc.lpfnWndProc=(WNDPROC)WndProc;  // Our WndProc handles events first.
  wc.cbClsExtra=0;                  // No Extra Window Data
  wc.cbWndExtra=0;                  // No Extra Window Data
  wc.hInstance=hInstance;           // Set The Instance
  wc.hIcon=LoadIcon(NULL,           // Load The Default Icon
                    IDI_WINLOGO);
  wc.hCursor=LoadCursor(NULL,             // Load The Arrow Pointer
                        IDC_ARROW);
  wc.hbrBackground=NULL;            // No Background Required For GL
  wc.lpszMenuName=NULL;             // We Don't Want A Menu
  wc.lpszClassName="TorqWindow";    // Set The Class Name

  if (!RegisterClass(&wc)){
    return false;
  }

  // Fullscreen settings
  DEVMODE dmScreenSettings;         // Device Mode
  memset(&dmScreenSettings,         // Makes Sure Memory's Cleared
         0,
         sizeof(dmScreenSettings));
  dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
  dmScreenSettings.dmPelsWidth=WindowRect.right; // Selected Screen Width
  dmScreenSettings.dmPelsHeight=WindowRect.bottom; // Selected Screen Height
  dmScreenSettings.dmBitsPerPel=24; // Selected Bits Per Pixel
  dmScreenSettings.dmFields=DM_BITSPERPEL // What the Devmode will set (it could also work with printers.
                          | DM_PELSWIDTH
                          | DM_PELSHEIGHT;
  if (!ChangeDisplaySettings(&dmScreenSettings,
                             CDS_FULLSCREEN))
    return false;

  dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
  dwStyle=WS_POPUP;          // Windows Style
  ShowCursor(TRUE);         // Do not hide Mouse Pointer

  AdjustWindowRectEx(&WindowRect, // Adjust Window to fit fullscreen
                     dwStyle,
                     FALSE,
                     dwExStyle);

  hWnd=CreateWindowEx(dwExStyle, // Extended Style For The Window
                      "TorqWindow",     // Class Name
                      title.c_str(),    // Window Title
                      dwStyle |         // Defined Window Style
                      WS_CLIPSIBLINGS | // Required Window Style
                      WS_CLIPCHILDREN,  // Required Window Style
                      0, 0,             // Window Position
                      WindowRect.right, // Window Width
                      WindowRect.bottom, // Window Height
                      NULL,             // No Parent Window
                      NULL,             // No Menu
                      hInstance,        // Instance
                      NULL);            // Dont Pass Anything To WM_CREATE
  if (!hWnd) // If we didn't succeed with making a window
    return false;

  hDC=GetDC(hWnd);
  if (!hDC) // Did We Get A Device Context?
    return false;

  // Grab a pixel format descriptor. This tells Windows what kind of buffer we want.
  // see http://msdn.microsoft.com/en-us/library/dd368826(VS.85).aspx
  static    PIXELFORMATDESCRIPTOR pfd={ // pfd Tells Windows How We Want Things To Be
    sizeof(PIXELFORMATDESCRIPTOR),    // Size Of This Pixel Format Descriptor
    1,                    // Version Number
    PFD_DRAW_TO_WINDOW |  // Format Must Support Window
    PFD_SUPPORT_OPENGL |  // Format Must Support OpenGL
    PFD_DOUBLEBUFFER,     // Must Support Double Buffering
    PFD_TYPE_RGBA,        // Request An RGBA Format
    16,                   // Select Our Color Depth
    0, 0, 0, 0, 0, 0,     // Color Bits Ignored
    0,                    // No Alpha Buffer
    0,                    // Shift Bit Ignored
    0,                    // No Accumulation Buffer
    0, 0, 0, 0,           // Accumulation Bits Ignored
    16,                   // Z-Buffer (Depth Buffer)
    0,                    // No Stencil Buffer
    0,                    // No Auxiliary Buffer
    PFD_MAIN_PLANE,       // Main Drawing Layer
    0,                    // Reserved
    0, 0, 0               // Layer Masks Ignored
  };

  PixelFormat=ChoosePixelFormat(hDC,&pfd);
  if (!PixelFormat)
    return false;

  if (!SetPixelFormat(hDC,PixelFormat,&pfd))
    return false;

  hRC=wglCreateContext(hDC);
  if (!hRC)
    return false;

  if(!wglMakeCurrent(hDC,hRC))  // Try To Activate The Rendering Context
    return false;

  GLenum err = glewInit();
  if (GLEW_OK != err)
    return false;

  return true;
}

void destroyEngineWindow(){
  ChangeDisplaySettings(NULL,0);
  ShowCursor(TRUE);

  if (hRC){
    wglMakeCurrent(NULL,
                   NULL);
    wglDeleteContext(hRC);
    hRC=NULL;
  }

  if (hDC){
    ReleaseDC(hWnd,hDC);
    hDC=NULL;
  }

  if (hWnd){
    DestroyWindow(hWnd);
    hWnd=NULL;
  }

  UnregisterClass("TorqWindow",
                  hInstance);
  hInstance=NULL;
}

```

Thanks for the help!

# Answer
> 4 votes
If you have VSYNC on, and if you handle windows events in the same thread where you handle rendering, you will experience some small but noticeable input lag. The SwapBuffers() function will wait for vertical sync, which slows down main loop, which again slows down recieving of windows events.

There are several different solutions.

1. The easiest one would be just to ignore the small lag. For most small games it's not harmful.
2. Call the render function only after some time has passed since last render call.
3. Handle windows events in separate thread.

If you don't want to set up separate thread for that, and don't want to ignore the input lag, then the 2nd option works something like this:

```
double lastTime, lastRenderTime;
double desiredFps = 60;

while(!quit) {
    // Get current time and delta in milliseconds
    double currentTime = getCurrentTime();
    double delta = currentTime - lastTime;

    // Update the last time for next loop round
    lastTime = currentTime;

    handleWindowsEvents();

    update(delta);

    // Call render only when needed
    if(lastRenderTime <= currentTime - (1000.0/desiredFps)) {
        double renderDelta = currentTime - lastRenderTime;
        lastRenderTime = currentTime;
        render(renderDelta);
    }
}

```

You might need to tweak the if clause to be more accurate, but that's how it basically works. You can use that same method for the update function if you want to tweak how often it gets called.

Also, you might want to add in a mechanic for detecting if your render function takes too much time to be able to call it 60 times a second. In this case, you might want to change the desired FPS to half of the current desired FPS to prevent some unwanted rendering behaviour. The key is to have consistent rendering interval.

---
Tags: c++, input, windows, events, lag
---


# Question
Title: How to debug framerate drops with VBOs, OpenGL
I'm working on an experimental app to test how VBOs perform when rendering a minecraft-like world. If the performance is better than what I use now I'll update my actual game. Based on what everyone says, VBOs should totally be the right direction, but it's really hard making that become a reality.

I've finally gotten to a point where I've replicated culling block faces, I'm properly using the buffer IDs to render and not building the VBO every frame - there's no a ton of performance tweaking left aside from:

* Using an indexed system so I can send fewer vertices
* Using a ByteBuffer for my color/texture values instead of floats (I need to find a good way, right now everything is interleaved)
* I could take block face culling a little further because in the test app, they don't check across chunks for solid blocks.

My primary issue is that for some reason, when I render 15x16 chunks (16x16x16 blocks per chunk in my test app) the performance and rendering is great. Movement is fluid, 60fps.

At 16x16 chunks, performance drops to like 5fps. I've run profiling like VisualVM and see no unusual differences in the speeds/memory of the code between the two states. It's odd how the addition of one extra row of chunks can take performance down so much - there must be some specific threshold I cross.

**How can I better debug what's happening? Where should I be looking?** There are no console errors.

This test app is open source so you can look at the code:

World Chunk Rendering

**Update** I've updated my actual game with the VBO work I've been doing in this test app and the performance of the 10x10 grid of chunks (16x16x128) was so horrid that my system took minutes to allow me to kill the app. I'll certainly spend some time adjusting things and making sure that it's performance-tuned for my app, but wow - still not seeing how VBOs are all they're cracked up to be.

# Answer
For the actual problem (slow rendering of VBO), you might try to use instancing. That only helps if you have hundreds or thousands of objects to render.

You can debug the problem several ways. AMD Perfstudio and Nvidia Nsight are tools for getting debug data from the GPU. You could use those to try to find out the problem.

Another way to debug the problem is to measure the time each operation takes. Timing a certain operation looks like this:

```
glFinish(); // Make sure there is no work queued in the GPU
double timeBefore = getCurrentTime(); // milliseconds
theGlDrawCallOrBufferUpdateEtc(); // the GL function you want to measure
glFinish(); // Finish that
double timeAfter = getCurrentTime();

double timeTheFunctionTook = timeAfter - timeBefore;

```

This might give you a **hint** of which GL calls are causing the lag. You can use the same thing to measure any other parts of the code too. if there are no GL calls, just drop the glFinish() calls as they are not required then.
> 1 votes

---
Tags: opengl, java, vbo
---


# Question
Title: Target tracking with a small delay (actionscript 3.0)
I'm having trouble thinking of a good method to track my character with an enemy attack. Of course, I don't want the attack to track my character's current position; I want it to track where the character was about 1 second before (so you can move around and make the attack miss and loop around you sort of a thing).

The general structure of my game uses a timer to update all of my events. I have a timer going off every 25 milliseconds that updates everything, including my player's position and the enemies position. Right now I just have the enemy attack directly targeting my character....which works fine except that it's impossible to escape =p.

Let me know if I didn't supply enough details. My approach was going to basically be get my character's position from about 1 second ago, then have the enemy target that position, the only problem is I can't think of a good way to get my character's position from previous times. Thanks for the help!

# Answer
> 1 votes
One simplistic approach can be by making the targeting fuzzy. Instead of directly targeting a location, choose a random location within a given radius range. Ideally you are projecting a point you are targeting based on velocity and heading of both your missile and the target, and then applying the fuzzieness.

Having a minimum radius on that fuzziness can decrease the maximum accuracy. So that random location is never on target directly if you don't want it to be.

You could then also shrink how fuzzy that is the closer you get just by shrinking the min/max radius, so that you are not missing the target based on fuzzieness.

Obviously the more fuzzieness you have, the more likely that missile is going to miss that target.

# Answer
> 1 votes
The simplest thing to try: Make the rate that the missile turns very low while the rate that it moves forward is very high. That way it can't make quick turns and will zoom past a dodging target.

Another approach that may look better: Track only until the missile is within a certain distance of the target, and then the missile is locked onto it's course until it has passed the target position. That way it won't correct again until after zooming past.

# Answer
> 0 votes
I am answering exactly this question:

> I want it to track where the character was about 1 second before

Solution #1, simple.

Your requirement may be rephrased as "aiming position must reach actual terget position within 1 second". When missile just spawned, set aiming position same as actual target position. On every update, lerp aiming position to target position, using `dt/lag` as lerp factor. Here `dt` is time since previous update and `lag` is desired delay. Alternatively, when missile just spawned, set its aim bit towards its current flight direction, so it will not instantly turn to target.

Solution #2, precise.

On every update save pair of current time and target position into FIFO-queue, but also remove from that queue previous items thar are older than 1 second. This way you got movement history for your entity. Use current record in queue as aiming position.

Solution #3.

There is defect in previous solutions: fast moving missile may jump ahead its aim. I can imagine few ways for solving this, but I want to show simplest. Take solution n1 as base, and instead of lerping aim towards target, just set aim as lerp between missile position and target position with same factor `dt/lag`.

```
missile::update(dt)
{
    lf = dt / me.desiredLagTime;
    me.aimPos = me.target.pos * lf + me.pos * (1.0 - lf)
}

```

---
Tags: actionscript-3
---


title: Creating a knockback effect

text:
# Question
Title: Creating a knockback effect
I'm fairly new to creating a 2D game in java and I'd love some help. I'm trying to create a sort of knock back effect the enemies have on you. So when you are touched by a enemy you will:

1. lose life
2. be knocked back a few pixels

I thought about saying something simple such as:

```
    if ((player.x & player.y) == (enemy.x & enemy.y)){
        player.x += 8;
        player.y += 8;
    }

```

But seeing as this will only push you back with no hope of moving while being pushed, I didn't want to use it. Is there any simple, yet effective way for going about this?

# Answer
> 3 votes
Usually this is done by changing velocity.

If you simply change position, there is danger of stucking in walls (and other solid objects, including enemises) or falling/jumping through them (depends on your collision system and level design).

Also you need to configure friction and/or gravity accordingly, so player will not fly into open space after one kick.

If inertial sliding will be too smooth for you, some engines allowing to attach short-living constant-power pushing forces to objects.

Honestly, it is hard to answer without knowing anything about your physics engine and its capabilities.

---
Tags: java, 2d, software-engineering
---


# Question
Title: Rotation about a point in OpenGL ES 2 (Android)
I'm trying to implement rotation about a point (the origin) using quaternions. My camera is at `(0, 0, 3)`. I'm applying all the operations to the view matrix. Basically my rotation is at the moment not about the origin, but about the camera position. Here's what I'm trying to do:

```
public void rotate(float phi, float theta) {
        Quaternion phiRot = new Quaternion(0, 1, 0, (float)Math.toRadians(phi/2));
        Quaternion thetaRot = new Quaternion(1, 0, 0, (float)Math.toRadians(theta/2));

        Quaternion temp = thetaRot.mul(phiRot);

        camera.translate(0, 0, -3);
        camera.multiply(temp.toMatrix());
        camera.translate(0, 0, 3);
}

```

where

```
public void translate(float x, float y, float z) {
    Matrix.translateM(mViewMatrix, 0, x, y, z);
}

public void multiply(float[] matrix) {
    Matrix.multiplyMM(mViewMatrix, 0, matrix, 0, mViewMatrix, 0);
}

```

Any idea what I'm doing wrong?

EDIT: Solution that seems to work. Based off Milos' answer.

```
public void rotate(float phi, float theta) {
    Quaternion phiRot = new Quaternion(0, 1, 0, (float)Math.toRadians(phi/2));
    Quaternion thetaRot = new Quaternion(1, 0, 0, (float)Math.toRadians(theta/2));

    Quaternion temp = thetaRot.mul(phiRot);
    float[] rotate = temp.toMatrix();
    float transMinus[] = new float[16];
    float transPlus[] = new float[16];
    Matrix.setIdentityM(transMinus, 0);
    Matrix.setIdentityM(transPlus, 0);
    Matrix.translateM(transMinus, 0, 0, 0, -3);
    Matrix.translateM(transPlus, 0, 0, 0, 3);

    Matrix.multiplyMM(rotate, 0, transMinus, 0, rotate, 0);
    Matrix.multiplyMM(rotate, 0, rotate, 0, transPlus, 0);

    camera.multiply(rotate);
}

```

# Answer
> 1 votes
It seems to me that the translate function moves the camera in world coordinates, not in camera's own coordinate system.

You basically want to translate camera along it's forward vector by 3, rotate camera, then move back along the newly-rotated forward axis. Instead of doing the Matrix.translateM(...), try making a translation matrix along z axis, then (pre)multiplying it with camera rotation matrix. This *should* make it move along its forward vector properly and get you the wanted effect.

I used this way in achieving the similar thing in my game. Let me know if there's a better way.

---
Tags: rotation, opengl-es2
---


# Question
Title: Get current window position with Monogame
I'm looking for some help figuring out the current position of the Monogame windowed form. My ultimate goal is to figure out when the user is clicking inside of the game window and where they're clicking.
Getting the mouse position is easy:

```
var mouseState = OpenTK.Input.Mouse.GetState();
var mousePosition = new Point(mouseState.X, mouseState.Y);

```

That returns a Point relative to the computer's display. I'm running my app as a windowed form, so I need to compute the mouse position inside of the window based off the forms current location on the monitor.
And in reading up on the subject, it looks like this should give me the point data I need:

```
System.Windows.Forms.Form form = (System.Windows.Forms.Form)System.Windows.Forms.Control.FromHandle(this.Window.Handle);
var formPosition = new Point(form.Location.X, form.Location.Y);

```

Trouble is, that the object form is always coming back as a null object. this.Window.Handle will return a valid (System.IntPtr) handle ID, but the form object is never created.

While I'm stopped at a break point, I can see the data I need inside the this.Window located at ((OpenTK.NativeWindow)(((Microsoft.Xna.Framework.OpenTKGameWindow)(this.Window)).window)).Location - but that location is a non-public location so I can't get it out of there.

Any suggestions?

# Answer
I think you're using the wrong Mouse.GetState() method. It appears you are using the OpenTK implementation, you should really be using the MonoGame implementation that lives in the Microsoft.Xna.Framework.Input namespace.

```
var mouseState = Microsoft.Xna.Framework.Input.Mouse.GetState();

// this is the position relative to the top left corner of the window.
var mousePosition = new Point(mouseState.X, mouseState.Y);

```

The documentation on MSDN is pretty terrible around this, but if you read the words around the related method Mouse.SetPosition you'll notice it says "Sets the position of the mouse cursor relative to the upper-left corner of the window."

It stands to reason then, that the MouseState.X and Y are also relative to the upper-left corner of the window.
> 2 votes

# Answer
If you only need to know if the user is clicking inside the form, you wouldn't need all that code.

```
int width = graphics.PreferredBackBufferWidth;
int height = graphics.PreferredBackBufferHeight;

var mouseState = OpenTK.Input.Mouse.GetState();
var mousePosition = new Point(mouseState.X, mouseState.Y);

if (mousePosition.X < 0 || mousePosition.Y < 0 || mousePosition.X >= width || mousePosition.Y >= height)
{
    // Click was outside window
}
else
{
    // Click *inside* window
}

```
> 1 votes

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


# Question
Title: Replicating no. of sprites without letting the app to slow down and crash
Is it possible that if I'm making a a simple drag-n-drop game, does making a new sprite via constructor with texture as a parameter makes the game slower and depletes more memory until it crashes or does making a new texture via constructor cause the memory to go slow? I'm on a revision for the new drag-n-drop puzzle game where the only goal is to stack the most no. of objects as you can before it falls off the platform. Is it a good idea to create another sprite with texture as a parameter every time a player drag-n-drop another object?

Here's the start of the dry run looked like and I set it to debug mode so that the platform is completely block the pit to test the replication test.

Afterwards, when it reaches from hundreds to thousands, this will be like this and the game gets slower.

When the game crashes, here's the result via **Logcat**:

```
12-11 16:38:53.953: E/AudioTrack(25701): AudioFlinger could not create track, status: -22
12-11 16:38:53.953: E/SoundPool(25701): Error creating AudioTrack
12-11 16:38:53.993: D/dalvikvm(25701): GC_EXPLICIT freed 947K, 14% free 14414K/16672K, paused 2ms+4ms, total 96ms
12-11 16:39:16.363: E/AudioTrack(25701): AudioFlinger could not create track, status: -22
12-11 16:39:16.363: E/SoundPool(25701): Error creating AudioTrack
12-11 16:39:16.433: D/dalvikvm(25701): GC_FOR_ALLOC freed 2120K, 15% free 14418K/16848K, paused 47ms, total 47ms

```

By the way, I'm using **BodyEditor** library for Box2D program and rendering, a physics engine.

# Answer
The use of keyword `new` results in costly allocation to heap memory during play.

On mobile apps (not only!), you should always pre-allocate your maximum number of objects, and assign them to an object pool. During initialisation, create an object pool consisting of say, 200 objects. Whenever a object is to be created or destroyed, you simply take one from the pool, or put it back into the pool, respectively. The pool is simply a list holding references to existing, unused objects. In some implementations, it's a class wrapping that list and providing pool access methods.

This pooling approach should apply to your box2d objects and your graphics objects like `Sprite`; for that matter, any object which is used to compose your "Fruit" entities.
> 2 votes

# Answer
You should be able to create a lot more sprites than you've currently got, as long as you don't create a new Texture each time.

From your pictures, you seem to use textures more than once, so you should be able to have something like:

```
// In some class that manages sprite textures
Texture blueSquareSmiley = new Texture(...);
Texture yellowSquareX = new Texture(...);

// Then where you create your sprites
for(... 1000 times ...) {
    Sprite aBlueSquareSmiley = new Sprite(blueSquareSmiley);
    world.addSprite(aBlueSquareSmiley);
}

```

That's how you should be able to manage your textures.

Based on your Logcat, it looks like either the Audio system can't allocate something (could be some other application though) or perhaps the is GC being busy (though it is freeing stuff on the order of 1MB which isn't much).
> 2 votes

---
Tags: textures, sprites, libgdx, physics-engine, memory-efficiency
---


# Question
Title: How can I tell the player that a key or other item can be discarded?
We're working on a survival horror classical Resident evil (1, 2, 3, 0, REmake) type of game - link.

I'm using Unity3D with C#.

There's something that's kinda puzzling me - more a game design question than a technical one.

Item usage - In Resident Evil - You could use a key to open more than one door - when it's not needed anymore you'd get a "XXX key is not deeded anymore, discard?" YES|NO. I was curious as to how would one implement this in an elegant manner...

1. First, we should discuss who knows about the other, is it the key that knows what doors it opens? or is it the door that knows which key fits in its keyhole? - Well, it's kinda both if you think about it. For example, a diamond shaped key, opens doors with diamond shaped keyholes - Looking at the key you know which doors it could open - Same said about the door - you look at it and know what type of key you need...
2. If we went with the first approach in that a key knows what doors it unlocks, we should have to assign those doors to the key - handle them to it in some way - What if you had a key, that will remain with you for a very long period - let's say it opens so many doors that some of those doors are in the middle of the game - Why would a key you pickup in the beginning of the game, carry information about something that would occur in the middle of the game? Seems redudant to me... So I wouldn't go with this approach.
3. OK, so you tell doors which key fits in them - Get in a scene with 3 doors, information about what keys to use for those 3 doors are loaded, and nothing else! - So I guess, we got that out of the way...
4. Now, how would you tell, that a key is not needed anymore? I thought of two approaches - both have downsides:

1. Have a `nUsages` counter - that you preset (via inspector for ex) - This way you have to know exactly how many times it will be used in the game - Add another door and forget to increment the counter, you get screwed. Each time you open a door/use the key, you decrement the counter by one, reach zero -\> "You don't need this key anymore, discard\>" YES|NO.
    2. Detect the doors a key gets used in dynamically (When you pick up the key?) - So maybe you'd have like a database of `DoorTriggers` \- Pickup key -\> Look up the key's entries and increment the counter that way - This is slow relatively to the previous method. It's also kinda foggy a bit - You know, a key could open doors in scenes other than the one it's picked in - how would I go about searching for its doors in this case? (Getting a bit Unity3D-specific here...) - I guess, to answer this we must answer: How do doors register themselves in our db? Upon scene load? If that's the case, then a key picked up a scene A - can't detect a door it opens in Scene B where B \> A...

Note that a key is just an example - There are Usable items that I don't need to do this - Like health items - The items that I must perform this operation on, are "Other" items, like keys, a crank, a wrench, a pipe, a holeopener, etc.

Again, this is what's off the surface of my head.

What do you think of my assessment? How would you implement this feature? (maybe in a better way?) (General ideas)

And if you'd go with my 2nd method in adding the stuff dynamically upon item pickup, how would you do it in Unity3D - More accurately, how would you look up the key's doors that resides in other scenes? and how where would you let the doors register themselves in teh db? (General approaches again)

Thanks for any help.

**EDIT**: UA Crosslink.

# Answer
I don't see an easy way to meet all requirements in a general case.

# To Make a Key Auto-Discard

Two ideas:

1. If your game is linear, and one scene follows another with no backtracking, then you can store with the key a number and a string. The string is the latest scene that the key can be used in, the number is the number of matching doors in that scene. Discard when the number is zero, or when leaving that scene. (the latter catches the case when you don't open all doors for some reason).
2. If your game is more complex, you'll have to store a list of scenes reachable from the current scene, and -- for each key -- a number of unopened doors that match the key in each scene. After each key use on a new door, decrement the count for that scene. If it goes to zero, check the counts for all reachable scenes. If they are all zero, discard. Compiling the 'reachable' scene automatically, is basically impossible in Unity, since it would require some kind of knowledge of the behavior of your scripts. So you'd need to hard-code that. You can automatically iterate through a list of scenes, open them, try the keys on each door, and store the counts.

# Who Decides which Key Fits

You've covered key-has-a-list-of-doors and doors-have-a-list-of-keys. Both of which can easily be exposed by a method on a door that takes a key and returns a boolean.

Another approach is to make the key and door more like a real key and lock. Have each key be an integer representing a bit pattern. Have each door be the same. Then in your `CanOpen` function, AND them together and the door opens if the result is zero.

So a key with 'prongs' 00000000 is a skeleton key, it opens anything. A key with 11011001 would fit a lock of 00100110, or 00100010. With this you can build patterns of opening that mean keys and doors don't need complete lists of one another beforehand. Figuring out the patterns is more difficult. A real lock effectively has two masks, and does `key AND door1 == door2`, which might be worth doing if you get stuck making the bitmasks.
> 3 votes

# Answer
As long as items are used only on the same level, the matter is fairly simple. Upon loading, count the number of doors requiring a certain key. This determines the number of times a key is usable on a level, and every time it is used on a door the key usage counter is decreased. If the counter is 0 the key is no longer needed.

If there can be multiple keys of the same time, the counter needs to be global.

On a global game world level the same principle applies, but this time you have to know the number of uses for all "levels". If the level format is simple or split into different files the number of doors requiring a specific key can be determined when the game launches. Otherwise a preprocessing task could determine that number when the game is compiled or the levels exported.

You certainly don't want designers to have to give the key a specific number of uses, because that is prone to human error.

To make lookup easier, there needs to be some form of database. You'll also need this to link doors with a key. Let's say all items in the game world have a unique (database) ID (an integer number) or a unique name "RedSkeletonKey" then the red skeleton doors would set that they require "RedSkeletonKey" to be unlocked. You will want to edit this in the door template, so that every instantiated door placed in the world automatically has this requirement. Again this is to avoid human error.

At runtime when the player approaches a locked door and tries to unlock it, the "RedSkeletonKey" reference is looked up in the item database. When found, the item of the same type is looked up in the player inventory. If player has that key, the door is unlocked and the runtime database usage counter for that key is decreased (or a separate counter increased and compared to be equal, whichever you prefer).
> 1 votes

---
Tags: game-design, unity, game-mechanics
---


title: Show a range grid movement as3

text:
# Question
Title: Show a range grid movement as3
How do I show range of grid movement in AS3? When player controls a character and chooses "move" options, the grid of movement will be displayed as 3 grid of X, 4 grid of Y (Both sides, + and -). So, it will be like this:

In the image above, movement grid displayed in blue color. But, how do i display a range grid movement like that?

# Answer
Not sure exactly how you have your current system setup, but one way to handle this situation rather simply is to have a Sprite that depicts the range and simply do a quick collision check with your tiles currently displayed.

The Sprite itself could be your visual element, but it doesn't have to be. You could trigger whatever tile specific highlighting you want after the collision check.

So you could have a method that does this collision check and returns valid tiles, then you can do any secondary checks such as if it's actually a tile that you can occupy - ie not water. Ideally that method accepts a range Sprite and the location it should be centered at for the check as parameters.
> 1 votes

# Answer
As for how to identify the tiles in range, there was a question similar to this recently - maybe this will give you a useful starting point?

(Note that those examples assume you want to work with all tiles within a radius. If you want to show walking distances around obstacles, use Depth-First Search from the character's position, returning whenever you hit an obstacle or your search depth reaches your maximum hop count)

For displaying the range with a blue tint, I might try something like...

```
const WITHIN_RANGE_COLOR : ColorTransform = new ColorTransform(0.5, 0.5, 1, 1);
const NORMAL_COLOR : ColorTransform = new ColorTransform(1, 1, 1, 1);

```

then each time you find a tile in range, do:

```
tileDisplayObject.transform.colorTransform = WITHIN_RANGE_COLOR

```

just don't forget to set it back to NORMAL\_COLOR when you're done displaying movement range.
> 1 votes

---
Tags: actionscript-3, movement, grid
---


# Question
Title: iOS: OpenGL ES 2.0 render texture with glScissor performance
I have drawn image with OpenGL and will redraw tile of its texture (non filled area).

Which case will work faster?

1. Set glViewport with full texture's rect, draw full texture and use glScissor with updated area's rect.
2. Set glViewport with updated area's rect and draw tile of texture with calculating its texture coordinates.

I've found in Apple's documentation, that scissor test is called after fragment shader. Does this mean, that fragment shader will work with pixels of full texture? How slower will it be rendered than case 2?

**SOLVED:** I've viewed pipeline scheme of OpenGL ES 2.0 here. Scissor test is done before fragment shading and allow to optimise rendering.

# Answer
> 3 votes
According to this pipeline map, the scissor test is applied before the fragment shader (I couldn't find a mention of the scissor test on the page you linked - perhaps you confused it with the stencil test which does happen after the fragment shader), so option 1 should not be more expensive than option 2 in terms of shader execution and texture fetch. There may still be a rasterization cost for the fragments which fail the scissor test. As always, the only way to be sure is to test.

---
Tags: ios, performance, opengl-es2
---


title: Passing through edges of AABB collision

text:
# Question
Title: Passing through edges of AABB collision
When I move, I grab the tile in front of the player, but when the player is colliding between two tiles, I grab the wrong tile due to rounding error. I made a video explaining what I mean.

As you can see, when the player is moving down on the edge of a tile, they pass through. This is how I find the tile:

```
Tile t = world.tiles[(int) ((int) getX() / 32 + x)][(int) ((int) getY() / 32 + y)];`

```

This is my collision detection code:`public static boolean isColliding(AABB a, AABB b) {
 if (Math.abs(a.pos.getX() - b.pos.getX()) < a.size + b.size) {
 if (Math.abs(a.pos.getY() - b.pos.getY()) < a.size + b.size) {
 return true;
 }
 }
 return false;
 }` The pos variable in the AABB class is the center of the entity and the size is half the size of the player.

How can I fix this so it finds the correct tile?

Edit: Ok, I changed my move method to get the tiles around the player, but now the player only collides if he is colliding in the middle of four solid tiles! I don't understand!

```
private void move(int x, int y, float sx, float sy) {
    Vector2f tempPos = new Vector2f((pos.getX() + (pos.getX() + 32)) / 2, (pos.getY() + (pos.getY() + 32)) / 2);
    box.update(new Vector2f(tempPos.getX() + sx, tempPos.getY() + sy), 16);
    if (getX() / 32 + x > 0 && getX() / 32 + x < world.mx && getY() / 32 + y > 0 && getY() / 32 + y < world.my) {

        for (int xx = 0; xx <= 1; xx++) {
            for (int yy = 0; yy <= 1; yy++) {
                if (world.getTile((int) (getX() / 32) + xx, (int) (getY() / 32) + yy) != null) {
                    Tile t = world.getTile((int) (getX() / 32) + xx, (int) (getY() / 32) + yy);
                    t.color = true;
                    if (t.type != 0 && !Collision.isColliding(box, t.getBox())) {
                        setPos(getX() + sx, getY() + sy);
                    } else if (t.type == 0) {
                        setPos(getX() + sx, getY() + sy);
                    }
                } else {
                    setPos(getX() + sx, getY() + sy);
                }
            }
        }

    } else {
        setPos(getX() + sx, getY() + sy);
    }
    glPushMatrix();
    glTranslatef(getX(), getY(), 0);
    glPopMatrix();
}

```

The type in Tile is just for checking to see if the tile is air. As you can see, I have two for loops that loop through the four tiles above, below and to the right and left of the player, and see if he collides with any of them. I have no idea why this isn't working, and I've tried to figure out how to do this for a week now. Can anyone show me a link or code to get the tiles around a player and see if he collides with them?

# Answer
The comments have it covered pretty well, but just to lay it out there:

Your current code is treating your tile as though it's a point. The most common case for your tile, however, is that it's overlapping two tile boundaries (whether horizontally or vertically) because of its size (again, horizontally or vertically).

Change your above code to a loop that checks tileX and tileX + 1; and tileY and tileY + 1; and you should be good to go.
> 1 votes

---
Tags: java, collision-detection, tilemap
---


# Question
Title: ShaderBytecode Compiler one technique multiple passes
I have an effect code with a basic structure like

```
technique TechniqueName {
    pass FirstPass {
        Profile = fx_4_0
        VertexShader = RenderFirstVS
        GeometryShader = null
        PixelShader = RenderFirstPS
    }
    pass SecondPass {
        Profile = fx_4_0
        VetrexShader = RenderSecondVS
        GeometryShader = null
        PixelShader = RenderSecondPS
    }
    pass ThirdPass {
        Profile = fx_4_0
        VertexShader = RenderThirdVS
        GeometryShader = null
        PixelShader = RenderThirdPS
    }
}

```

Now I tried to compile this with

```
using (BinaryReader reader = new BinaryReader(stream)) {
    CompilationResult result = ShaderBytecode.Compile(reader.ReadBytes((int)stream.Length), "fx_4_0");
    if (result.HasErrors) {
        throw new Exception(result.Message, new Exception(result.ResultCode.ToString()));
    }
    Data = result.Bytecode.Data;
}

```

stream is `new MemoryStream(Encoding.Default.GetBytes(effectContent))`.
The Data-Property (`byte[]`) is about 1 KiB large but if I try to load it via

```
context.InputAssembler.InputLayout = new InputLayout(device, effect.Data, someElements)

```

it crashes with following exception `D3D11 ERROR: ID3D11Device::CreateInputLayout: Input Signature in bytecode could not be parsed. Data may be corrupt or in an unrecognizable format. [ STATE_CREATION ERROR #161: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE]`

Any idea how I can fix this or why the error is thrown? I do not want to use multiple shaders because I reuse many parameters I do not want to reassign in a deferred shading setup.

# Answer
When you use the effect shader syntax (techniques and passes), the resulting bytecode is actually a container that includes the bytecode for each compiled vertex and pixel shader for each technique and pass. When creating an input layout, you need to use the bytecode for an individual vertex shader. You'll have to extract that from the effect shader.

It looks like in SharpDX you do this by creating an `Effect` object using the effect bytecode. You should be able to iterate through the techniques and passes in the effect, although it's not clear to me from the docs just how that works. If you get the `EffectPassDescription` for a pass, that has a `Signature` element that should be what you can use to create the input layout.
> 1 votes

---
Tags: shaders, sharpdx
---


# Question
Title: Replace a div (with a ball picture in it) with a 3D canvas ball
I am trying to make a game where you have to keep the ball on a green platform. At this point the ball is a `div` with a ball image. You can move the ball over the field, all works great.

See it in action here (click the 1 first).

When you use your arrow keys you can move the ball (actually you move a `div`). This looks kinda fake, so I want to use a real 3D canvas ball for this. I saw a nice example here. (scroll down half way to the page. You will see a smiley with a ball in it just above the title: Smoothing it out)

So how can I use this ball into my game? I have the following code for the ball:

```
  // build the ball and draw its texture with a 2d canvas -------------------------------------------
  var buildBall = function() {
    // create a canvas to draw the ball's texture
    var ballCanvas = document.createElement('canvas');
    ballCanvas.width = 64;
    ballCanvas.height = 64;
    var ballContext = ballCanvas.getContext('2d');

    // draw 2 colored halves of the 2d canvas
    ballContext.fillStyle = "#f8ae44";
    ballContext.fillRect(0, 0, ballCanvas.width, ballCanvas.height/2);
    ballContext.fillStyle = "#ffda4e";
    ballContext.fillRect(0, ballCanvas.height/2, ballCanvas.width, ballCanvas.height/2);

    // create the THREE texture object with our canvas
    var ballTexture = new THREE.Texture( ballCanvas );
    ballTexture.needsUpdate = true;

    // create the physijs-enabled material with some decent friction & bounce properties
    var ballMaterial = Physijs.createMaterial(
      new THREE.MeshLambertMaterial({
        map: ballTexture,
        shininess: 10,
        color: 0xdddddd,
        emissive: 0x111111,
        side: THREE.FrontSide
      }),
      .6, // mid friction
      .5 // mid restitution
    );
    ballMaterial.map.wrapS = ballMaterial.map.wrapT = THREE.RepeatWrapping;
    ballMaterial.map.repeat.set( 1, 1 );

    //THIS PART IS FOR QUESTION 2
    // create the physics-enabled sphere mesh, and start it up in the air
    ball = new Physijs.SphereMesh(
      new THREE.SphereGeometry( 30, 32, 32 ),
      ballMaterial,
      100
    );
    ball.position.y = 500;
    ball.receiveShadow = true;
    ball.castShadow = true;
    scene.add( ball );
  };

```

I know I have to implement `three.js` to make this work, but how can I get the `div` replaced with this 3D canvas ball keeping everything else working as is (using arrows to move, move speed of the ball, reset when fallen of the platform etc)?

# Answer
> 1 votes
Well, these are very different things. You should just throw away your current code and rewrite it directly for three.js.

But:

The logic should be separated from rendering. As long as you have your 'ball position' variables, you can just use them on 3D.

Create a three.js scene, add a plane, a camera, and a sphere, and then just move your sphere depending on keyboard input.

Detect when it gets out (if you don't want to bother with physics you can just detect when it's coordinates are out of the green terrain and then start getting it down with a little speed). You don't need a physics engine for that.

---
Tags: 3d, javascript, html5, html-canvas, three.js
---


# Question
Title: Why do I have to run my 2D game at 300+ FPS for movement to be passably smooth?
I'm working on a simple game with SFML, and the only way to make the game reasonably smooth is to allow it the highest framerate my machine can handle (that is, giving it no limit). 60 FPS in my game looks like 5 FPS in most games.

I've made sure it wasn't any weird timing issue with sf::Clock by making my delta variable constant, and I've made a simple moving square with the default SFML template to make sure it wasn't anything else in my code.

Limiting framerate using window.setFramerateLimit(80), window.setVerticalSync(true), or by placing usleep(1000 * 15), a 15-millisecond pause (~67 FPS, in theory) in the game loop, cause the terribly glitchy, asymmetric animation.

I think the problem is my Mac. I hesitate to blame anything other than my code, but I just can't explain the problem otherwise. I'm running OS X Mavericks on a 15-inch MacBook Pro with a Retina display (2.4 GHz i7, Nvidia, 8GB RAM).

Is it the Retina display, or some issue with the sleep() system calls? Any thoughts are welcome. Thanks!

# Answer
> 10 votes
Sleep calls are an extremely bad way of controlling framerate. Use them to reduce CPU usage for sure, but don't use them to control framerate.

> usleep(1000 * 15), a 15-millisecond pause (~67 FPS, in theory)

No, it's not.

First of all, see the documentation for usleep:

> The actual time slept may be longer, due to system latencies and possible limitations in the timer resolution of the hardware.

Secondly, realise that the sleep time is *in addition* to the time taken to run a frame, which may be longer. So if frame 1 takes 3ms, frame 2 takes 5ms, frame 3 takes 1ms, frame 4 takes 7ms, then when you add the sleep time (and assume that you actually do sleep for 15ms exact - which is unlikely) you're looking at frame times of 18ms, 20ms, 16ms, 22ms.

That's why you should **never use sleep to control framerate**.

The standard reference page for this topic is Glenn Fiedler's Fix your Timestep so I'm going to finish up by pointing you at that.

---
Tags: animation, movement, sfml, macos
---


# Question
Title: Rendering a image with some transparency has removed all black pixels and makes full texture transparent
I am writing a program where with Directx11 I am rendering a texture to a flat rectangle something along the line a of 2D engine. Now parts of this image need to be transparent, to this effect I looked into alpha blending and it seemed to work until i changed textures and realized that it had removed all black pixels and made the whole image transparent not just those pixels that are blank. So how in Directx11 do you have it so that you preserve the transparency of the original image. I am using a ShaderResourceView that is a loaded png for the texture

```
**//Setup Blend State
D3D11_BLEND_DESC BlendStateDescription;
ZeroMemory(&BlendStateDescription, sizeof(D3D11_BLEND_DESC));

BlendStateDescription.RenderTarget[0].BlendEnable = TRUE;
BlendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
BlendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;

BlendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC1_COLOR;
BlendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
BlendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
BlendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
BlendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

dev->CreateBlendState(&BlendStateDescription, &blend);
float blendFactor[] = { 0, 0, 0, 0 };
UINT sampleMask = 0xffffffff;

devcon->OMSetBlendState(blend, blendFactor, sampleMask);**

```

# Answer
> 2 votes
Your blend state isn't set up to be standard alpha-blending. The general blend state specifies `dest.rgb = src.rgb * [SrcBlend] [Op] dest.rgb * [DestBlend]`, and likewise for the separately blended alpha channel. For standard alpha-blending, you should use:

```
SrcBlend = D3D11_BLEND_SRC_ALPHA
DestBlend = D3D11_BLEND_INV_SRC_ALPHA
BendOp = D3D11_BLEND_OP_ADD
// dest.rgb = src.rgb * src.a + dest.rgb * (1 - src.a) ==> standard alpha blended color

SrcBlendAlpha = D3D11_BLEND_INV_DEST_ALPHA
DestBlendAlpha = D3D11_BLEND_ONE
BendOp = D3D11_BLEND_OP_ADD
// dest.a = src.a * (1 - dest.a) + dest.a
//       == src.a + dest.a - src.a * dest.a
//       == 1 - (1 - src.a) * (1 - dest.a) ==> preserves alpha to target (optional)

```

---
Tags: rendering, directx11, transparency
---


# Question
Title: How forward rendering done using OpenGL?
Recently I come across the term forward rendering. I'm kind of curious how this could be done in OpenGL. I have done a lot of search on this, majority of the result I get are on theory but not code implementation. May I know is there any code implementation on OpenGL for this rendering technique?

# Answer
There are two major types of rendering:

1. forward rendering
2. deferred rendering

In both types you have you objects and lights present in the scene, but the difference is when to calculate lighting.

**Forward rendering**

Render object, and while running its (usually) fragment shader, for each fragment you calculate lighting from all the light sources.

So, you for every object, and all of its fragments, calculate ligthing.

*Why is this good and why is it bad?*

* It's bad because it might happen (and in most cases it does) that fragment is overwritten by the next, and all your lighting calculations are wasted. Also, running lighting calculations on each and every fragment is quite expensive. The cost is const and is equal to `num_fragments * num_lights`, and that's a lot.
* It's good because it uses hardware enabled AA

**Deferred rendering**

Render into buffers the data that is required for calculating lighting later, such as diffuse color, specular power, normals... and *after* you've done that, run ligthing calculations for every light, but only on the parts of the image that cold possibly be affected by that light.

*Cons and pros?*

* It's good because, once you have the information what is visible in the scene, you run calculations only on those parts. Further more, only on the parts of the image that could be affected by that light. The cost is in worst case scenario `num_lights * num_pixels_of_screen`.
* It's bad because there's no AA and no support for transparent objects

---

In short, that's the difference between forward and deferred rendering. So if you put your lighting calculations directly into shading of the object, then it's called forward rendering. That means, almost any tutorial that you might find on the internet is probably implementing forward rendering type.

Hope this helps.
> 4 votes

# Answer
Forward rendering is the classic approach to rendering where the data for a scene is generally used directly to calculate a final pixel color in a single pass (additional post-processing passes can be used as well, but these are usually still considered part of forward rendering). The alternative, deferred rendering, generally encodes much more data (not necessarily actual colors) to an intermediate target, then *defers* the final render pass that uses the intermediate target as its source.
> 2 votes

---
Tags: opengl, rendering
---


title: How do I check if a surface is sloping?

text:
# Question
Title: How do I check if a surface is sloping?
I'm implementing gravity over a 3D terrain and I'm struggling with how to check if surface "under your feet" is flat or sloping.

I read some tutorials but gravity is always considered along a single axis.

How do I proceed?

# Answer
> 6 votes
You could just calculate the dot-product of your "up-vector" and the normal of the surface below your feet.

So assume you have a world where positive-Y is up, then your up-vector is `(0,1,0)`. Then get the normal of the triangle below your feet and calculate the dot-product.

```
float dot = Vector3.Dot(upVector, normalVector);

```

The dot product will be the cosine of the angle of these two normal vectors. It will be `1.0` when both normals point in the same direction (eg. your plane is absolutely flat), `0.0` when the normals are perpendicular and `-1.0` when they are pointing in the opposite direction.

Your check if a surface is sloping could be a simple threshold comparison, such as:

```
// 0.8f is just some arbitrary value.. could be 0.9f or even higher
// if you want to make sure the surface is as close to flat as possible
bool isSlope = Vector3.Dot(upVector, normalVector) < 0.8f;

```

Some other thing to consider is the coarseness of your mesh. If you have really small triangles (compared to the "feet" of your character), you might get unwanted results if you just consider a single triangle and its normal. Instead you might want to average the normals of several triangles and use that for your calculation.

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


# Question
Title: PID controller error value for heading correction
I'm using a PID controller in my AI to steer my NPCs to a desired heading (by adding torque). I've adapted the code from here: http://answers.unity3d.com/questions/199055/addtorque-to-rotate-rigidbody-to-look-at-a-point.html

The above example uses the cross-product of the two headings as the error value for the PID controller. This works great if the angle between the desired and current headings is less than 90 degrees but if the angle is greater than that, the PID controller corrects to the opposite direction than I want (as it tries to correct to zero)!

What is a good error value between two vectors to pass into a PID controller that works no matter what the angle between the desired, and current heading?

Note: because the PID controller returns the correction as a vec3, the error value must also be a vec3

# Answer
Assuming v1 & v2 are unit length, acos(dot(v1, v2)) will vary between 0 when they are identical to pi when they are opposite.

To turn this into a vector, we can use...

```
Vector3 error = Vector3.Cross(v1, v2);
float dot = Vector3.Dot(v1, v2);
float length = error.magnitude;

if(length > 0f)
{
   error *= Mathf.acos(dot)/length;
   // equivalently, you can use error *= Vector3.angle(v1, v2)/length; but this will be in degrees.
}
else if(dot < 0f)
{
   error = axis * Mathf.PI;
}

return error;

```

...where axis is your rotation axis (we can't infer it from v1 & v2 when they are parallel)
> 1 votes

---
Tags: ai, rotation
---


title: AABB SAT code detects collision wrongly

text:
# Question
Title: AABB SAT code detects collision wrongly
I've been having trouble getting my SAT code working using AABBs, and I've been trying to find a solution but, I'm scratching my head.

For some reason, it detects collisions very wrongly, as shown by this desk check I did. (AABBvsAABB method at bottom.)

Consider two AABB, A and B.

```
A = X: 0, Y: 0, W: 102, H: 19

B = X = 87, Y: 6, W: 1, H: 1

```

These are colliding.

First, calculate normal

```
Normal = (0,0) - (87,6) = (-87,-6)

```

Next, we get half widths

```
aExtent = 102/2 = 51
bExtent = 1/2 = .5

```

Now lets calculate the overlap of the two.

```
 xExtent = 51 + .5 - |-87| = 51.5 - 87 =  -35.5

```

xExtent is less than zero so it says its not colliding, obviously this is wrong.

```
   /// <summary>
   /// Compares bounding boxes using Seperating Axis Thereom.
   /// </summary>
   public static bool AABBvsAABB(AABB a, AABB b, ref Manifold manifold)
   {
        manifold.Normal = a.Position - b.Position;

        //Calculate half widths
        float aExtent = a.Width / 2f;
        float bExtent = b.Width / 2f;

        //Calculate the overlap.
        float xExtent = aExtent + bExtent - Math.Abs(manifold.Normal.X);

        //If the overlap is greater than 0
        if (xExtent > 0)
        {
            //Calculate half widths
            aExtent = a.Height / 2f;
            bExtent = b.Height / 2f;

            //Calculate overlap
            float yExtent = aExtent + bExtent - Math.Abs(manifold.Normal.Y);

            if (yExtent > 0)
            {
                //Variable to multiply the normal by to make the collision resolve
                Vector2 faceNormal;

                //Check to see which axis has the biggest "penetration" ;D

                //Collision is happening on Y axis
                if (xExtent > yExtent)
                {
                    faceNormal = manifold.Normal.X < 0 ? -Vector2.UnitX : Vector2.UnitX;
                    manifold.PenetrationDepth = xExtent;
                    manifold.Normal = Physics.GetNormal(a.Position, b.Position);
                    manifold.Normal.X *= faceNormal.X;
                }
                //Collision happening on X axis
                else
                {
                    faceNormal = manifold.Normal.Y < 0 ? -Vector2.UnitY : Vector2.UnitY;

                    manifold.PenetrationDepth = yExtent;
                    manifold.Normal = Physics.GetNormal(a.Position, b.Position);
                    manifold.Normal.Y *= faceNormal.Y;
                }
                manifold.AreColliding = true;
            }
        }
        return manifold.AreColliding;
    }

```

Any idea what I am doing wrong here?

# Answer
> 1 votes
It looks like you're mixing definitions for the x & y coordinates of your AABBs.

Checking for collisions using this formula with half-extents implies that your x & y coordinates represent the coordinates of the centers of the bounding boxes. In this definition, the two boxes you describe are indeed not colliding, and everything is working as expected.

If the two boxes are colliding as you say, then the coordinates must be the min-x, min-y corner. In this situation, the half-extents check is not appropriate. Instead, you'd want to use something like:

```
if(A.x < B.x)
   colliding = B.x - A.x < A.width;
else
   colliding = A.x - B.x < B.width;

```

---
Tags: xna, c#, collision-detection, aabb, separating-axis-theorem
---


title: Lighting Covering Up Sky ( XNA / C# )

text:
# Question
Title: Lighting Covering Up Sky ( XNA / C# )
I have a 2D tile-based lighting system which is drawn onto a Render Target. I am also drawing a background which involves mountains, sun/moon, and clouds. There is also the unlit game; blocks, character, etc.

Here is the order in which everything is drawn:

```
1. Background
2. Game World
3. Lighting

```

The problem is that the LIGHTING is covering up the BACKGROUND when it's dark:

Although it's perfectly fine in the day because the light is full:

**You might ask, well, why don't you just blend each block, not drawing the lighting on a RenderTarget?**

Because that would prevent me from performing smooth lighting, as seen in the pictures. To produce the smooth lighting, I draw squares of light onto a RenderTarget, perform a Gaussian blur and then draw that RenderTarget.

**How about not drawing a square of light in empty spaces?**

The light blurs onto any adjacent blocks, and not all objects in my game affected by lighting are square, so they would look like a sprite with a blurry square on top of it.

Light NOT being drawn in empty spaces:

Light being drawn everywhere:

Is there any way to keep the background visible, or something else that would help my predicament?

***USING THE STENCIL BUFFER***

I put in the stencil buffer code that you said should cause "little overhead"

As you can see the background blocks, due to the effect, are not darkened like they should be. The FPS here is ~15 as opposed the the steady 60 FPS it runs at without the stencil method. Also the character is somehow not being drawn correctly.

It does in fact work though despite the more than annoying lag.

# Answer
The issue seems to be that you are applying lighting to an object which should not be affected by it. It makes no logical sense that something in the local scene should be able to affect the sky, like the shadows in your sample do during the day. I think this doesn't make logical sense but perhaps it does make aesthetic sense.

If I have understood correctly what you want, then you should consider the following method:-

1. Break your system into two sets; things you want affected by lighting and things you don't want affected.
2. Render the set of light affected objects to a stencil buffer (for implementation details see this tutorial).

* You should add this to the system that currently renders the scene and simply enable and disable writing to the stencil buffer depending on whether you want lighting on the object you are currently drawing.
3. Use this stencil buffer when rendering the lighting buffer to only draw to areas that you want shadows (pixels occupied by objects we want illuminated).

What this will do is make sure that you only render lighting to pixels which are used to display an object affected by lighting and not pixels being used to display the sky.

At the end your draw method should resemble (code taken from here);

```
var a = new AlphaTestEffect(graphics.GraphicsDevice) {
    Projection = m
};

var s1 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

var s2 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.LessEqual,
    StencilPass = StencilOperation.Keep,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

// not drawing to the stencil buffer here
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, a);
// draw all NON-light affected objects here
foreach (Sprite s in nonIlluminatedSprites)
{
    spriteBatch.Draw(s.texture, s.rectangle, Color.White);
}
spriteBatch.End();

// drawing to the stencil buffer here...
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s1, null, a);
// draw all light affected objects here
foreach (Sprite s in illuminatedSprites)
{
    spriteBatch.Draw(s.texture, s.rectangle, Color.White);
}
spriteBatch.End();

// using the mask here
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s2, null, a);
// Blend the light buffer with scene here
spriteBatch.Draw(lightBuffer.texture, Vector2.zero, Color.White);
spriteBatch.End();

```

Note: while a sky/mountain backdrop might not be affected by shadows you may want to have shadows cast on other background objects; such as the background walls when the game is an interior location like a house. So you might want to split the background into two things, background objects and sky/mountain backdrop.

*Alternative Method*

In a comment it was mentioned that the stencil buffer approach was being slow. This shouldn't be the case if generated in the same pass as rendering the main game objects as it should add very little overhead. However, there may be another method in this particular case.

If you are using a pixel shader to render all scene objects then add a new "float illuminate" attribute. Before the draw call for a non-illuminated object set this attribute to 1 and before the draw call for illuminated objects set it to 0. Then, in the pixel shader, set the alpha channel of the lighting buffer to this value.

This should mean that when you blend using alpha blending at the end of your rendering pass the lighting buffer will have transparent areas where we don't want illumination applied on the screen.

Note: I may have the 1 and 0 round the wrong way. I get this wrong most of the time and wrote this assuming that 1 means "completely transparent".
> 1 votes

---
Tags: xna, c#, 2d, lighting
---


title: Storing a Quadtree

text:
# Question
Title: Storing a Quadtree
I have a quadtree which organize my terrain chunks (heightmap) and all the static objects of my 3D world. I use Axially Aligned Bounding Box as a volume for each node of the quadtree. Due to the static nature of the objects, the quadtree will not be modified during the execution of the program. The quadtree is generated on a homemade editor so I need to implement a system that writes/reads the entire tree from a binary file.

How should I organize the nodes in the binary file (what order...) and how to build the quadtree when I read the file?

My JavaScript QuadNode Object:

```
function QuadNode ( box, children )
{
    this.boundingBox = box;
    this.children = children; // undefined if leef node
    this.objects = [];
}

```

I precise that my quadtree may be incomplete and that any node can have objects attached to it. Moreover, the extents of the AABB will not have X, Z components in the file as those can be computed during the parsing.

So the scheme for a node in the binary file might be:

```
struct QuadNode {
    struct AABB {
        float         (MinHeight)
        float         (MaxHeight)
    }
    uint32            (NbObjects)
    struct Object {
        ...
    } [NbObjects]
}

```

PS: The quadtree will be entirely parsed during the loading. I don't need to stream it.

# Answer
> 2 votes
Walk the quadtree recursively when saving:

```
save_node(node n) {
    write_bbox(n.bbox)
    write_int(n.objects.length)
    for (object in n.objects) {
        write_object(object)
    }
    write_int(n.children.length)
    for (child in n.children) {
        save_node(child)
    }
}

save_node(quadtree.root)

```

Read back the same way:

```
read_node() {
    node n
    n.bbox = read_bbox()
    num_objs = read_int()
    while (num_objs--) {
        n.objects.append(read_object())
    }
    num_children = read_int()
    while (num_children--) {
        n.children.append(read_node())
    }
    return n
}

quadtree.root = read_node()

```

---
Tags: javascript, resource-management, quadtree
---


# Question
Title: How to remove a circular dependency as pointed out in a libgdx tutorial
In this libgdx tutorial, the author says he's not happy with the circular dependency between the game and the screens.

How can this diagram:

be improved to remove that dependency?

# Answer
You can't. **Game** class is the one that handles the **Screens**, and the Screens need to be able to communicate with it to tell it which Screen it should set next.

That dependency isn't really a big of a deal. Just having a reference to the Game in your Screens (via the abstract Screen that all of them extends from).

If you want to change that, you would need to create your own **Game** and **Screen** classes, with a different design. (Not worth the effort if you ask me)
> 2 votes

---
Tags: game-design
---


# Question
Title: Loading TextureAtlases using AssetManager in LibGdx
I want to use AssetManager in LibGDX to load my TextureAtlas. But I am not getting it. I have actually one large 2048 x 2048 px image, that I am creating in Predator. and then I am using the regions. Should I need to load the atlas once using AssetManager or what?

This is my current code

```
public class Assets {
private final static String FILE_SPRITE_ATLAS = "data/sprite_sheet.txt";

private final static String FILE_UI_SKIN = "skin/uiskin.json";
private final static String FILE_UI_SKIN_OTHER = "otherskin/uiskin.json";

public static TextureAtlas spriteAtlas;
public static Skin skin;
public static Skin other_skin;

//
public static TextureRegion bg;
public static TextureRegion dark_bg;

public static TextureRegion button_bg;
public static TextureRegion dracus;
public static TextureRegion egg;
public static TextureRegion egg_icon,play_icon,settings_icon,fb_icon,back_icon,credits_icon,sound_off,sound_on;
public static TextureRegion hunter_shooting;
public static TextureRegion hunter_walking;
public static TextureRegion button_pause;
public static TextureRegion dragon_icon;
public static TextureRegion arrow;
public static TextureRegion transparent_credits;
public static TextureRegion transparent_box;
public static TextureRegion transparent,mat,high_scores,tooltip,player_icon;
public static TextureRegion logo,egg_bucket,audio_icon,lock_icon,star;

public static Animation dragonLeft, dragonRight,dragonUp,dragonFront;
public static Animation anim_hunter_shooting;
public static Animation anim_hunter_walking;
public static Animation hunter_ready_shooting;
//
public static BitmapFont smallFont;
public static BitmapFont bigFont;

// TEST OBJECT
public static TextureRegion imgTest;
public static BitmapFont font3_1;

public static Texture loadTexture(String file) {
    return new Texture(Gdx.files.internal(file));
}

public static TextureAtlas getSpriteAtlas() {
    if (spriteAtlas == null) {
        spriteAtlas = new TextureAtlas(
                Gdx.files.internal(FILE_SPRITE_ATLAS));
    }
    return spriteAtlas;
}

public static Skin getSkin() {
    if (skin == null) {
        FileHandle skinFile = Gdx.files.internal(FILE_UI_SKIN);
        skin = new Skin(skinFile);
    }
    return skin;
}

public static Skin getOtherSkin() {
    if (other_skin == null) {
        FileHandle skinFile = Gdx.files.internal(FILE_UI_SKIN_OTHER);
        other_skin = new Skin(skinFile);
    }
    return other_skin;
}

public static void loadAll() {
    relaseResources();
    loadImages();
    loadButtons();
    loadFonts();
    loadAnimations();
    loadSoundsAndMusics();
}

private static void relaseResources() {
    skin = null;
}

public static void loadImages() {

    //REGIONS FROM SPRITE ATLAS
    bg = getSpriteAtlas().findRegion("bg");
    dark_bg = new TextureRegion(bg.getTexture(),0,0,960,300);
    button_bg = getSpriteAtlas().findRegion("button_bg");
    dracus = getSpriteAtlas().findRegion("dracus");
    egg = getSpriteAtlas().findRegion("egg");
    egg_icon = getSpriteAtlas().findRegion("egg_icon");
    sound_on = getSpriteAtlas().findRegion("sound_on");
    sound_off = getSpriteAtlas().findRegion("sound_off");
    credits_icon = getSpriteAtlas().findRegion("credits_icon");
    back_icon = getSpriteAtlas().findRegion("back");
    fb_icon = getSpriteAtlas().findRegion("fb_icon");
    settings_icon = getSpriteAtlas().findRegion("settings_icon");
    play_icon = getSpriteAtlas().findRegion("play_icon");
    transparent = getSpriteAtlas().findRegion("transparent");

    hunter_walking =getSpriteAtlas().findRegion("hunter_walking");
    hunter_shooting =getSpriteAtlas().findRegion("hunter_shooting");

    button_pause =getSpriteAtlas().findRegion("button_pause");
    arrow =getSpriteAtlas().findRegion("arrow");
    dragon_icon =getSpriteAtlas().findRegion("dragon_icon");

    transparent_credits =getSpriteAtlas().findRegion("transparent_credits");
    transparent_box =getSpriteAtlas().findRegion("transparent_box");
    egg_bucket =getSpriteAtlas().findRegion("egg_bucket");
    logo =getSpriteAtlas().findRegion("logo");
    mat =getSpriteAtlas().findRegion("mat");

    audio_icon=getSpriteAtlas().findRegion("audio_icon");
    lock_icon =getSpriteAtlas().findRegion("lock_icon");
    //howtoplay_icon =getSpriteAtlas().findRegion("howtoplay_icon");
    high_scores =getSpriteAtlas().findRegion("high_scores");
    star = getSpriteAtlas().findRegion("star");
    tooltip = getSpriteAtlas().findRegion("tooltip");
    player_icon = getSpriteAtlas().findRegion("player_icon");

    }

public static void loadButtons() {
    //img_btn_home = getAtlas().findRegion("img_btn_home");
    //img_btn_home_pressed = getAtlas().findRegion("img_btn_home_pressed");
}

public static void loadFonts() {
    //
    smallFont = new BitmapFont(Gdx.files.internal("data/smallFont.fnt"),
            Gdx.files.internal("data/smallFont.png"), false);
    bigFont = new BitmapFont(Gdx.files.internal("data/bigFont.fnt"),
            Gdx.files.internal("data/bigFont.png"), false);
    font3_1 = new BitmapFont(Gdx.files.internal("data/font3.fnt"),
            Gdx.files.internal("data/font3.png"), false);
}

public static void loadAnimations() {
    //Loading the Dragon

    TextureRegion[][] regions2 = Assets.dracus.split(96, 96);

    dragonLeft = new Animation(0.15f, regions2[1][0],regions2[1][1], regions2[1][2],regions2[1][3]);
    dragonLeft.setPlayMode(Animation.LOOP_PINGPONG);

    dragonRight = new Animation(0.15f, regions2[2][0],regions2[2][1], regions2[2][2],regions2[2][3]);
    dragonRight.setPlayMode(Animation.LOOP_PINGPONG);

    dragonUp = new Animation(0.15f, regions2[3][0],regions2[3][1], regions2[3][2],regions2[3][3]);
    dragonUp.setPlayMode(Animation.LOOP_PINGPONG);

    dragonFront = new Animation(0.15f, regions2[0][0],regions2[0][1], regions2[0][2],regions2[0][3]);
    dragonFront.setPlayMode(Animation.LOOP_PINGPONG);

    TextureRegion[][] hunter_shoot_regions = hunter_shooting.split(110, 143);
    anim_hunter_shooting = new Animation(0.25f, hunter_shoot_regions[0][0],hunter_shoot_regions[0][1],
            hunter_shoot_regions[0][2],hunter_shoot_regions[0][3]);
    //anim_hunter_shooting.setPlayMode(Animation.LOOP_PINGPONG);

    hunter_ready_shooting = new Animation(1.0f, hunter_shoot_regions[0][0],hunter_shoot_regions[0][1]);

    TextureRegion[][] hunter_walk_regions = hunter_walking.split(86, 132);
    anim_hunter_walking = new Animation(0.20f, hunter_walk_regions[0][0],hunter_walk_regions[0][1],
            hunter_walk_regions[0][2],hunter_walk_regions[0][3]);
    anim_hunter_walking.setPlayMode(Animation.LOOP_PINGPONG);
}

public static void loadSoundsAndMusics() {
}
}

```

# Answer
> 11 votes
Create an AssetManager:

```
AssetManager manager = new AssetManager();

```

This to begin the loading:

```
manager.load(FILE_SPRITE_ATLAS, TextureAtlas.class);

```

This getting called continously for asynchronous loading:

```
manager.update();

```

Or this called once for synchronous loading:

```
manager.finishLoading();

```

and then this saves the spriteAtlas (when update() returns 1):

```
spriteAtlas = manager.get(FILE_SPRITE_ATLAS, TextureAtlas.class);

```

Next time, do not post that much code. Post only the relevant parts. In this case there wasn't actually any relevant parts. You don't even have an AssetManager declared...

Useful Link: Libgdx Wiki.

---
Tags: libgdx, texture-atlas
---