title: Simple shader for sprite interface

text:
# Question
Title: Simple shader for sprite interface
I have been looking for any examples for a long time, I cant get anything to work (from the examples). I have tried using vertex/pixel shaders, effects files, but they never have any effect on the rendering. I am using seemingly simple shaders (adding a value to the red color, or removing a color entirely). This has led me to believe that the code setting up/rendering the shader is not working correctly. Almost every example is for non sprite based rendering, but I dont know if that matters (I cant find any info on that).

A lot of forum posts/answers point to sites that no longer exist.

I want to get a proof of concept simple shader that does anything in particular, to the entire rendered screen.

The technology I am using is C++ Directx 9 Sprite interface. Any help/links in the right direction is appreciated.

Thanks in advanced!

# Answer
> 1 votes
This is the shader I use to push my pre-built HUD texture to the full display window. I compile it using the VS\_4\_0 and PS\_4\_0 profiles which I'm not sure will work right with DX9. The mesh I use with this shader is a simple quad ranging from (-1,-1,0) to (1,1,0) (note the zeros for Z -- there is no depth involved... the -1 to 1 range maps to the corners of the screen, and (0,0) is in the middle). If you do have a problem compiling for DX9 (VS3/PS3), the problem will most likely be with the SV\_POSITION and SV\_TARGET semantics. This shader is also meant to be used with alpha blending configured, but there is no reason It cant be used without blending.

```
struct VS_IN
{
    float4 pos : POSITION;
    float2 tex : TEXCOORD;
};

struct PS_IN
{
    float4 pos : SV_POSITION;
    float2 tex : TEXCOORD;
};

Texture2D picture;
SamplerState pictureSampler;

PS_IN VS(VS_IN input)
{
    PS_IN output = (PS_IN)0;

    output.pos = input.pos;
    output.tex = input.tex;

    return output;
}

float4 PS(PS_IN input) : SV_Target
{
    return picture.Sample(pictureSampler, input.tex);
}

```

---
Tags: c++, shaders, sprites, directx9
---


# Question
Title: What is the correct multiplication order for a 2D matrix?
I'm currently trying to create a camera and entity/model matrix for my 2D game similar to that of Unity3D. I've already tried to find answers to this question on stackoverflow/gamedev but i couldn't find an answer that explains how to center the camera and image.

Goal:

1. Have a camera matrix wich is centered at the position of the camera.
2. Have a entity matrix wich draws everything centered

Current implementation:

```
camera: matrix = Matrix.translation(Screen.width * 0.5, Screen.height * 0.5) *
                 Matrix.rotation(camera.rotation_radians) *
                 Matrix.scale(camera.scale.x, camera.scale.y) *
                 Matrix.translation(camera.x, camera.y);

entity: matrix = Matrix.rotation(entity.rotation_radians) *
                 Matrix.scale(entity.scale.x, entity.scale.y) *
                 Matrix.translation(entity.x, entity.y);

image component draw function:
                 setMatrix(camera.matrix * entity.matrix);
                 drawImage(x=0, y=0, image) // position is already included in the entity matrix

```

Results:

1. Image rotates around the upper-left corner of the screen not around it's center
2. Image is not centered. The image's origin is at its upper-left corner.
3. The camera matrix seems to be correct.

Questions:

1. What is the correct multiplication order for the entity/model matrix?
2. Can i use a single matrix for all components of a entity or do i need to calculate in the width/height of the image/text/animation component.

# Answer
> 1 votes
> What is the correct multiplication order for the entity/model matrix?

Scale then rotate then translate.

> Can i use a single matrix for all components of a entity or do i need to calculate in the width/height of the image/text/animation component.

No each component part of your scene has its own matrix as the matrix represents the combination of scale, rotation and position for that object.

---
Tags: opengl, 2d, unity, rendering, matrix
---


title: Unity3D - How to tessellate 2D sprites?

text:
# Question
Title: Unity3D - How to tessellate 2D sprites?
I use dynamic vertex lighting on 2D sprites. On larger sprites the lighting is uglier than on smaller ones. This is because every sprite is just a quad of two triangles. Not enough vertices there for lighting on larger areas.

Is there a way to use more triangles on a sprite? Maybe even depending on how much screen space they cover?

# Answer
Sounds like you need to create your own game object and use a custom triangulation algo to handle the detail based on some size related math.

Maybe something like this could help ...

http://forum.unity3d.com/threads/tessellation-algorithms-for-polygons.228051/

Others options might be to use a smarter shader and a bump map with your sprite ... vertex displacement type approaches.

It's hard to say without knowing exactly what it is you are trying to achieve as to what might fit best. Hopefully one of these helps.
> 2 votes

---
Tags: 2d, unity, sprites, tessellation
---


# Question
Title: How to do collision detection on marching cubes terrain?
I'm writing the physics part of my game engine. The world uses the marching cubes algorithm on a 3d perlin noise to make the terrain.

How do I do collision detection on the resulting mesh? I can't use SAT since the terrain is not convex and subdividing it into smaller convex parts seems to be nearly impossible.

What is the best collision detection algorithm for such a mesh? The objects that are supposed to collide with the terrain can be any convex polyhedron.

EDIT: The terrain is not "cubed" (like minecracft). The terrain is smooth with slopes. This is pretty close to what my terrain looks like (this is NOT my video): https://www.youtube.com/watch?v=-4rA3fdKWQA

I am looking for a general collision detection here. I need the point(s) of contact and the normals so that I can put these into my collision resolver.

Example of usage is throwing a box onto the terrain and it should roll and bounce approximately like it would in the real world.

# Answer
> 1 votes
Minor Edit:

I made an assumption here that you are looking to do your physics simulation / collision detection on the resulting mesh that you have generated rather than on say ... your point cloud (voxel) data (another assumption made that you are using voxels too) as this is the normal scenario.

Such collision detection on voxels would be problematic at best.

End of edit

> How do I do collision detection on the resulting mesh?

The simplest way to answer this is ... How would you do collision detection on any mesh?

Throw a raycast in the direction you intend to perform your collision check then "pick" the vert that was hit and decide what action you want to take.

I don't know what technology you are using so it's hard to be too specific but here's an example of how its been done using OpenGL ...

3D Ray Casting / Picking

However based on this comment in your question ...

> Example of usage is throwing a box onto the terrain and it should roll and bounce approximately like it would in the real world.

... I would say that without realising it what you need is a little more than collision detection, you need a physics simluation engine that can handle complex interactions between collisionable objects.

I went down this route when faced with the same problem ...

Most people because of the complexity of the math pull in a physics engine to their game engine code handle that for them, in my case I am using SharpDX and I chose to sit BulletSharp on top of that to handle physics simlations like rolling a mesh about on my terrain in the manner you describe.

The Bullet engine is great and comes with a ton of examples that can help you get started and has other wrappers than the one i'm using ...

https://code.google.com/p/bulletsharp/

I would give you a code sample here on exactly how all this clicks together but the code can be quite lengthy and I think the guys that provide Bullet are better placed to give you better description and a full working demo project to show this in action.

# Answer
> -1 votes
It depends if you are walking on it or flying over it. i.e. collision frequency. also it depends if your cubes are squares like minecraft, which makes it easy.

You have to make some kind of mesh collider, or some triangles around the point of collision.

Normally your program should have a way of making a mesh collider.

For advanced coders, and specific kinds of projects, you can use the perlin noise function to see how close an object is to a the terrain boundary. the isovalue is a guide for collision.

as a rough guide, the cheapest way to check collision is ISO value of noise, you can find a value, say \>4 which is very far from the 0 isometric value, and only objects with a diamter larger than 20 say, could reach it. so first check the isovalue of the objects or of their boundaries.

if they are within a few meters of the boundary, have a 3d array of all the cubes in space, only a few of which will have triangles precomputed in them... fill that array when the cubes compute, and when necessary, you can check exact cubes that can collide using that array, very fast also.

then you can construct a dynamic collider using this array because you can access all triangles positions that you need instantly.

also there is the bullet physics engine under zlib licence.

---
Tags: collision-detection, software-engineering, perlin-noise, marching-cubes
---


# Question
Title: Can the different computation power in a multi-player game affect each player's performance?
In case an RTS game allows the clients to perform some calculations such as path-finding after the player clicks the map for a destination, and taking into account the game should be synchronised for all clients, there is clearly a chance that one of the machines is so slow that such computation (if it is done on a different process) might take much longer than in another client.

Therefore, the first player would experience a processing delay of his commands (and his units would be stopped for some time), giving the second player a clear advantage.

**Now, how is this usually managed in the commercial RTSs?**

Are all computations handled by the server and sent back to the clients? In case processing in the client would be preferred, how would you implement a system to avoid such a player advantage?

*Note: In SC2 I have seen how the server notifies the players that someone is slowing down the match. But I guess that is just the client has not enough speed to compute the visualisation.*

# Answer
To answer the question in the title: **Yes**.

At the very least having a computer that can display a larger resolution area at higher fps will give that player an advantage.

To answer the question in the body: **No**, their computation power doesn't affect the AI calculations and cause delays in sending pathfinding results.

The pathfinding calculations tend to be very easy / fast calculations in RTS games and having even a semi-modern machine can handle them fine. In games with more advanced AI the processing is done at the game server, such as in Titanfall.
> 2 votes

# Answer
Peoples perceptions are subjective but theres a ton of science that says a few key things about computer interactions we can lean on ...

1. As long the system updates and renders at roughly 25 FPS or higher the system is usable perceptibly suitable for game play

This comes from the fact that a typical TV holds our attention because it does not fall below this threshold (i should insert a link to some research on this).

2. If the game updates and renders faster than that then few will be able to react fast enough for it to make a tangible difference, however hardcore / professional gamers push this statement to the limit every day proving that somehow some people can react faster than the average to state change.
3. Computer applications these days are variable based on the load being presented to them as it happens (so an explosion may effect frame rates / update speed depending on programming) which may have a positive or negative effect. Having a faster PC means I am less likely to be affected by the next guy in this situation which could give me a temporary advantage.

However when all is said and done there are so many variables in play that can take effect here. For example: The computer is typically running through refresh loops that are insanely fast compared to the rate at which network traffic is received ... so is there any gain to having a superfast pc that then can't update the network at the same rate?

What you tend to see with RTS games is that someone "hosts" the game by starting up the client on their pc and starting a "server" their interaction with that server is going to be orders or mangitude faster than anyone on a LAN or over the internet so games hosted in the cloud tend to have a better "fairness" to them in that everyone is interacting with the same internet latency (to some extent, ignoring ISP perversions).

But taking all of that in to the inner workings here Yes an individual command might be slower to place on a slower pc on a slower connection but the overall game state is a long running process that all users are within half a second of each other in seeing so for the big picture it likely makes little or no difference.

In short ... as long as the game meets that first point threshold of 25 to 30 FPS it really comes down to ... If you see an enemy now or in half a second time are you more or less likely to issue the same command?

My thinking is ... YES you are so .. NO it makes no difference.

In an FPS style game however where the game state (perception of at least) changes so fast that may not be quite the same in that I may go left unless I see an explosion in which case I may go right ... my perception is shifted enough that it could effect my decision.

So the real question that should be asked ... What is the frequency point at which a game update affects the decision a user will make?

And that is a tough one !!
> 0 votes

---
Tags: client-server, rts, synchronization
---


# Question
Title: HLSL Shadow Mapping occurs only around player
I've recently begun playing around with Monogame (OpenSource "remake" of XNA). My current task is to write a simple shadow mapping shader. After following Riemer's XNA Tutorial I got the shadows to show up. But interestingly only around where the "player" (camera) is. When I'm outside of the light's radius there's no light showing up around the camera (which is good), but the light from my spotlight should of course still be there. But it's not. The shadows and the bright lighting from my spotlight only appear around player.

As I said, my HLSL code is exactly the same as Riemer's (Except that I wrote SV\_POSITION instead of POSITION0 at the VertexShaderInput struct because MonoGame only supports Pixel-/Vertexshader 4.0 and above)

I also have a feeling that my Light-View/-Projection Matrices might somehow be wrong:

```
Matrix lightsView = Matrix.CreateLookAt(lightPos, new Vector3(lightPos.X, lightPos.Y-1, lightPos.Z), new Vector3(0, 0, 1));
Matrix lightsProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45F), 1f, 1f, 10f);

```

(I know that my "up" vector is not pointing upwards; that was the only way I got the light to point downwards from it's position, otherwise it would always point to (0 -1 0) even if I wrote it so that the lights coordinates were used and then it would go y -1 from the light - really weird...)

I really hope someone knows what's up here, this issue prevented me from doing anything else in my code for a couple of days now...

PS: Here's my rendering code:

```
    ////In my Model-Class
    private void DrawModel(string tech)
    {
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (var mesh in model.Meshes)
        {
            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                part.Effect = Game1.effect;
                Matrix tempWorld = ((transforms[mesh.ParentBone.Index] * Matrix.CreateScale(scale)) * rotationMatrix) * Matrix.CreateTranslation(pos);
                part.Effect.CurrentTechnique = part.Effect.Techniques[tech];
                part.Effect.Parameters["xWorldViewProjection"].SetValue(tempWorld * Game1.camera.View * Game1.camera.Projektion);
                part.Effect.Parameters["xTexture"].SetValue(textures[part]);
                part.Effect.Parameters["xWorld"].SetValue(tempWorld);
                part.Effect.Parameters["xLightPos"].SetValue(Game1.currentLevel.lightPos);
                part.Effect.Parameters["xLightPower"].SetValue(Game1.currentLevel.lightPower);
                part.Effect.Parameters["xAmbient"].SetValue(Game1.currentLevel.ambientPower);
                part.Effect.Parameters["xLightsWorldViewProjection"].SetValue(tempWorld * Game1.currentLevel.lightsViewProjectionMatrix);
                part.Effect.Parameters["xShadowMap"].SetValue(Game1.currentLevel.shadowMap);
            }

            mesh.Draw();
        }
    }

    ////In my Level-Class
    public void Render()
    {
        var device = Game1.graphics.GraphicsDevice;

        device.SetRenderTarget(renderTarget);
        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        DrawScene("ShadowMap");

        device.SetRenderTarget(null);
        shadowMap = (Texture2D)renderTarget;

        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
        DrawScene("ShadowedScene");
    }

    private void DrawScene(string tech)
    {
        foreach (var model in models)
        {
            model.Render(tech);
        }
    }

```

and the light-update code:

```
private void UpdateLightData()
    {
        ambientPower = 0.2f;

        lightPos = new Vector3(-0.2F, 1.2F, 1.1F);

        lightPower = 1.8f;

        Matrix lightsView = Matrix.CreateLookAt(lightPos, new Vector3(lightPos.X, lightPos.Y-1, lightPos.Z), new Vector3(0, 0, 1));
        Matrix lightsProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45F), 1f, 1f, 10f);

        lightsViewProjectionMatrix = lightsView * lightsProjection;
    }

```

# Answer
> 0 votes
Alright, so I tried pretty much everything. It didn't work. Then I resignated and tried putting everything into an XNA project instead of using MonoGame... And it worked without modification. Maybe it's because it's now compiled with PS/VS 3.0 as supposed to 4.0. Maybe because of magic. I dont know.

# Answer
> 0 votes
It looks like you have a view projection specifically for your lighting ... so my guess is that the GPU is culling any math outside your view frustrum ...

Maybe try placing the "camera" for building your light map in a more "overview" type position or something?

but surely you only want to do light math in front of your camera not for your whole scene?

---
Tags: xna, c#, hlsl, monogame, shadow-mapping
---


# Question
Title: How to rotate object not from it's center point but from it's another point?
I am new in unity and I am developing a game where I want to rotate my object I try this code for it.

```
if(Input.GetMouseButton(0)){
        if(Input.GetMouseButtonDown(0)){
            LastMousePosition = Input.mousePosition;
        }
        else if(LastMousePosition.y> 112){
            Bow.Rotate(Vector3.up*(Input.mousePosition.y - LastMousePosition.y));
        }
        else if(LastMousePosition.y<112){
            Bow.Rotate(Vector3.down*(Input.mousePosition.y - LastMousePosition.y));
        }
        LastMousePosition = Input.mousePosition;
    }

```

It works fine for me but my object is rotate from It's center point and I want to rotate it from another point can any one help me with this?

# Answer
Create an empty gameobject, make it child of your gameobject. Move it to one of the corners you want to rotate about, Use RotateAround to rotate your gameobject. You could also do the same through code by calculating the dimensions of your gameobject.

Edit: You could use these scripts to make your life easier: PivotManager, SetPivot.
> 4 votes

---
Tags: unity, rotation
---


# Question
Title: How do I add a border to rectangles using a shader?
I want to draw some rectangles with a border. Currently I render the fill with `glDrawArrays(Triangles, ...)` and the border with `glDrawArrays(LineLoop, ...)`. Is there a neater way?

I'm targeting OpenGL 3.3.

# Details

Illustrative excerpt:

```
// vertexBuffer   -> VertexAttribArray(0)
// colorBuffer    -> VertexAttribArray(1)
// texCoordBuffer -> VertexAttribArray(2)

GL.DrawArrays(PrimitiveType.Triangles, 0, 12); // 2 test rectangles

GL.DisableVertexAttribArray(1); //Disable color array
GL.DisableVertexAttribArray(2); //Disable texture array

GL.DrawArrays(PrimitiveType.LineLoop, 0, 6); // First rectangle border
GL.DrawArrays(PrimitiveType.LineLoop, 6, 6); // Second rectangle border
// Lots of draw calls for every rectangle,
// if there are more than the 2 test rectangles...

```

This works fine, but I don't like having to draw the additional `LineLoop`s for every rectangle. How can I improve this?

Could I do this elegantly with a shader? Something like this:

```
// VertexArributes

GL.DrawArrays(Triangles, 0, vertices.Length); // Shader does the border

// DisableVertexAttributes

```

# My current shaders

## Vertex

```
#version 330 core

layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;
layout(location = 2) in vec2 texCoord;

uniform mat4 projMatrix;
uniform mat4 worldMatrix;

out vec4 vColor;
out vec2 texCoords[];

void main()
{
  gl_Position = projMatrix * worldMatrix * position;
  texCoords[0] = texCoord;
  vColor = color;
}

```

## Fragment

```
#version 330 core

in vec4 vColor;
in vec2 texCoords[];

uniform sampler2D tex;

out vec4 fColor;

void main(void)
{
  fColor = texture2D(tex, texCoords[0].st) * vColor;
}

```

# Answer
> 9 votes
You can use your texture coordinates, and set a uniform that tells you the aspect ratio of your rect, and the desired width of your border. Then, you can just check to see if your pixel falls within the bounds of your rectangle.

```
(0, 0)                         (1, 0)
-------------------------------------
|  (0.1, 0.1)  Border  (0.9, 0.1)   |
|  -------------------------------  |
|  |                             |  |
|  |                             |  |
               . . .
|  |                             |  |
|  |                             |  |
|  -------------------------------  |
|  (0.1, 0.9)          (0.9, 0.9)   |
-------------------------------------
(0, 1)                         (1, 1)

```

Then in your pixel shader you can just test to see if the pixel is within the border:

```
uniform float border_width;
uniform float aspect;  // ratio of width to height
varying vec2 texCoord;

main() {
   float maxX = 1.0 - border_width;
   float minX = border_width;
   float maxY = maxX / aspect;
   float minY = minX / aspect;

   if (texCoord.x < maxX && texCoord.x > minX &&
       texCoord.y < maxY && texCoord.y > minY) {
     gl_FragColor = **rect color**;
   } else {
     gl_FragColor = **border color**;
   }
}

```

---
Tags: opengl, c#, shaders
---


# Question
Title: Changing distance after some time on OnGUI Unity
Though I am using IEnumerator to calculate the distance travelled value, the distance is updated very frequently, how can I change that? and why exactly increasing the time in WaitForSeconds function not changing the behaviour?

```
    void OnGUI ()
    {
        GUI.contentColor = Color.black;
        GUI.Label (new Rect (40, 40, 140, 40), "Speed : " + _speed, "color");
        StartCoroutine (distancetravelled ());
        GUI.Label (new Rect (40, 100, 100, 140), "Dist : " + Mathf.RoundToInt (distance * 1000) + " Kms", "color");

    }

    IEnumerator distancetravelled ()
    {
        timeInHours = (Time.smoothDeltaTime / 60) / 60;
        if(PlayerControl.collision != true)
        distance += _speed * timeInHours;
        yield return new WaitForSeconds (60);
    }

```

# Answer
Your coroutine is being started multiple times. The coroutine will continue to wait in the background, even though you're starting new coroutines on top of it. If you only want to start the coroutine once, add a simple flag:

```
bool coroutineRunning = false;

void OnGUI ()
    {
        GUI.contentColor = Color.black;
        GUI.Label (new Rect (40, 40, 140, 40), "Speed : " + _speed, "color");
        if(!coroutineRunning)
            StartCoroutine (distancetravelled ());
        GUI.Label (new Rect (40, 100, 100, 140), "Dist : " + Mathf.RoundToInt (distance * 1000) + " Kms", "color");
    }

IEnumerator distancetravelled ()
    {
        timeInHours = (Time.smoothDeltaTime / 60) / 60;
        if(PlayerControl.collision != true)
        distance += _speed * timeInHours;
        yield return new WaitForSeconds (60);
        coroutineRunning = false;
    }

```
> 1 votes

# Answer
Documentation : This means that your OnGUI implementation might be called **several times per frame (one call per event)**. For more information on GUI events see the Event reference.
> 1 votes

---
Tags: unity
---


title: animation control problem

text:
# Question
Title: animation control problem
I have a list of .FBX object.When I drag that .FBX into scene its corresponding inspector Animation component(fig 1) appears but when I drag some other .FBX object into the scene the Animator component(fig 2) is getting added to the scene.Please see the image attached

Issues Found : 1)fig (1) - When we click on the object and write code to display animation

```
void OnMouseEnter()
{
 animation.Play("DropBothFork01");
}

```

The above code is working But if we consider fig(2) the code is not working even though adding a animation component.

What will be the issue?Why for each .fbx object when drag into scene the animation and animator component varries.Could you please help me out solving it.

# Answer
The short answer is that you don't have an animator controller on that object (note the 'None' in the Controller slot.)

The long answer is... kinda long. Read my answer here, how to setup an Animation Controller: Unable to use Maya animation with scripts when imported to Unity
> 1 votes

# Answer
Fig1 has the animation that you call in your code.

Fig2 has an animator component but no animation, this may explain the problem. try replacing the animator with your animation you want to run then call it in the same way you do in the code related to Fig1.

This is likely something not quite right with the fbx / prefab that contains it.
> 0 votes

---
Tags: c#, unity, animation
---


title: What does Quaternion.Lookrotation do?

text:
# Question
Title: What does Quaternion.Lookrotation do?
I have this code,

```
if(Physics.Raycast(camRay,out floorHit,camRayLength,floorMask))
{
    Vector3 playerToMouse = floorHit.point-transform.position;
    playerToMouse.y=0f;
    Quaternion newRotation = Quaternion.LookRotation(playerToMouse);

    playerRigidbody.MoveRotation(newRotation);
}

```

What happens when I use playerToMouse = floorHit.point,instead of playerToMouse = floorHit.point-transform.position.

# Answer
Quaternion.LookRotation() turns a direction vector into a quaternion (by "looking" along that direction)

floorHit.point-transform.position determines the direction vector between the hit position and the object's position, versus floorHit.point is simply a position. Specifically, subtracting one position from another gets the direction vector between those positions.
> 3 votes

---
Tags: unity, unityscript
---


title: Tons of textures using vbo

text:
# Question
Title: Tons of textures using vbo
I recently learned how to create shaders and was looking to make a simple top down game, starting with a tilemap. The problem I encountered, Whilke I can store a vbo of all the blocks in a "chunk" of blocks, I can't specify what texture it should have... or at least I don't see how! I could just bind the texture using GL.BindTexture() function, but that would only allow me to use one texture in the whole chunk! I don't know how many textures I might render, it could certainly be more than 8! Is there a way to bind a texture inside a vertex shader?

I basicly would like to do something like "Display Lists" in earlier opengl versions... but I want to use modern opengl techinques as much as possible!

# Answer
Solution 1: Texture Atlas where you can tweak the UV coords in your mesh to specify a subsection of the texture to use for a portion of your map. This solution requires that each "tile" of the map be a separate quad so you can control the UV coords of each corner... sharing verticies at the corners of a tile will not work right.

Solution 2: if you are doing more like terrain than a tile map, texture splatting uses one texture to control the blending of texture data from several other textures to decide what the final pixel color is... a simple version could use RGBA data from the splat map to blend the colors from 4 other texture maps to create the final output... more complicated systems sometimes use multiple vertex colors to blend colors from 4/8/12 textures, but due to limitations in the number of samplers allowed in a pixel shader, this tends to take multiple shader passes.

Number 1 is probably what you want for a true top down tile mapped game.. but maybe texture splatting will give you other ideas :)
> 2 votes

---
Tags: opengl, shaders, vbo
---


title: Water Physics In top down 2D game

text:
# Question
Title: Water Physics In top down 2D game
I have been making a game like Minecraft or Terraria in which you add blocks and such to the world, and I came across this interesting debacle, the game is in a top down 2D perspective, and I would like to make it so users can add water to the world, however I would also like the water to behave like water would in the real world.

In other words, spread.

I'm guessing the code would work something like

```
if (space next to water block is open)
{
    \\spread to that block
}

```

However, this would not stop the water at that point, flooding the underpart of the map and creating little islands where the players have made things.

I could also pre-make the map, and put the water in that way, allowing the land mass of the map to go unscathed, however this prevents the players from making their own rivers and whatnot.

So my question is, do I prevent players from using water? Or do I allow them to and try to fix any disasters?

Would there be any use to code that allows me to limit the amount of water generated?

The reason water is important is due to the fact that several water vehicles are being planned, and water could be used as a resource to feed the player (dehydration etc)

**EDIT:** I have worked in water as follows. It the player will add the water like a block, at this point the water will spread in an equal outward direction.

If the water intersects **ANY** block it will stop and proceed with phase two, which is to move back and forth to simulate waves.

I found that through using XNA's ability to locate the side of the rectangle intersected, I can make it continue on down a length

For example:

```
 if (water.Intersects(something) && something.position.Y >= water.Top)
 {
     \\allow the water to continue adding to the width until the width hits something

 }

```

Here is an image of the partially completed function in action

# Answer
> 1 votes
I'm not quite clear on what you meant in your question, but I believe that limiting the spread of a particular water source would indeed solve your problem.

Perhaps something along the lines of giving it a `height` and `maximum water limit` when spawned, and decrementing the `height` and `max water` each block it goes along, with spreading to a lower block (you mentioned it was 2D top-down but gave the impression that there was height to blocks, is that correct?) giving it more `height` but not maximum water. Or just `height` if you think that would help solve your problem.

I say go ahead with water, just keep experimenting until you find a balance that suits your game.

PS: I'm not sure if it's relevant (I would add this as a comment if I had the rep to), but I personally loved the fact that in Minecraft an ill placed water block could cause havoc, those parts of the engine were what helped make it so fun imo.

# Answer
> 0 votes
I'd just like to add a couple items to consider. The first is the speed at which water will transfer to an adjacent empty area. For example maybe one block of water will transfer 1/3 of it's volume per second to every open block next to it. If you open a second space for water, it would take two seconds (or whatever a tick of game time is) to get an equal amount of water in each space. If two spaces are opened, you would have all three spaces at an equal amount in one tick.

There shouldn't be much reason to keep it out. The player will likely learn to be careful. I would limit the amount of water generated. If you want to allow for a flowing source of water, I would make sure that there is some sort of outlet for every inlet.

The last item I would consider is an amount of water that is considered negligible and should be destroyed. Essentially evaporation of a very thin layer of water.

---
Tags: game-design
---


# Question
Title: How can I add a batch of sprites to a list in Unity's inspector?
I have a C# script with a public property:

```
List<Sprite> someSprites;

```

I would like to add **20** sprites to it, from the inspector window. However, it seems like the only way to do so is to drag one by one. Is there a simpler way to batch fill lists in Unity?

# Answer
> 6 votes
There are two ways to assign multiple objects:

1. **Editor**: Click on the object you want to assign items to. In the top-right of the inspector window, click on the lock icon. Select the objects you want to assign and drag them into the field. Once done un-click the lock icon.
2. **Code**: Assign it using `someSprites = Resources.LoadAll<Sprite>("Location");` inside `Awake()`.

---
Tags: unity
---


title: DirectX11 Linker error

text:
# Question
Title: DirectX11 Linker error
I'm in the process of learning DirectX and in the examples supplied with the book I get the following error:

Error 29 error LNK2038: mismatch detected for '\_MSC\_VER': value '1600' doesn't match value '1800' in d3dApp.obj

Google didn't really come up with anything, or rather I was struggling to understand how to fix it from what I read, could someone explain what it means/how to fix it?

The line of code that is causing it is:

```
ID3D10Blob* compiledShader = 0;

HR(D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(),
    0, md3dDevice, &mFX));

```

# Answer
> 1 votes
You're trying to use .obj files produced with a different version of the compiler. You need to use the same older version of Visual C++ or you need to recompile whatever object files you're using. Presumably d3dApp.cpp and some others are source files provided with your book and you're using the pre-compiled versions instead of the sources.

# Answer
> 0 votes
The warning is a protection mechanism in the compiler when linking static libraries made with one version of the VC compiler with code built by another version of the VC compiler. This only matters for some specific headers, notably STL, but can also get pulled in by some other headers in older versions of the compiler (such as stdint.h). This does not affect import libraries for DLLs, just static libraries that contain code.

I'm guessing you are using a static library of Effects 11 that was built by the book author, since we never shipped a static library of it just the source in the legacy DirectX SDK.

The solution here is really simple: Build Effects 11 yourself with your current compiler. The latest version of Effects 11 is on CodePlex.

Note that the book you are using likely has some other deprecated D3DX11 stuff as well. See this blog post for some modern replacements. Also be aware that since you are apparently using Visual Studio 2013 (the MSCVER 1800 compiler), but the book was using Visual Studio 2010 (the MSCVER 1600 compiler), the setup for projects that use legacy DirectX SDK must change since VS 2012 and VS 2013 have the Windows 8.x SDK. See MSDN and this blog post.

---
Tags: directx
---


# Question
Title: Where/how do I store configuration files in Unity development?
I am transitioning from working with cocos2d-iphone to Unity.

One particular thing I loved were the `.plist` files: you could easily put any sort of configuration data you wanted: for game levels, stats, etc.

Now, with Unity, I am not entirely sure if I am supposed to be using such files. I suppose I can, but I'd rather adapt myself to whatever Unity developers use. What is the equivalent to property-list files in Unity development? Plain text files?

# Answer
For data that is created at design time you can use the TextAsset resource type. Note that despite its name it can be used for arbitrary binary data if preferred.

To persist data that is created at run time PlayerPrefs provides a key-value store. This will be implemented in a platform appropriate manner and performance may vary. If storing a large number of items at once is causing delays it may be improved by consolidating the data into a single sting.

To simplify parsing of this data many people use SimpleJSON.
> 6 votes

# Answer
**Prefabs** : It is convenient to build a GameObject in the scene by adding components and setting their properties to the appropriate values. Or you could write your own similar system. Check this tutorial written by @Byte56.
> 1 votes

---
Tags: unity
---


# Question
Title: C# XNA Rectangle.Contains returns false?
I am creating a simple XNA game. My `mainMenu` class contains a list of strings for menu options wich I draw on the scren using `spriteBatch.DrawString`. I've set `Vector2` variables to controll the position of the spritefont. Then I created 2 `Rectangle`s (and took the values of the `Vector2`s) and 2 `Color`s that will be given a value if the mouse is/isn't currently hovering the drawn string. My mainMenu.cs class contains these variables:

```
Vector2 playGameButtonPos = new Vector2(303, 300);
Vector2 exitGameButtonPos = new Vector2(303, 350);
List<string> m_ButtonList = new List<string>();
Rectangle m_ButtonArea0 = new Rectangle(303, 300, 50, 30);
Rectangle m_ButtonArea1 = new Rectangle(303, 350, 50,30);
Color optionsColor0;
Color optionsColor1;

```

mainMenu.LoadContent(ContentManager Content):

```
Game1.g_MainMenuFont = Content.Load<SpriteFont>(".\\mainMenu\\mainMenuFontTex");

```

mainMenu.cs's constructor:

```
m_ButtonList.Add("Play Game");
m_ButtonList.Add("Exit Game");

```

mainMenu.Draw(SpriteBatch spriteBatch):

```
var m_MousePosition = new Point(Game1.g_MouseState.X, Game1.g_MouseState.Y);
if (m_ButtonArea0.Contains(m_MousePosition))
{
    optionsColor0 = Color.Yellow;
}
else
{
    optionsColor0 = Color.CornflowerBlue;
}
if (m_ButtonArea1.Contains(m_MousePosition))
{
    optionsColor1 = Color.Yellow;
}
else
{
    optionsColor1 = Color.Red;
}
spriteBatch.DrawString(Game1.g_MainMenuFont, m_ButtonList[0], playGameButtonPos, optionsColor0);
spriteBatch.DrawString(Game1.g_MainMenuFont, m_ButtonList[1], exitGameButtonPos, optionsColor1);

```

Game1:

```
public static MouseState g_MouseState = Mouse.GetState();
public static SpriteFont g_MainMenuFont;
mainMenu m_MainMenu;

```

Game1's `Initialize()` method:

```
m_MainMenu = new mainMenu();

```

Game1's `LoadContent()` and `Draw()` methods:

```
m_MainMenu.LoadContent(Content);

m_MainMenu.Draw(spriteBatch);

```

But when I hover with my mouse on the position where the `Rectangle` should be, nothing happens.

# Answer
You're only asking for the mouse state once. You'll get the mouse state as it was at the time of initialisation. Specifically I think you'll get a **copy** of the mouse state at the time of initialisation, so it will appear to never change.

Call Mouse.GetState() directly in your Draw function instead.
> 2 votes

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


# Question
Title: changing a sprite width when playing a reel using Crafty.js
can anyone help me with this : http://jsfiddle.net/B5UsC/20/

you can see that the sprite animation is not rendering correctly when the reel is in the last frame when animating `Hardpunch` is it possible to change the character width when playing a specific frame ? like you see my spritesheet does not contain a static width and height so it's a bit confusing for me

**THE CODE :**

```
// initialize the sprite
Crafty.sprite("http://i.imgur.com/bkYVEe5.png", {
    Ryu: [0, 0, plrw, plrh]
});

// initialize the component
Crafty.c("RyuAnimation", {
    init: function () {
        this.requires("SpriteAnimation,Keyboard")
        .addComponent("Ryu")
        .reel('idle', 300, [
            [0, 0],
            [plrw * 1, 0],
            [plrw * 2, 0],
            [plrw * 3, 0]
        ])
        .reel('punch', 300, [
            [plrw + 12, plrh],
            [plrw * 2 + 15, plrh]
        ])
        .reel('Hardpunch', 300, [
            [plrw * 3 - 25, plrh],
            [plrw * 4 + 32, plrh],
            [(plrw + 19) * 5 - 38, plrh]
        ]); //
        this.animate("idle", -1);

    }

    // creating the player
    plr1 = Crafty.e("2D,Canvas,RyuAnimation")
    .attr({
    x: 15,
    y: ch - 100
})
.start(3);
this.bind('KeyDown', function () {
    if (this.isDown('A')) {
        if (!this.isPlaying("Hardpunch")) {
            this.pauseAnimation().animate("Hardpunch", 1);
        }
    } else {
        this.stop();
    }

});

```

I read about handling complex sprite sheet with different width and height and all the answers was about creating evenly sized boxes for all sprites like this example here : How do I support animation with frames of different sizes? but i actually couldn't understand what the mean by that and how would i do it they didn't provide an example . what is `evenly sized boxes`?

# Answer
The sprite sheet that you are using is what is known as a "sprite atlas". I am not sure that Crafty supports them. The current solution is to make even separation between all sprites so that they are in a grid.

See: https://groups.google.com/forum/#!topic/craftyjs/eN9KTAxieSI
> 0 votes

---
Tags: javascript, crafty
---


# Question
Title: How to find a free patch of area in a tiled map?
I've been trying to formulate the question and try to find some information on Google, but didn't managed to, so here it is... We've got a nice tropic-themed game that is about to be released soon, that uses a tile map and an A\* pathfinding is utilized and everything works flawlessly.

Until when it comes to the point where I need to somehow find **unoccupied patch of area** on the map that matches certain criteria, so that I can guide the player to place their just bought map objects on.

The map is 200x200 tiled map and it holds instances of each tile that determine two things - if it is occupied and if it is a water or a ground tile. These are already used for the A\* pathfinding algorithm that I've put into the game.

Let's say the player buys a water-placible map object from the store and the map object occupies 5x5 tiles for instance. I need to guide the player to a free patch of water tiles where they can place that map object.

Any guidance and/or reference to such algorithms will be highly appreciated :) Thanks

**EDIT: It turns out that I need to find such a patch as close as possible to given point (centre of viewport for instance). This will improve user experience**

# Answer
> 4 votes
**Method 1** Here's a fairly brute-force algorithm:

1. Scan across each row, left to right, top to bottom, until you hit an unoccupied tile of the correct type. (You can skip the far right columns/bottom rows once you get too close for the placement to fit)
2. Once you find a valid tile, check all tiles that would be within the placement footprint, if you put the top left corner here. Start with the tile furthest away (the bottom-right corner of the placement), and gradually work back.
3. If you find an invalid tile (wrong type/already occupied), mark all tiles in the rectangle containing your proposed top-left corner and the obstacle as "explored", and resume searching with the next tile after the proposed top-left corner.
4. As you continue your main scan, skip over any tiles marked "explored"
5. If your search in 2 does not find an obstacle, return your proposed top-left corner as a valid placement and terminate.

Steps 3 & 4 are a small improvement over straight-up brute force search, in that they keep you from repeatedly checking the same patch. Starting from the opposite corner lets you skip as many tiles as possible using this trick.

**Method 2** If you need to improve on this (profile, to see if it's worth your trouble), you can keep a bit of helper data with each tile: the size of the largest unoccupied square of the same type with that tile as its top-left corner.

Fill this data in once during map generation, by brute force if need be, then update it any time a tile changes state (search a rectangle up & left of the changed tile for any tiles that count it in their largest square. Decrease their largest square so that it ends just before the changed tile. You can end this search early once you've gone as far as the widest placeable item in your game.)

Now you can find a rectangle of the right size with a linear scan of the map. You can shape this scan any way you want - say searching an expanding spiral out from the focus of the player's current view, so that you can minimize the camera move required.

If you need even faster lookups (doubtful), you can use this data to sort your tiles into a heap (or series of heaps) by largest-placeable-area. Then in a O(1) operation you can pluck out a tile big enough for a given placement, or correctly conclude that none exists. (Just watch out, if you always choose the biggest-available area, regardless of the size of the placement, you'll tend to fritter away your wide open space on small placements)

That kind of acceleration structure can be expensive to maintain though, so only do it if your searches for placeable areas are causing noticeable problems.

# Answer
> 2 votes
A similar problem is finding the largest square block in a binary matrix and the algorithm actually gives the number of largest square blocks for every cell if this cell is top-left of the square block.

A very good documentation of the algorithm is the answer by Joy Dutta in the Dynamic programming - Largest square block question on SO.

---
Tags: algorithm, tiles, maps, tilemap
---


# Question
Title: Ambient occlusion: Correct culling after anisotropy correction
I've added simple color based ambient occlusion to my game.

First it looked like this (from giawa.com):

The description: "Due to anisotropy, the ambient occlusion shading on the top left is inconsistent with the top right. We need to flip those quads so that they get rendered properly."

So according to that I had to flip some faces in order to fix the issue. I did and then it would look like this:

This is of course because of back face culling, culling the flipped faces.

When I disable culling, it looks like this:

Which is how it's supposed to look. But as you can imagine, that costs a lot of performance because culling is now disabled.

According to the article: http://www.giawa.com/author/giawa/page/10/ "This occurs due to differences in how the GPU linear interpolates across the edge of a triangle versus the body of a triangle. This is called anisotropy, and can be fixed by ‘flipping’ the quad. My final fix was to enable polygon culling, which meant I had to make sure to render my quads in a consistent winding. "

I've searched for this "polygon culling" but could not find anything about that.

I can't just switch between culling modes because all the vertexes are added to a vertex buffer when initializing a chunk. This is so I can render each chunk in one draw call.

I hope anyone knows a way to fix this, thanks in advance.

# Answer
> 4 votes
By "flip the quads", the article doesn't mean to reverse the winding order. That swaps the front and back faces of the quad and causes other problems, as you've found.

The article means to change the way the quad is divided into two triangles. Instead of a quad like this:

```
 __________
|         *|
|      *   |
|   *      |
|*_________|

```

sometimes you need a quad like this:

```
 __________
|*         |
|   *      |
|      *   |
|_________*|

```

Splitting along the other diagonal makes the vertex interpolation look different, and the article is taking advantage of this to improve the appearance of the AO.

It can be done by permuting the vertices. If the first quad had vertices 1, 2, 3, 4 then the second one should have 2, 3, 4, 1.

(BTW, the author's use of the term "anisotropy" in that article is a bit confusing as that word is usually used only to talk about anisotropic texture filtering, which is something completely different. What the author calls "anisotropy" I would just call the fact that vertex interpolation is done per-triangle, not per-quad.)

---
Tags: c++, directx, culling
---


# Question
Title: Speeding up sprite the second time it passes the screen
I'm a student studying Games Development. I want a sprite to speed up on it's second passing of the screen. How do I do this?

Code I wrote so far:

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    int displaywidth;
    int displayheight;

    int carwrap;
    int carspeed;
    //structure for 2D graphics
    struct graphic2D
    {
        public Texture2D image;
        public Rectangle rect;
    }
    //structure for moving 2D graphics

    struct sprite2D
    {
        public Texture2D image; //texture to hold image
        public Vector3 position; //position on screen
        public Rectangle rect;  //size and position
        public Vector2 origin;  //centre point
        public float size;      //size ratio
        public Vector3 velocity; // sprite speed and direction
        public BoundingSphere bsphere; //bounding sphere

    }
    sprite2D car;
    sprite2D car2;
    graphic2D background;
    Boolean gameover;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        // set game resolution to current resolution
        //this.graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
        //this.graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        //store height and width of screen

        displaywidth = graphics.GraphicsDevice.Viewport.Width;
        displayheight = graphics.GraphicsDevice.Viewport.Height;

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        //load background image
        background.image = Content.Load<Texture2D>("challenge1");

        //work out ratio for image depending on screen size
        float ratio = ((float)displaywidth / background.image.Width);

        background.rect.Width = displaywidth;
        background.rect.Height = (int)(background.image.Height * ratio);

        background.rect.X = 0;
        background.rect.Y = (displayheight - background.rect.Height) / 2;

        // Loads sprites to car
        car.image = Content.Load<Texture2D>("sub1");
        car2.image = Content.Load<Texture2D>("sub2");

        reset();
        // TODO: use this.Content to load your game content here
    }
    // use the reset to initialise at start of game and call again when game is restarted
    void reset()
    {
        //set initial position car 1
        car.position = new Vector3(displaywidth / 10, displayheight / 2, 0);
        car.size = 0.5f; //set size of car
        car.origin.X = car.image.Width / 2;
        car.origin.Y = car.image.Height / 2;

        car.rect.Width = (int)(car.image.Width * car.size);
        car.rect.Height = (int)(car.image.Height * car.size);
        car.velocity = new Vector3(4, 0, 0);
        carspeed = 0;

        //car 2
        car2.position = new Vector3(displaywidth / 10, displayheight / 1.2f, 0);
        car2.size = 0.5f; //set size of car
        car2.origin.X = car2.image.Width / 2;
        car2.origin.Y = car2.image.Height / 2;

        car2.rect.Width = (int)(car2.image.Width * car.size);
        car2.rect.Height = (int)(car2.image.Height * car.size);
        car2.velocity = new Vector3(8, 0, 0); // Velocity of (X,Y,Z)
        gameover = false;
    }
    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {

        KeyboardState keys = Keyboard.GetState(); //reads keyboard

        if (!gameover)
        {
            //  code for when game is running
            car.position += car.velocity; //add current velocity to pos of thr

            // check if car hits any of the four sides and bounce it off them

            if ((car.position.X + car.rect.Width / 2) >= displaywidth) //RHS

                car.position.X = 0;
                carwrap++;

                if (carwrap % 2 == 0)

                    carspeed++;

                car.rect.X = (int)car.position.X;
                car.rect.Y = (int)car.position.Y;

            //set bounding sphere
            car.bsphere = new BoundingSphere(car.position, car.rect.Width / 2);

            // car 2
            car2.position += car2.velocity; //add current velocity to pos of thr

            // check if car hits any of the four sides and bounce it off them

            if
                ((car2.position.X + car2.rect.Width / 4) >= displaywidth) //RHS
                car2.position.X = 0;
            //other way
            //if ((car2.position.X - car2.rect.Width / 2) <= 0)//LHS
            //car2.position.X = (car2.rect.Width / 2);

            car2.rect.X = (int)car2.position.X;
            car2.rect.Y = (int)car2.position.Y;

            //set bounding sphere
            car2.bsphere = new BoundingSphere(car2.position, car2.rect.Width / 2);

        }

        else
        {
                reset();
        }
        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        spriteBatch.Draw(background.image, background.rect, Color.White);

        //draw car
        spriteBatch.Draw(car.image, car.rect, null, Color.White, 0,car.origin, SpriteEffects.None, 0);
        spriteBatch.Draw(car2.image, car2.rect, null, Color.White, 0, car2.origin, SpriteEffects.None, 0);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}

```

# Answer
> 0 votes
You are doing most of it already.

When you wrap the car around the screen, you are incrementing carspeed. But you never use the carspeed variable.

You are using the velocity vector to control the speed of the car. You could, for instance, increase the velocity instead of carspeed.

# Answer
> 0 votes
This looks like XNA/Monogame. If you really wanted to base it on the draw rate, change the code in the Draw() method to toggle a bool and increase the Car object position property whenever the bool toggles true.

Ideally you really don't want to do this on a draw - the car's position should be handled by update as everyone gets different refresh rates and hits the draw method a different number of time per second. You should instead look at your code in the Update() method and put your toggle in there. That way the car will consistently hop ahead a little bit equally for everyone.

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


# Question
Title: What's wrong with my step-toward-target implementation?
I want to move a game object from its current position toward the mouse position.

I wrote this `Vector2D` class to help me:

```
public class Vector2D {

        private double xVect;
        private double yVect;

        public Vector2D() {
                xVect = 0;
                yVect = 0;
        }
        public Vector2D(double x1, double y1) {
                xVect = x1;
                yVect = y1;
        }
        public double getX(){
            return xVect;
        }
        public double getY(){
            return yVect;
        }

        public double length() {
                return Math.sqrt((xVect*xVect) + (yVect * yVect));
        }
        public void normalize() {
                double length = length();
                if(length > 0){
                    xVect = (xVect/length);
                    yVect = (yVect/length);
                }
        }
        public Vector2D normalize2() {
                double length = length();
                return new Vector2D((xVect/length), (xVect/length));
        }
}

```

I then try to move it toward the target position.

```
public void move(){
// saveX , saveY - mouse x, y coordinates
// x, y - game object coordinates
    Vector2D moveVec = new Vector2D(saveX, saveY);
    moveVec.normalize();
    while(cont){
        if(saveX > x){
            x += ((moveVec.getX()));
        }if(saveX < x){
            x -= ((moveVec.getX()));
        }
        if(saveY > y){
            y += ((moveVec.getY()));
        }if(saveY < y){
            y -= ((moveVec.getY()));
        }
        sleep(); // Thread.sleep(200);
        frame.repaint();
        cont = moveEnemy(moveVec);
    }
}

```

But something strange happens: When **x = 0 and y = 0**, everything is OK, but when for example **x = 200 y = 0**, my object moves along the red line instead of directly toward its target.

Why is this? What's wrong with my code?

EDIT:

```
public boolean moveEnemy(Vector2D v){
    if((((x - sizeX) <= currentX && currentX <= (x + sizeY) && (y - sizeY) <= currentY && currentY <= (y + sizeY)))){
        return false;
    }else if((((x - sizeX) <= saveX && saveX <= (x + sizeY) && (y - sizeY) <= saveY && saveY <= (y + sizeY))) && (saveX != currentX || saveY != currentY)){
        miss(v);
        return false;
    }
    return true;
}

```

# Answer
Look at what's happening.

SaveX is 300, SaveY is 0.

When you normalize moveVec you take the Vector (300,0) and resize it to be a length of 1, which makes it (1,0).

You test to see if 300 \> your position, if so you add moveVec.getX(), otherwise you subtract. So you move 1 to the right. You then test to see if 0 \> your position, if so you add moveVec.getY(). The Y value of this, in this case is 0, so it shouldn't adjust the position of the object at all.

So after that, you call moveEnemy, which you don't describe in this post, and we know from your picture that it does move down the screen, so something else is moving it.

Now, consider what's happening when you use the vector (0,0). Regardless of whether the tests pass or fail, there is no movement, because moveVec.getX() and moveVec.getY() will be 0. So your move function should not cause any movement at all.

But it does move. It gets to your point correctly. But again, moveEnemy gets called.

My guess is that whatever is in moveEnemy might be doing its job correctly, but in move you're also moving the object, but incorrectly. When you use 0,0 it moves correctly because that causes the move function to not move the object at all.
> 1 votes

---
Tags: java, movement, vector
---


# Question
Title: Need help with algorithm for generating connected bricks in Pick A Brick clone
I want to make a clone of an Amiga 500 game, Pick A Brick, a 2D game where the goal is to clear a table of bricks by matching them up, following certain rules. I am getting nowhere when it comes to the algorithm for generating the layout of the bricks. I have added the rules of the game (as I remember them) below.

* The player wins the game by clearing all tiles before the time runs out.
* Tiles are cleared by clicking on a pair of them and if the following is true:
    + The tiles must be of the same type (there is only one pair of each type).
    + There is a clear path between them (more on path in the points below).
    + The path from a tile must always start towards an (clear) edge of the screen.
    + The path between the tiles must be u-shaped.

(edit) NOTE: In the video the path is not always the u-shaped. I do not recall if the path shown is just a shortcut or not, but regardless, in my version I do not want to allow removing tiles "from inside out".

I have done some manual testing/prototyping using both outside in and inside out approaches, with variations on both. So far, nothing I have come up with has really come close. I kind of dislike asking a question like this since it is so specific, probably not of general interest and may take up more than a little time for anyone interested in helping out. That being said, some people enjoy coming up with algorithms and "solving stuff", and the community may learn something from the answer, so, a post it is.

(edit) Clarification. The algorithm must provide a solvable solution.

# Answer
> 1 votes
Start with an empty board.

```
........
........
........
........
........
........

```

Add 2 tiles with the same image to different columns on the the left. Add 2 tiles with the same image to different columns on the right.

```
........
A.......
.......B
........
A.......
.......B

```

Repeat this pattern until the board is filled.

```
........
AC.....D
.......B
C.......
A......D
.......B

........
AC....FD
E......B
C......F
A......D
E......B

.......A
ACG...FD
E......B
C.....AF
AG.....D
E......B

B.....CA
ACG...FD
E.....CB
CB....AF
AG.....D
E......B

BD....CA
ACG..EFD
ED....CB
CB....AF
AG.....D
E.....EB

BDF...CA
ACGFGEFD
ED....CB
CB....AF
AG....GD
E.....EB

BDF..BCA
ACGFGEFD
EDA...CB
CB....AF
AG...BGD
EA....EB

BDFC.BCA
ACGFGEFD
EDA..DCB
CBC..DAF
AG...BGD
EA....EB

BDFCEBCA
ACGFGEFD
EDA.FDCB
CBCE.DAF
AG...BGD
EA...FEB

BDFCEBCA
ACGFGEFD
EDAAFDCB
CBCE.DAF
AGG..BGD
EAG.AFEB

BDFCEBCA
ACGFGEFD
EDAAFDCB
CBCEBDAF
AGGBCBGD
EAGCAFEB

```

You just have to make sure you don't leave the last 2 tiles in the same row. The puzzle is going to be solvable by making the same moves as you did to generate it.

---
Tags: algorithm, procedural-generation
---


# Question
Title: How do I output a webcam stream to a 2D canvas with SharpDX in C#?
I'm writing an application for the Oculus Rift using the SharpOVR library to access HMD position data. I decided it is reasonable to use SharpDX to also output webcamera streams.

Unfortunately, all SharpDX documentation is basically a copy paste from C++ documention and I only know basic C++. C# uses a different style, class names, etc. The MediaFoundation samples are also C++-only.

I'm trying to write a pretty simple part that renders 2 videos from 2 webcams. I've managed to get webcameras list with this code, but I'm failing to init one— it currently fails at `source.Start(descriptor, null, time);`

According to the exception, I need to bind all Stream events first. Or I am missing something I need to init?

Can one help with further actions from camera start till outputting to monitor? I know the code shouldn't be too hard, problem is adapting it to C#.

# Answer
> 4 votes
Sorry for not posting a complete solution, but I have done something relatively similar to what you're doing. You may be able to adapt this idea into your program.

What I did was output a video file into a Direct3D 9 (not 11) texture for rendering. I'm pretty sure it was possible to select a webcam as a video source instead of a video file, so in general this could be useful to you.

Notice that these are snippets from actual code, so there may be methods and other things that may not be included in these snippets. This is not meant for you to copy and paste, but so you can understand the general idea of what you have to do.

In general terms, the library you're interested in is `SharpDX.MediaFoundation`.

Reading a video source will give you a bunch of `Sample` elements, so you may want to create a `Queue<Sample>`, so on one side you're reading from the video source into the queue, and on the other side, you're converting those samples to textures and outputting them to your framebuffer.

Then, you create a `MediaFactory` and a `SourceReader`. Don't ask me what those parameters are, I wrote this a while ago, and I don't remember what each parameter is supposed to be (the docs are your friends):

```
var mediaAttributes = new MediaAttributes(IntPtr.Zero);
var SourceReader = new SourceReader(IntPtr.Zero);

MediaFactory.CreateAttributes(mediaAttributes, 16);
mediaAttributes.Set(SourceReaderAttributeKeys.EnableVideoProcessing, 1);
MediaFactory.CreateSourceReaderFromURL(url, mediaAttributes, SourceReader);
SourceReader.SetStreamSelection(SourceReaderIndex.AllStreams, false);

```

Right there where I'm doing `CreateSourceReaderFromURL` is where you want to change it to read from your webcam. After that, the rest of the program should be pretty similar for webcams and video files.

Now that you have the reader, you loop through the available streams. You should have one video stream, and one or more audio streams. At this point, we're just interested in the video stream:

```
int streamIndex = 0;
while (true)
{
    var nativeMediaType = SourceReader.GetNativeMediaType(streamIndex, 0);
    var currentMediaType = SourceReader.GetCurrentMediaType(streamIndex);
    var outputMediaType = new MediaType();

    SourceReader.SetStreamSelection(streamIndex, true);

    if (nativeMediaType.MajorType == MediaTypeGuids.Video)
    {
        VideoStreamIndex = streamIndex;

        VideoSubType = currentMediaType.Get<Guid>(MediaTypeAttributeKeys.Subtype);
        UnpackLong(currentMediaType.Get(MediaTypeAttributeKeys.FrameSize), out VideoWidth, out VideoHeight);
        UnpackLong(currentMediaType.Get(MediaTypeAttributeKeys.FrameRate), out VideoFrameRateNumerator, out VideoFrameRateDenominator);
        UnpackLong(currentMediaType.Get(MediaTypeAttributeKeys.PixelAspectRatio), out VideoAspectRatioNumerator, out VideoAspectRatioDenominator);
        VideoInterlaceMode = (VideoInterlaceMode)(currentMediaType.Get(MediaTypeAttributeKeys.InterlaceMode));

        MediaFactory.CreateMediaType(outputMediaType);
        outputMediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video);
        outputMediaType.Set(MediaTypeAttributeKeys.Subtype, new Guid(22, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71));
        outputMediaType.Set(MediaTypeAttributeKeys.FrameSize.Guid, PackLong(VideoWidth, VideoHeight));
        outputMediaType.Set(MediaTypeAttributeKeys.FrameRate.Guid, PackLong(VideoFrameRateNumerator, VideoFrameRateDenominator));
        outputMediaType.Set(MediaTypeAttributeKeys.InterlaceMode, (int)VideoInterlaceMode.Progressive);
        outputMediaType.Set(MediaTypeAttributeKeys.PixelAspectRatio, PackLong(1, 1));

        SourceReader.SetCurrentMediaType(streamIndex, outputMediaType);

        VideoReady = true;
    }
    outputMediaType.Dispose();

    streamIndex++;
}

```

`UnpackLong` is simply a function I made to get two `int`s out of one `long`. The `Guid` there is the format of the video. I think I got this for H.264, so you're going to have to look online what is the Guid for the native format of your webcam.

And then it's just a loop in which you fill your queue, and then consume from the queue. To read one video frame from the queue, you do something like this:

```
int readStreamIndex;
SourceReaderFlags readFlags;
Sample sample;

sample = SourceReader.ReadSample(SourceReaderIndex.AnyStream, SourceReaderControlFlags.None, out readStreamIndex, out readFlags, out timestamp);
if (sample != null)
{
    if (readStreamIndex == VideoStreamIndex)
        VideoSampleBuffer.Enqueue(sample);
    else // Other stream
        sample.Dispose();
}
if ((readFlags & SourceReaderFlags.Endofstream) == SourceReaderFlags.Endofstream)
    EndOfStream = true;

```

Now, on the rendering side, first you have to create a texture in which you will write your frames:

```
VideoTexture = new Texture(device, videoWidth, videoHeight, 1, Usage.Dynamic, Format.X8R8G8B8, Pool.Default);
var lockData = VideoTexture.LockRectangle(0, LockFlags.None);
byte[] data = new byte[videoWidth * videoHeight * 4];
for (int k = 0; k < videoWidth * videoHeight * 4; )
{
    // Fill with black
    data[k++] = 0x00;
    data[k++] = 0x00;
    data[k++] = 0x00;
    data[k++] = 0xff;
}
Marshal.Copy(data, 0, lockData.DataPointer, videoWidth * videoHeight * 4);
VideoTexture.UnlockRectangle(0);

```

Now, for each frame we want to convert, we simply lock the source buffer, copy the bytes into the texture and we're done.

```
var sourceBuffer = sample.ConvertToContiguousBuffer();
var sourcePointer = sourceBuffer.Lock(out maxLength, out currentLength);
var destRect = texture.LockRectangle(0, SharpDX.Direct3D9.LockFlags.None);
var destPointer = destRect.DataPointer;

CopyMemory(destPointer, sourcePointer, (uint)(reader.VideoWidth * reader.VideoHeight * 4));
texture.UnlockRectangle(0);

sourceBuffer.Unlock();
sourceBuffer.Dispose();

```

This last step is pretty inefficient, since even though the video decoding is probably done in the GPU, and the texture is also in the GPU, we're bringing both these buffers to RAM to copy them.

There is a library called DXVA2, which allows you to convert Media Framework frames into Direct3D9 textures with a single pass, without going through RAM. This is pretty cool, but I could not get it to work. Additionally, when I wrote my video renderer, DXVA2 was not supported on SharpDX, so there was a lot of interop stuff in there. If you're interested, you may want to start reading up on `DXVA2CreateDirect3DDeviceManager9`

On a related note, I've gotten accelerated video rendering working on iOS using xamarin. The idea is exactly the same, although the API is certainly quite different.

---
Tags: camera, sharpdx
---


title: Menus for LWJGL - Swing or other?

text:
# Question
Title: Menus for LWJGL - Swing or other?
Okay so I want to create a main menu which includes several buttons and text fields, is there a built in library for LWJGL or would I use normal Swing and start a thread of the application?

Its a 2D game and I'm simply looking for a way of starting it from a menu rather than having it jump straight into game.

# Answer
> 2 votes
As far as I know, there isn't a built in library for LWJGL, but there are several libraries using LWJGL.

I tried NiftyGui and TWL. TWL looks a bit easier and less messy to me, but both libraries need quite a lot of time to get used to work with (I managed to make some simple UIs with NiftyGui, with TWL we are stuck in the theme creation...).

If you only need buttons, you can make something pretty quick by yourself. But input text boxes (where the player can enter text) require some more work.

My advice would be: Check what you want to do. Do you want a complex or a simple UI. Does it need many different controls (sliders, checkboxes, comboboxes, textfield, multiline textfield, dropdown etc.) or only a few. If you have a complex UI with many menus, settings, editable controls etc. I would look at either TWL or NiftyGui, as both libraries are used by many people and work pretty well (if you set them up correctly). If you only need some basic things like buttons and a text menu, I would implement a basic UI by yourself, as it could take more time getting used to something like TWL or NiftyGui, then implementing the basic things from scratch.

As Peter Taylor pointed out, "Feng Gui" could also be an alternative. Though it seems to be discontinued, it seems to have a solid base: http://www.fenggui.org

# Answer
> 5 votes
This might be too late for you, but for the benefit of web searchers, I'll answer:

1. Create an empty canvas (AWT).
2. Set the size of the canvas to be equal to the LWJGL `Display`.
3. Add the canvas to the Java Swing form. (There's a reason for this).
4. Set the canvas as parent of the LWJGL `Display` using `Display.setParent(canvasName);`. (Remember you might also need to allow the display to be resizable.)

The reason for adding the canvas to the form before setting it as parent of the `Display` is that, the canvas needs to be drawable so it can be a parent of the the LWGL `Display`. Otherwise your program will crash with an error that no OpenGL context was found.

This official tutorial is a good reference.

---
Tags: java, lwjgl
---


title: Vertex definitions and shaders

text:
# Question
Title: Vertex definitions and shaders
I noticed that from looking at other examples like say .. riemers tutorials he takes a buffer with a bunch of vector3's in it and ties it to a shader which expects a float4 ... why does this work in his situation and not mine?

Also is there a simple fix for this situation that will allow me to do this with the shader determining the w component as to my game logic this means nothing but is obviously crucial to the gpu.

Riemers code is here:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series4/Textured\_terrain.php

and mine (key parts only) ...

CPU Code:

```
public struct TexturedVertex: IVertex
{
    public Vector3 Position { get; set; }
    public Vector2 Uv { get; set; }

    public TexturedVertex(Vector3 position, Vector2 uv) : this()
    {
        Position = position;
        Uv = uv;
    }
}

```

Shader Code:

```
struct VS_IN
{
    float4 pos : POSITION;
    float2 tex : TEXCOORD;
};

struct PS_IN
{
    float4 pos : SV_POSITION;
    float2 tex : TEXCOORD;
};

Texture2D picture;
SamplerState pictureSampler;

PS_IN VS(float4 inPos : POSITION, float2 uv : TEXCOORD)
{
    PS_IN output = (PS_IN)0;
    output.pos = mul(inPos, mul(World, ViewProjection));
    output.tex = uv;
    return output;
}

```

How do the two tie together?

I am however using sharpDX not XNA so my code for setting up the buffers is different slightly ...

I created my own mesh class that does this:

```
VertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer ,Vertices.ToArray());
context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, Utilities.SizeOf<TexturedVertex>(), 0));

```

# Answer
> 0 votes
Turns out the problem was in my material handling code ,,

```
layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[]
        {
            new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
            new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
        });

```

See that 12 ... yeh it was wrongly a 16 :(

---
Tags: hlsl, sharpdx, vertex-buffer
---


# Question
Title: Is moving entities between sectors of a grid spatial partitioning inefficient?
I'm using a grid system for spacial partitioning. If I have moving entities, will I have to reassign every entity to its correct section every frame?

Surely this is inefficient. Have I got the wrong idea?

# Answer
> 5 votes
First of all, unless you have an exorbitant number of entities, assigning them to a sector on every logic frame is most likely performance-wise negligible.

That said, it sounds like you are in over your head. Either your game doesn't actually need spatial partitioning, or what you are trying to create is too advanced for your level.

The point of spatial partitioning is usually that you can avoid double-looping over all your entities to do collision detection. But that double-loop usually isn't a big issue if you have less than around 1000 entities.

If you plan on having that many entities, then ask yourself: Do the big number improve the gameplay? And do I have the resources to do all the work this requires?

The point of all this is that you should focus your effort, don't solve problems that don't exist, and try to achieve the desired gameplay by as simple means as possible. Stacking on more complexity is easy, retaining a good game while doing so is difficult.

# Answer
> 2 votes
You don't have to check every entity, every frame. You only have to check entities when you move them. Further, since you're using a grid system, you can just check to see if they've crossed a boundary.

For example, if they're currently in grid 5,5 and you have a grid line every 10 units, you only have to do a modulus on their current x and y coordinates to know if they belong in a new grid. This is a pretty fast test.

# Answer
> 2 votes
This does not necessarily have to be as computationally expensive as you imagine. First of all, as you hinted at, you don't have to check every entity; just the ones that are moving. As such it might be wiser to have individual entities update their grid cell in their update method.

As for checking coordinates, there are a few optimizations you could make. For example, say your grid is made up of cells that are 64x64. To figure the coordinates of which cell an entity is in, all you have to do is `x>>6` and `y>>6` (try it). This is faster than, say, a grid with cells that are 100x100, where to find out the cell coordinates you would need to do `x/100` and `y/100` and floor the result (or cast into `int` if it's not already). Thus it's more efficient on a larger scale to pick cell sizes that are powers of 2 for example.

Although I doubt that this will be a bottleneck (remember premature optimization is the root of all evil), you could also update zones less frequently than on every game tick and maybe even make the rate depend on the maximum/expected speed of any given entity.

# Answer
> 1 votes
The frame you're in is irrelevant. You don't do this every frame. When the entity moves just check if it's in a new section and update it as needed.

---
Tags: 2d, grid, space-partitioning
---


# Question
Title: Total Texture memory size iOS / OpenGL ES
My team is running into an issue where the amount of texture memory allocated via the `glTexImage2D` is high enough that it crashes the app ( at about 400 MB for iPhone 5). We're taking steps to minimize the texture allocation ( via compression, using fewer bits/channel and doing procedural shaders for VFX etc).

Since the app crashed on `glTexImage2D`, I felt like, it's running out of `texture memory` (as against virtual memory). Is there any documentation/guideline on the recommended texture memory usage by an app (not just optimize your texture memory) .

AFAIK on iOS devices ( and many Android devices) there's no dedicated VRAM and our app process is still well within the virtual memory limit. Is this some how related to the size of physical RAM ? My searches so far has resulted only in info on max texture size and tricks for optimizing texture usage and such. Any information is appreciated.

# Answer
> 3 votes
On iOS it seems that you are asking for trouble when the total memory usage for your app starts approaching half of the device's total memory (1gb for iPhone 5). But there's not a completely hard limit and it's not totally predictable. We have noticed that you get more leeway after a reboot of the device, for example. Anecdotally it seems that if your app has been ejected by the OS for using too much memory, it can be extra sensitive about ejecting you in the future (until reboot).

---
Tags: textures, ios, opengl-es
---


title: Why is my custom Texture2D blurry?

text:
# Question
Title: Why is my custom Texture2D blurry?
Have some WWW object downloading a .PNG image.

```
((SpriteRenderer)renderer).sprite = Sprite.Create(request.texture,
         new Rect(0,0,100,100));

```

My sprite looks fine.

Now, let's be a bit redundant and create a `Texture2D` out of the bytes from the download:

```
Texture2D t = new Texture2D(100,100);
t.LoadImage(request.bytes);
((SpriteRenderer)renderer).sprite = Sprite.Create(t, new Rect(0,0,t.width,t.height));

```

Technically, this should produce something identical to the above snippet. However, the sprite is blurry (as in, low quality).

I suppose it is when calling `LoadImage`. What may be causing this?

# Answer
Try changing the filterMode to Point:

```
t.filterMode = FilterMode.Point;

```
> 9 votes

---
Tags: unity, textures
---


# Question
Title: How do I handle packet loss in a client-server network model?
In a client-server network model, the clients only send commands to the server (i.e. coordinates of a click, fire gun, etc.) and the server then runs those commands to produce a game state.

But what if the client sends a command like "fire gun" in one packet which is dropped. Does the user experience that he tapped his fire-button with nothing happening or is there some intelligent way to make sure that such commands are received by the server regardless of packet loss?

I.e continuing to send the old "fire gun" command multiple times to ensure that it at least eventually fires (tagging the command so that the server understands that it is the same command sent multiple times, not a command that is fired over and over).

I've been looking at documentation regarding Quake3, Unreal and Source Network Models but I cannot find anything on this particular problem. I do believe they have solved it though because I never fired my AWP without it actually shooting. If there was lag involved, then it just took a short while before it shot, but it's never lost the command I think.

EDIT: I've found a resource that explains one way to handle this here: http://gafferongames.com/networking-for-game-programmers/reliability-and-flow-control/

They solve it by adding a kind of loose ACK on top of UDP. I feel like there should be a smarter way to go about it however. This way of handling it is ok for the server I guess which mostly needs to make sure that it has a live connection to the and to handle things such as chat messages (which are not really time sensitive but cannot be allowed to get lost) but for the client I believe an ACK creates too much delay when a packet is lost (a full round time latency at the very least).

# Answer
It always frustrates me how many people oversimplify the differences between TCP and UDP as "TCP is reliable but slow, while UDP is fast but unreliable".

This is not what TCP and UDP are about. TCP and UDP are two different abstractions over IP, and are used for different things. Both very good in their own fields.

TCP is a **stream** oriented protocol. You use TCP when you want to transfer a lot of sequential data from one point to another, maximizing the **throughput** (that is, minimize the amount of time it takes you to send -all- of the data). The automatic resending of lost datagrams and reordering are one of the features of TCP, but TCP also features stateful connections, flow control and congestion control. These features make TCP a really good tool for transferring large amounts of data from one point to another. Protocols such as HTTP and FTP where you want to send large chunks of data as fast as possible are meant to use TCP.

UDP, on the other hand, is a **message** oriented protocol. You use UDP when you want to send messages from one point to one or many points, minimizing the **latency** (that is, the amount of time it takes between a message is sent until it is received). In order to minimize latency, UDP does not implement datagram retransmissions or reordering. However, if you want your message-based application to support retransmissions and/or reordering, you can implement that yourself, and it's actually quite simple! Additionally, there is a bunch of fun things you can do in UDP that you simply can't do with TCP, like multicast and UDP hole punching.

TCP and UDP are both awesome technologies meant for different things, so what you want to do is to ask yourself whether the communications in your program are better represented as a stream of bytes, or as a series of messages, and a good rule of thumb is:

* If your program is about sending messages, use UDP.
* If your program is about sending a stream of bytes, use TCP.

This is what the decision between TCP and UDP should be like, not about reliability, which is just one of the many differences between them, and in my opinion the least important of them all.

Just like it is possible to make a stream abstraction over UDP, it is possible (and sadly very common) to make a message abstraction over TCP.

If you do choose to make a message abstraction over TCP, remember that you're going to have to use TCP in a way it was not meant to, which means you're going to encounter some difficulties. In particular:

* Message boundaries: TCP treats data as a very long stream of bytes, and as such, has no concept of packets or messages. If you want to send messages over TCP, you're going to have to create some kind of message header that includes the length of each message.
* Buffering on send: TCP expects you to be able to produce data as fast as you can. TCP datagrams can be very large, and if the network conditions are good, a TCP stack will buffer your bytes until it can send a very large datagram therefore maximizing throughput. This is a good thing for streams, but not so much for messages. Once too many times people end up flushing the buffer on each send, or using options such as `TCP_NODELAY`, and even then you have no guarantees. To quote the late Richard Stevens:

> 2.11. How can I force a socket to send the data in its buffer?
>
> You can't force it. Period. TCP makes up its own mind as to when it can send data. Now, normally when you call write() on a TCP socket, TCP will indeed send a segment, but there's no guarantee and no way to force this. There are lots of reasons why TCP will not send a segment: a closed window and the Nagle algorithm are two things to come immediately to mind.

* Buffering on receive: Even if you manage to flush the buffer on each send, there is no guarantee that you will get one reception for each flush you send. It is perfectly possible for you to get several messages on a single `recv` call, because they were buffered at the reception end (especially on networks with high packet loss rates). You then have to implement a message reception queue, which is a pretty stupid thing to do when you're using TCP.
* Heartbeats and connection drop detection: TCP has its own mechanism for detecting dropped connections, but they are usually too slow for message passing applications (the non-configurable keep alive datagram is sent about once every two hours). Once too many times people end up implementing their own hearbeat protocols inside the very same TCP stream, and then they end up asking "how to force close TIME\_WAIT", "How to detect a closed connection" or something like that.

None of these problems exist if you make your message oriented program with UDP:

* Message boundaries: Each message is a separate UDP datagram.
* Buffering on send: Doesn't exist. A `sendto` call immediately sends a datagram.
* Buffering on receive: Doesn't exist. You will only get one datagram per `recvfrom` call.
* Connection drop detection: UDP is not connection oriented. You can implement a simple timeout with your own parameters to consider a client is no longer there.

If you want to use TCP for message passing because you think it's simple, don't.

Now, for the dreaded reliability "problem", you can implement simple reliability by including two fields on each message: the first one is a permanently increasing message ID, and the second one is the largest message ID you have received from a particular client. If your internal count differs too much from what the client says he has received, you just resend starting from the first message the client hasn't received. With wrapover, you can do this with just two additional bytes per message.

The best thing about your own reliability layer is that you can tune it for whatever your needs are: you may have some message types with reliability in them, while others without it. You can have various channels, each with its own sequence numbers, you can use those numbers to predict lag, and lots of other awesome stuff.

Don't run away from UDP because other people have told you "it's hard". They probably have never (seriously) used UDP, and probably have not even (seriously) used TCP. Actually UDP is much more simple and easier to understand than TCP.

Read Stevens' Unix Network Programming. And then reread it.
> 9 votes

# Answer
To handle packet losses, you first need to decide which network protocol you will use: TCP or UDP.

* TCP: is reliable, but *slow* to send simple messages (has higher latency)
* UDP: has low latency, but to achieve your objective of not letting the user notice some packages losses, you will need to develop an extra layer that will slow your communication.

This extra layer is like the difference between UDP x TCP.

You will need to study the details of the TCP protocol and implement many features. You will need at least to develop ACK packets and packet ordering. If your layer is not well developed, it can be even slower than TCP.

Maybe you can mix both protocols in the same game.

UDP should only be used when you are delivering data that can be lost without problems. For example, if you miss the packet "enemy 1 is on field A", it is not a big problem if you repeat the enemy position from time to time. If you get the second packet with "enemy 1 is on field A" or "enemy 1 is on field B", it does not matter where it was before. You will just place the enemy in the last received field.

Now, if you don't want your player to lose ANY shots, use TCP (or a reliable modified UDP message).
> 1 votes

# Answer
Unless you are interested in the details of implementing your own reliability layer using UDP, I would recommend using RakNet, especially since it has been made open source. This would be the way to go if you are focused on making a game rather than a networking protocol.

With RakNet, you can send packets with certain reliability flags such as RELIABLE\_ORDERED. This ensures each packet will arrive (it is re-sent if it's not acked) and it uses an underlying ordering system so that the packets are processed in order on the receiving end. This would be very important if you are sending inputs for something like a fighting game where order is crucial for calculating moves and such. This is all very easy to accomplish using a library such as RakNet.

This will however increase the bandwidth, but you can choose appropriately which packets need to be reliable and ordered and which ones you can afford to lose.

Edit: Also consider following these articles for implementing fast paced multiplayer. It's quite easily done with a powerful library like RakNet.
> 0 votes

---
Tags: client-server, lag
---


# Question
Title: Is there any way to load pieces of a tile-map as and when needed, and not the entire map at once?
I created a tile-based rpg game in java, but it runs really really slow, the reason is the big tile-map that is stored in the buffer. Is there any way to programmatically load pieces of the map when needed and not the entire map at once, so that the buffer will remain small and the game will run fast? Any sort of useful tip would be helpful.

# Answer
> 1 votes
Oh man- I've implemented this a time ago...

The map is divided into map chunks - I've created separate files for each map chunk... a map chunk consist of 32x32 tiles in my implementation, you may vary on this

whenever the player (centre of red X) is moving inside a chunk you can detect if the player is moving from one chunk into another...

```
// Depending on chunk size - change 32 to your desired size

int xChunkBefore = xPlayer/32;
int yChunkBefore = yPlayer/32;

// Move player to new position

int xChunkAfter = xPlayer/32;
int yChunkAfter = yPlayer/32;

if (xChunkBefore == xChunkAfter && yChunkBefore == yChunkAfter)
{
    // No changes detected
}
else
{
    boolean isTeleport = someBool // check if teleport
    if (isTeleport){
         recreateWholeViewPort(newChunkCenter); //make all new!
    }
    else
    {
        Direction dir = determineDirection();
        updateChunksInView(newChunkCenter);
    }
}

```

So what to do now? When you have do display your view-port you don't have ALL chunks in memory only a 3x3 MapChunk\[x\]\[y\]...

And when you change into a new centre you do the following:

```
if (dir == Direction.NORTH)
{
    // All three chunks
    for (int dx = 0; dx < 3; dx ++)
    {
        viewPort.mapChunk[dx][2] = viewPort.mapChunk[dx][1];
        viewPort.mapChunk[dx][1] = viewPort.mapChunk[dx][0];
        viewPort.mapChunk[dx][0] = loadFromFile();
    }
}
// So so for all other directions

```

If you are using this approach you can theoretically have an unlimited large map but only show 3x3 map chunks...

NOTE - Directional movement is not mentioned here

NOTE - Buffering last movement is not mentioned here

NOTE - Teleport (load ALL) is not mentioned here

# Answer
> 1 votes
To expand upon my earlier comment: For a 2D tile map, I don't usually see any need to stream the map into memory, or load it by chunks. The easiest gains will come from simply not rendering any tiles that are off screen, and not updating any entities that are more than X screen size units away. If the map is truly massive, to the point that you can't iterate through it to cull your off-screen draw calls without breaking your frame-rate, then and only then will you want to find a way to break the map into chunks.

Let's assume your camera is tracked as being at an (x,y) point, and that unless the player character is at the edge of the map, the camera position matches the player position.

The first thing you'll need to know is the screen size, which is language/library dependent, and also another question.

For the sake of example, you've determined the screen size is 1920x1080. Having access to the tile assets, you know they're 16x16. You can then determine that you need to draw 1920/16 x 1080/16 =\> 120 tiles horizontally, and 68 (67.5) tiles vertically. Considering that the player/camera may not always be directly centered on a tile, you'll want to add a 1 tile buffer on either side in both dimensions. In terms of tile size, your screen dimensions are 122x70.

You'll also need to know the relative position of that screen area within the tile array. If the player/camera is at (4237, 5642), then your player is on tile (x.pos/tile.width, y.pos/tile.height) =\> (4237/16, 5642/16) =\> (264, 352). Taking the screen size in tile units from above (122x70), halving it, and adding to / subtracting from the player tile in each direction, your on-screen tiles would therefore range from (203,317) to (325,387). For later reference, I'll call these (xMinTile, yMinTile) and (xMaxTile, yMaxTile).

In your rendering function, where you determine which tiles to pass off to the video card, instead of sending the entire array of tiles you'll check against the min/max tile positions.

```
 renderer.beginBatch()
 for(i = 0; i < map.size.x; ++i)
    if(i >= xMinTile && i <= xMaxTile)
       for(j = 0; j < map.size.y; ++j)
          if(j >= yMinTile && j <= yMaxTile)
             renderer.draw(map[i,j])
 renderer.endBatch()

 # please excuse any Java syntax errors, I've been working mostly with Ruby lately

```

The 'j' for loop is inside the if check for x bounds to somewhat optimize the test. Similar to AABB collision testing, why check the Y dimension if we already know X is out of range? This is important to getting as much mileage out of this approach as possible, as is sending your tiles in a draw batch (assuming your renderer supports that, which... it really should), before you have to start breaking the map into chunks.

You'll have to make changes for determining the on-screen tiles as the player approaches the edge of the map, whether it overflows and wraps around, or just caps to the edge tile so you don't see the neutral zone outside the map boundaries, but this should cover the general idea.

# Answer
> 0 votes
Yes, of course there is a way...if you implement it.

The technique you seem to be looking is often referred to as "terrain paging". It stems from the fact that you divide your terrain/map into multiple pages (basically chunks / tiles) and only load / render those close to the player.

In your tile-map scenario, you already have the pages (= your tiles or sections of tiles depending on how big they are). Given that you know where the player is you know which tiles need to be rendered.

There are some points to consider when deciding on how many tiles to load / display:

* View that the users has (top down vs. 1st/3rd person with a horizontal view): Depending on that you might need more tiles to be rendered to create the illusion of a vast landscape.
* Movement speed of player: The faster the player can move the more pages you will need to prepare upfront to prevent lags when the users leaves old pages and enters new ones.
* You also need to separate between loading and rendering: It might make sense to already pre-load some of the resources needed for future tiles (models, textures, etc.) but simply not render them. This will cut down the time needed to prepare a new page, since you already have everything in the memory, but simply did not render it so far.
* To prevent lags in the rendering process, it might make sense to load the data for the next pages in the background to keep your main thread humming along nicely.
* Another technique that might help, is LoD (Level of Detail). In games you can often get away with rendering lower quality objects in the far distance (meaning less polygons and low resolution textures). This can also improve your game's performance.

# Answer
> 0 votes
You can start by doing this ...

I can load new tiles but how do I load new chunks?

Once you have that in place you can then choose what chunks to render by using some basic positional logic like "get me all the chunks with tiles between pos1 and pos2"

pos1 and pos2 can be simply determined like this ...

```
pos1 = char.Position - renderDistance;
pos2 = char.Position + renderDistance;

```

---
Tags: java, tilemap
---