# Question
Title: Can't figure out what's making the player teleport back to spawn
I've been working on a multiplayer game that uses pathfinding and I'm really confused over this one weird bug. On your screen, the other player glitches between the spawn point and his current location. It seems like there's a problem with the interpolation as it doesn't do this when I comment out:

```
transform.position = Vector3.Lerp(transform.position, bestGuessPosition, Time.deltaTime * latencySmoothingFactor);

```

Does this have anything to do with the way I'm moving the player?

```
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Networking;

public class MinionController : NetworkBehaviour {

    public Camera cam;

    public NavMeshAgent agent;

    Vector3 velocity;
    Vector3 bestGuessPosition;

    float ourLatency;
    float latencySmoothingFactor = 10;

    // Update is called once per frame
    void Update()
    {

        if (hasAuthority == false)
        {
            bestGuessPosition = bestGuessPosition + (velocity * Time.deltaTime);
            transform.position = Vector3.Lerp(transform.position, bestGuessPosition, Time.deltaTime * latencySmoothingFactor);
            return;
        }

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                agent.SetDestination(hit.point);
            }
        }
    }

    [Command]
    void CmdUpdateVelocity(Vector3 v, Vector3 p)
    {
        transform.position = p;
        velocity = v;

        RpcUpdateVelocity(velocity, transform.position);
    }

    [ClientRpc]
    void RpcUpdateVelocity(Vector3 v, Vector3 p)
    {

        if (hasAuthority)
        {
            return;
        }

        velocity = v;
        bestGuessPosition = p + (velocity * (ourLatency));
    }
}

```

# Answer
Your method for blending to the new updated position definitely looks dicey. While there are times when we want to use the pattern `value = lerp(value, target, sharpness)` for an exponential ease-out effect, interpolating positions in network replication is not one of them. At best, it will give us inconsistent movement speeds - fast whenever a new update comes in, slower as we approach the last estimate - resulting in a stuttery, glitchy appearance.

One common solution here is to use projective velocity blending.

Here's a quick overview of the technique from a presentation on vehicle replication in Watch\_Dogs 2:

The dark green arrow P0-\>V0 is the trajectory of the local pawn at the time of the update. The blue arrow P'0-\>V'0 is the trajectory according to the update packet. The orange arrow Vb represents a bending of the velocity into agreement with the new data, and the bright green squiggle P0-\>Pos is the interpolated position - initially agreeing with the old trajectory and gradually correcting into agreement with the update.

To do this we need to capture a bit more information when a new snapshot comes in:

```
struct Snapshot {
    readonly Vector3 positionOnArrival;
    readonly Vector3 velocityOnArrival;
    readonly Vector3 reportedPosition;
    readonly Vector3 reportedVelocity;
    // Using floats for time works well for games that can go for hours.
    // Switch to doubles or other formats for games expected to run persistently.
    readonly float arrivalTime;
    readonly float blendWindow;

    public Snapshot(Vector3 currentPosition, Vector3 currentVelocity,
                   Vector3 reportedPosition, Vector3 reportedVelocity,
                   float blendWindow) {
        arrivalTime = Time.time;
        positionOnArrival = currentPosition;
        velocityOnArrival = currentVelocity;
        this.reportedPosition = reportedPosition;
        this.reportedVelocity = reportedVelocity;
        this.blendWindow = blendWindow;
    }

    Vector3 EstimatePosition(float time, out Vector3 velocity) {
        float dT = time - arrivalTime;
        float blend = Mathf.Clamp01(dT/blendWindow);

        Vector3 velocity = Vector3.Lerp(velocityOnArrival, reportedVelocity, blend);

        Vector3 position = Vector3.Lerp(
                   positionOnArrival + velocity * dT,
                   reportedPosition + reportedVelocity * dT,
                   blend);

        return position;
    }
}

```

Note that the blending function transitions smoothly to dead reckoning from the last received update if we don't receive a new one within the expected window, so you don't need to handle the case of overdue messages separately.

Updating the snapshot:

```
Snapshot currentSnapshot;
// (Initialize this on Start/spawn with your spawn position)

[ClientRpc]
void RpcUpdateVelocity(Vector3 v, Vector3 p)
{
    if (hasAuthority)
        return;

    currentSnapshot = new Snapshot(
        transform.position, velocity,
        p, v,
        updatePacketPeriod // Expected time between new position/velocity reports.
    };
}

```

Using a snapshot:

```
if (hasAuthority == false)
{
    transform.position = currentSnapshot.EstimatePosition(Time.time, out velocity);
    return;
}

```

With the version above, the simulation is allowed to live one network update tick in the past. (ie. the reported position/velocity is considered accurate for "now" when it arrives, even though it was recorded & transmitted one transmission interval in the past)

You could optionally extrapolate the reported position into the future by (up to) your estimated latency, to reduce this time discrepancy.

The advantage of using the report as-is and living slightly in the past is that your replica will periodically reach position & velocity states that the original object actually occupied. By extrapolating, you lose this guarantee, and your replica might hover in the vicinity of the actual trajectory without hitting it exactly, though hopefully staying closer to the current position of the original on its own machine.
> 1 votes

---
Tags: unity, multiplayer, path-finding, interpolation
---


# Question
Title: Render to texture and gaussian blur texture problem
im using a lightmap to achieve a 2d lighting effect in OpenGL with dynamic shadows and to make them soft I use the gaussian blur. However I noticed one problem : When I use big blur ratio, it has some strange behaviour like in this picture:

It lookes like a problem with UV coordinates but I checked and everything should be fine. This is the shader:

```
#version 440

in vec4 fragmentColor;
in vec2 fragmentUV;

out vec4 color;

uniform sampler2D u_texture;
uniform float resolution;
uniform float radius;
uniform vec2 dir;

void main() {

    //this will be our RGBA sum
    vec4 sum = vec4(0.0);

    vec2 tc = fragmentUV;

    //the amount to blur, i.e. how far off center to sample from
    //1.0 -> blur by one pixel
    //2.0 -> blur by two pixels, etc.
    float blur = radius/resolution;

    //the direction of our blur
    //(1.0, 0.0) -> x-axis blur
    //(0.0, 1.0) -> y-axis blur
    float hstep = dir.x;
    float vstep = dir.y;

    //apply blurring, using a 9-tap filter with predefined gaussian weights

    sum += texture(u_texture, vec2(tc.x - 4.0*blur*hstep, tc.y - 4.0*blur*vstep)) * 0.0162162162;
    sum += texture(u_texture, vec2(tc.x - 3.0*blur*hstep, tc.y - 3.0*blur*vstep)) * 0.0540540541;
    sum += texture(u_texture, vec2(tc.x - 2.0*blur*hstep, tc.y - 2.0*blur*vstep)) * 0.1216216216;
    sum += texture(u_texture, vec2(tc.x - 1.0*blur*hstep, tc.y - 1.0*blur*vstep)) * 0.1945945946;

    sum += texture(u_texture, vec2(tc.x, tc.y)) * 0.2270270270;

    sum += texture(u_texture, vec2(tc.x + 1.0*blur*hstep, tc.y + 1.0*blur*vstep)) * 0.1945945946;
    sum += texture(u_texture, vec2(tc.x + 2.0*blur*hstep, tc.y + 2.0*blur*vstep)) * 0.1216216216;
    sum += texture(u_texture, vec2(tc.x + 3.0*blur*hstep, tc.y + 3.0*blur*vstep)) * 0.0540540541;
    sum += texture(u_texture, vec2(tc.x + 4.0*blur*hstep, tc.y + 4.0*blur*vstep)) * 0.0162162162;

    //discard alpha for our simple demo, multiply by vertex color and return
    color = 1. * vec4(sum.rgb, 1.0);
}

```

At the picture i used only the horizontal blur, for checking purposes. I create the lightmap in following order:

1. Render lights and ambient color to framebufferA
2. Render texture from framebufferA to framebufferB using horizontal blur
3. Render texture from framebufferB to framebufferA using vertical blur

I can post aditional code, however i dont know if the problem is with framebuffers. I tried it without the bluring and it works perfectly, it happens only when I use blur. Thanks in advance

**Edit1** I noticed that it is happening also on normal textures(not framebuffers textures). According to the comment, i´m including the code for texture wrapping:

```
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);

```

As for my UV coordinates, they were initialized and i didnt change them during runtime, they were set for normal rectangle.

I´ve tried the CLAMP\_TO\_EDGE wrap option (when i try CLAMP\_TO\_BORDER it disappears and i see just black texture), for normal textures it looked like it was solved but when I applied it also to the framebuffers texture it looked like this:

Here is my code for the framebuffer creation:

```
void Framebuffer::init(vec2 screenRes) {

        _screenRes = screenRes;

        //Generate the framebuffer ID
        if (_framebufferID != 0)
            glDeleteFramebuffers(1,&_framebufferID);

        if (_textureID != 0)
            glDeleteTextures(1, &_textureID);

        glGenFramebuffers(1, &_framebufferID);
        assert::checkWrongValue(_framebufferID, GL_FALSE, "Failed to generate framebuffer ID");

        //Bind it while we configure it
        glBindFramebuffer(GL_FRAMEBUFFER, _framebufferID);

        //Generation of the texture
        glGenTextures(1, &_textureID);

        assert::checkWrongValue(_textureID, GL_FALSE, "Failed to generate texture ID for framebuffer");

        //Bind it
        glBindTexture(GL_TEXTURE_2D, _textureID);

        //Actually create a space
        glTexImage2D(GL_TEXTURE_2D,
                    0,
                    GL_RGBA,
                    _screenRes.x,
                    _screenRes.y,
                    0,
                    GL_RGBA,
                    GL_UNSIGNED_BYTE,
                    NULL);

        //Wrapping
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        //Set it as a framebuffer texture
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _textureID, 0);

        //Creating render object
        glGenRenderbuffers(1, &_renderObjectID);
        assert::checkWrongValue(_renderObjectID, GL_FALSE, "Failed to generate render object ID for framebuffer");

        //Bind it
        glBindRenderbuffer(GL_RENDERBUFFER, _renderObjectID);

        //Configure it
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, _screenRes.x, _screenRes.y);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _renderObjectID);

        //Check the success
        assert::checkValue(glCheckFramebufferStatus(GL_FRAMEBUFFER), GL_FRAMEBUFFER_COMPLETE, "Failed to create a framebuffer");

        //Back to the default framebuffer
        glBindRenderbuffer(GL_RENDERBUFFER, 0);

        glBindFramebuffer(GL_FRAMEBUFFER, 0);
    }

```

# Answer
It looks to me like the problem is related to your texture wrapping. Originally you had `GL_TEXTURE_WRAP_REPEAT`, which is clearly wrong. You can even see in the original image on the right side, some of the light has bled over. I believe that `GL_TEXTURE_WRAP_CLAMP_TO_EDGE` is probably what you want. I think something else is going wrong with your second image which is causing the texture to repeat a single row of pixels vertically.

It seems odd that you're setting the `hstep` and `vstep` to 0 or 1. You're using `GL_TEXTURE_2D` which means that texture coordinates are in the range 0-1. You would need to make the step for a single pixel be 1/image width or 1/image height. Otherwise you're always getting the first or last pixel when you sample. That might explain the vertical problem you're seeing in the second image.
> 3 votes

---
Tags: opengl, glsl, lighting, lightmap
---


# Question
Title: Best way to store items with statistics in an mysql database?
Im currently working on an multiplayer game. Therefore using MySql for my game to store different data ( For example players, resources and so on ).

Lately i implemented items, players receive them by gathering resources for example, later they should also be able to craft them or even equip them if its a sword or an armor piece.

My problem is that due to my small experience with MySql, i have no clue how to add different statistics ( Equipable, Damage, Different Effects and so on ) to the items. Not every item should have them ( For example "Wood" shouldnt have statistics ). How should i modify my tables ? Any help would be appreciated ! Thanks !

My current table structure looks like this :

1. ItemCategories ( ID, Name )
2. ItemTypes ( ID, Name, ItemCategories\_ID )

---

For more information, how i actually manage/spawn those items in... here two more important tables.

This table contains resources ( For Example "Basic Tree" ) and the item it drops when gathered.

1. Resources( ID, Name, ItemTypes\_ID, gatheringTime, gatherAmount, spawnWeight)

This table contains the items in the players inventory.

2. PlayerInventory( ItemTypes\_ID, Player\_ID, amount)

# Answer
> 1 votes
A relational database is a great solution for persisting transactional data (data which changes during the game). But they are not necessarily that ideal for persisting static data (data which does not change during the game). An alternative solution you might want to consider for your item types is to store them all in a file which you load completely into memory when your gameserver starts up. This allows you to use a less structured format for it, like JSON or XML.

But if you are really determined to store your item properties in a relational database, then I would recommend to have one `ItemType` table which stores only the information used by all item types and then separate tables for each category with additional fields unique to items of that category. Like a table `Weapons ( ID, MinDamage, MaxDamage ... )`, a table `Armors( ID, Slot, Defense ... )` and so on.

Another option would be to have a table `ItemProperty(ID, Property, Value)` where `Property` is the name of the respective property. So when you want the attack of the item #737 you would do a query like `SELECT Value FROM ItemProperty WHERE ID = 737 AND Property = 'Attack';`. This schema allows you to add any arbitrary item properties to any item without having to alter any tables. But it's neither very type-safe (you can accidentally add properties which are meaningless) and it is not very query-friendly either.

---
Tags: unity, architecture, networking, databases, mysql
---


title: Camera not in sync with player

text:
# Question
Title: Camera not in sync with player
I am currently working on a game in XNA and MonoGame. This game is supposed to be a port of KidsCanCode's tutorial series of creating tile-based games in Python. Here is a link to one of the videos in the series I'm talking about: https://www.youtube.com/watch?v=3zV2ewk-IGU&index=4&list=PLsk-HSGFjnaGQq7ybM8Lgkh5EMxUWPm2i

My issue is that my player and camera don't move like how KidsCanCode's player and camera move (you can see KidsCanCode's player and camera movement by clicking on the link above). My camera and player are out of sync. The player can easily go outside of the camera.

Here is the camera code:

```
public class Camera
{
    public float Rotation { get; private set; } = 0;
    //private Matrix OldTransform;
    //public Vector2 Position { get; private set; }
    public float Zoom { get; private set; } = 1f;

    public int ScreenWidth { get; set; }
    public int ScreenHeight { get; set; }

    public int MapWidth { get; set; }
    public int MapHeight { get; set; }

    private Vector2 Position;

    const float Velocity = 280f;

    public void GetTransformation(out Matrix transform)
    {
        float x = -Position.X;
        float y = -Position.Y;

        transform =
      Matrix.CreateTranslation(new Vector3(x, y, 0));

    }

    public Camera(int screenWidth, int screenHeight, int mapWidth, int mapHeight)
    {
        ScreenWidth = screenWidth;
        ScreenHeight = screenHeight;

        MapWidth = mapWidth;
        MapHeight = mapHeight;
    }

    public void ApplyPositionFromSprite(Sprite sprite)
    {
        //Camera is supposed to center on sprite

        //Camera is always supposed to be ahead of player unless player is close to the edge

        float x = sprite.Position.X;
        float y = sprite.Position.Y;

        x = Math.Max(x, 0);
        y = Math.Max(y, 0);

        x = Math.Min(x, MapWidth - ScreenWidth);
        y = Math.Min(y, MapHeight - ScreenHeight);

        this.Position = new Vector2(x, y);
   }

```

Can someone tell me what's wrong with my code? Here is a link to the GitHub page.

# Answer
> 1 votes
I found the answer to my problem was that I didn't apply the matrix transform of the camera to my player sprite. It works as it should now.

Also, as a side note, if you're rendering the sprite with an overload of SpriteBatch.Draw that accepts a Rectangle instead of a Vector2, then you should use an overload that accepts a Vector2 because of jittering that may occur due to rounding a float to an int.

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


title: How can I generate Worms-style terrain?

text:
# Question
Title: How can I generate Worms-style terrain?
I'm working on a Worms-styled game and want to generate some terrain procedurally. I've previously done a lot of terrain generation using perlin noise, and this is what I started out using for this game. The only problem with it is that it's too simple and boring, giving me some hills but not the complexity I want. I'd like to have features like caves and hanging mountains and I don't mind floating islands and such. Something like this, but even crazier would be ok:

I thought of first generating the terrain using classic perlin noise, then just removing parts to create caves and what not, but I'm having trouble guiding the removal of those parts. Are there any alternatives to generating such a terrain?

# Answer
> 52 votes
I'd suggest you start with 2D Perlin-noise. Something like this:

Then apply a threshold on the image, so that you get several isolated islands, as shown here:

I chose a threshold of 0.04, everything above the threshold would be colored blue. The rest remaining black. Then after that, it's time to determine which "islands" to keep and which to throw away.

A possible approach would be to run through the image from left to right at various heights and select intersecting "islands" given a certain probability. In the example picture, the lowest line has a probability of 100%, so every island it crosses will be selected (filled white). The second line has a probability of 50% and the topmost line has a probability of 10%.

Once you have your islands marked like that, you can close the gaps in between by applying a morphological operation (*dilate*)

And there's a possible landscape.

The "granularity" of the noise is going to determine how small the details in your world are going to be. So it's probably best to experiment with these values.

Also where and with what probabilities your "selecting-lines" are positioned, the result is going to be vastly different. If you have a line near the top of the image with high probability to "select" an island, then you can build some sort of cave-landscape, etc.

# Answer
> 6 votes
I'd start with a perlin noise, filtered carefully. You'd end with something like in the picture attached to the question, with floating islands. Juste remove the floating islands afterwards using a counting algorithm like the ones discussed here

# Answer
> 4 votes
I actually implemented this starting from bummzack excellent answer.

Here are the steps I ended up with:

1. Generate an image with Perlin noise
2. Floodfill where you want some terrain
3. Dilation + erosion to remove the hollows that are too small
4. Remove the remaining background regions inside the terrain
5. Antialiasing

And this is an example of the result:

I wrote a detailed article about the whole process here and the code(JavaScript) is open source, check it out if you want something ready to use ;)

---
Tags: algorithm, procedural-generation, perlin-noise
---


# Question
Title: Random points spread like old TV static in a polygon OpenGL
OpenGL version 3.1

Have to draw around 10000 randomly placed and colored points inside a rectangle to appear like old TV static but colored as shown in the image below.

Right now the code draws a solid fill even with plotting one point inside the rectangle.

```
void Question1(int width, int height, int gap)
   {
   //    SCREEN_WIDTH   = width;
   //    SCREEN_HEIGHT  = height;
   srand (time(NULL));

   //    float r = rand() / (RAND_MAX + 1.0);
   //    float g = rand() / (RAND_MAX + 1.0);
   //    float b = rand() / (RAND_MAX + 1.0);

   glBegin(GL_POLYGON);{
      glVertex2f(0 + gap, 0 + gap);
      glVertex2f(width - gap, 0 + gap);
      glVertex2f(width - gap, height - gap);
      glVertex2f(0 + gap, height - gap);
   }
   glEnd();
   glPointSize(1.0f);
   glBegin(GL_POINT);{
      for (int i=0; i < 1; i++){
        glColor3f(rand() / (RAND_MAX + 1.0), rand() / (RAND_MAX + 1.0), rand() / (RAND_MAX + 1.0));
        glVertex2i(rand(), rand());
    }
}
glFlush();
glEnd();
}

```

How do I fix my current code? Also, please give feedback on bad practices used in my code.

My output is currently a solid fill inside my rectangle with random color change.

# Answer
There are multiple mistakes as @kromster pointed. I am not going to go on other mistakes, rather i'll tell you what is the best way I think.

In order to make it work, you have to do basically these things

1) set the `gap` to something

2) begin drawing the rectangle using `GL_LINE_LOOP`(just because, it would be easy with that)

3) then you just need 2 loops, one draws towards x-axis and other draws towards y-axis

that's it you're done. And this is how you would implement it.

```
//Gap is the distance from the sides
int gap = 100;

// Rectangle
glBegin(GL_LINE_LOOP);
    //glColor3f(1, 1, 1);
    //leftmost
    glVertex2d(SCREEN_WIDTH - (SCREEN_WIDTH-gap), SCREEN_HEIGHT - (SCREEN_HEIGHT-gap));
    //top
    glVertex2d(SCREEN_WIDTH-gap, SCREEN_HEIGHT - (SCREEN_HEIGHT-gap));
    //rightmost
    glVertex2d(SCREEN_WIDTH-gap, SCREEN_HEIGHT - gap);
    //bottom
    glVertex2d(SCREEN_WIDTH - (SCREEN_WIDTH-gap), SCREEN_HEIGHT - gap);
glEnd();

// drawing circles
glPointSize(4);
glBegin(GL_POINTS);
     //random colors

    //points inside the rectangle
    for(int i=0; i<SCREEN_HEIGHT - (2*gap); i++){     // Y-axis

        for(int j=0; j< SCREEN_WIDTH - (2*gap); j++ ){   // X-axis
                glColor3ub(rand()%255 + 1, rand()%255 + 1, rand()%255 + 1);
                glVertex2d((SCREEN_WIDTH - (SCREEN_WIDTH-gap)) + j, ((SCREEN_HEIGHT-(SCREEN_HEIGHT - gap)) + i));
        }
    }
    //glVertex2d(20, 50);
glEnd();

```
> 0 votes

# Answer
Okay, there is a number of mistakes:

1. The error in `glVertex2i(rand(), rand())` \- typical `rand()` returns a single number within `0.0..1.0` range. When you pass it to a function taking `i` (integers) they are way off and don't show up on the screen.

Use the `glVertex2i(Round(gap + rand() * width), Round(gap + rand() * height))` or `glVertex2f(gap + rand() * width, gap + rand() * height)`
2. The `for (int i=0; i < 1; i++)` loop looks odd to - you do draw only one point?
3. `glBegin(GL_POINT);` is wrong too. Look up the correct constant name ;-)
4. `glFlush(); glEnd();` are misplaced too.
> 0 votes

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


# Question
Title: lerp vector2 to target vector2 at constant rate
I am struggling to figure out how to lerp one vector2 to a target vector2 at a constant rate. I can do it as a percentage of the total x, y distance like so:

```
lerp(start, current, target, pctSpeed) {
  return current + pctSpeed * (target - start);
}

```

calling it as such:

```
speed = .02

// game loop
Update(timestamp) {
  x = lerp(startX, x, targetX, speed)
  y = lerp(startY, y, targetY, speed)
  resultingVector2 = {x: x, y: y}
}

```

which correctly lerps x and y by 2% of the distance between the start and target vector2 each frame. How do you do this at a constant rate, i.e instead of 2% a value of 2 or .2 or 3, etc. Thanks

# Answer
> 0 votes
I'd recommend not redefining a common method like Lerp. Linear interpolation has a standard definition:

```
Lerp(a, b, t) {
    return (1-t) * a + t * b;
}

```

If you redefine it to describe any old movement along a line, your code will become very hard to understand for anyone who's used to this standard.

Instead, if you want to move at a constant speed, define a new method for that:

```
Approach(current, target, maxStepDistance) {
    toTarget = target - current;

    // Clamp our travel so we never move further than our allowed step.
    squareMagnitude = dot(toTarget, toTarget);
    if(squareMagnitude > maxStepDistance * maxStepDistance) {
        toTarget *= maxStepDistance/sqrt(squareMagnitude)
    }

    return current + toTarget;
}

```

Which you can use like so:

```
Update(timestamp) {
    // Make sure you're using a high precision source for your timestamp
    // when calculating deltaTime - a float will lose precision after hours of play.
    deltaTime = timeStamp - lastFrameTimestamp;
    lastFrameTimestamp = timestamp;

    // Multiply speed by the timestep to get the distance travelled this frame.
    current = Approach(current, target, speed * deltaTime);
}

```

---
Tags: mathematics, lerp
---


# Question
Title: How to get tile rotation from TiledSharp and convert it to XNA/MonoGame
I am currently working on a game using XNA and Tiled. I use Tiled to create my maps and load them using TiledSharp. Some of my maps have tiles that are rotated by using one or more of the left rotate, right rotate, horizontal flip, vertical flip options in combination.

In the tiled documentation, it shows there are certain ways to find out if an object is horizontally, vertically, or diagonally flipped. TiledSharp tells me this information. However, I don't know what to do if a tile is diagonally flipped. How many degrees should I rotate the tile (in multiples of 90 degrees)?

# Answer
A diagonal flip in Tiled essentially swaps the X and Y axis of the tile (it flips along the line x=y, also called a transpose). For square tiles, this is easy to implement by swapping the corner vertices of the quad.

If you need to use flipping and rotation to implement the rendering then a diagonal flip is the same as a 90-degree rotation clockwise followed by a horizontal flip (or a 90-degree rotation counterclockwise followed by a vertical flip).
> 0 votes

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


title: Normals transformation problem

text:
# Question
Title: Normals transformation problem
I am working on my first Direct3D game and even after many days of searching Internet and experimenting I can't figure out how to work with normals properly. As a result, the lights are not working correctly. The scene is shown on the below picture.

The camera is always pointed into center of the scene (0,0,0) and rotates around it. The scene itself is static, only the vehicles can move forward or backward. The light source is a static point light. So I would presume the diffuse lighting level of the objects must be static during camera rotation. But it isn't. When I rotate the camera, the lighting levels of particular parts of objects are changing (even if I disable the specular part of light). Also the diffuse light on the objects is not correct with respect to the light position. So I would say I am doing something completely wrong with the normals. I am trying to figure it out for 1 week but with no success. So I am kindly asking you for any help which can push me forward.

I have found (e.g. here), that I must multiply my normal vectors with transposed inverse matrix of the original world matrix applied to my vertices, because my models are scaled. But this is not helping. Below are relevant parts of my code.

Render scene method:

```
struct CBUFFER {
    DirectX::XMMATRIX world;
    DirectX::XMMATRIX rotation;
    DirectX::XMMATRIX invTrWorld;
    DirectX::XMVECTOR cameraPosition;
    DirectX::XMVECTOR lightVector;
    DirectX::XMVECTOR diffuseColor;
    DirectX::XMVECTOR ambientColor;
    float specularPower;
    DirectX::XMVECTOR specularColor;
};

void Game::Render() {
    CBUFFER cBuffer;
    XMMATRIX matView, matPerspective;
    XMVECTOR camPosition = XMVectorSet(0.0f, 4.0f, -10.0f, 0.0f);
    camPosition = XMVector4Transform(camPosition, _rotation); // _rotation - defines the angle of the camera

    //Set the View matrix
    matView = XMMatrixLookAtLH(
        camPosition,                          // the camera position (rotating around the center of the board)
        XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f),  // the look-at position
        XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)   // the up direction
    );
    cBuffer.cameraPosition = camPosition;

    // create a projection matrix
    matPerspective = XMMatrixPerspectiveFovLH((FLOAT)XMConvertToRadians(45), (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, 1.0f, 100.0f);

    cBuffer.lightVector = XMVectorSet(-10.0f, 10.0f, 10.0f, 1.0f);
    cBuffer.diffuseColor = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f);
    cBuffer.ambientColor = XMVectorSet(_ambientColorIntensity, _ambientColorIntensity, _ambientColorIntensity, 1.0f);
    cBuffer.specularColor = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f);

    // clear the back buffer to a deep blue
    FLOAT bgColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
    _d3d->GetDeviceContext()->ClearRenderTargetView(_d3d->GetBackBuffer(), bgColor);

    // clear the depth buffer
    _d3d->GetDeviceContext()->ClearDepthStencilView(_d3d->GetZBuffer(), D3D11_CLEAR_DEPTH, 1.0f, 0);

    // select which vertex buffer to display
    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    _d3d->GetDeviceContext()->IASetVertexBuffers(0, 1, _d3d->GetVBufferAddr(), &stride, &offset);
    _d3d->GetDeviceContext()->IASetIndexBuffer(_d3d->GetIBuffer(), DXGI_FORMAT_R32_UINT, 0);

    // select which primtive type we are using
    _d3d->GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
    _d3d->GetDeviceContext()->IASetInputLayout(_d3d->GetLayout());

    // select Rasterizer and Sampler configuration
    _d3d->GetDeviceContext()->RSSetState(_d3d->GetRState());
    _d3d->GetDeviceContext()->PSSetSamplers(0, 1, _d3d->GetSStateAddr());

    // Draw model instances - Non-vehicle objects
    for (auto it = _minstances.begin(); it != _minstances.end(); it++) {
        ModelInstance mi = it->second;

        // Store instance transformation into constant buffer
        XMMATRIX worldMatrix = mi.GetTransformation() * _worldOffset;
        worldMatrix *= matView * matPerspective;
        XMMATRIX trInvWorld = XMMatrixInverse(nullptr, XMMatrixTranspose(worldMatrix));
        cBuffer.world = worldMatrix;
        cBuffer.invTrWorld = invTrWorld;
        // TODO: obtain specularPower from model
        cBuffer.specularPower = 1.0f;
        // Send constant buffer
        _d3d->GetDeviceContext()->UpdateSubresource(_d3d->GetCBuffer(), 0, 0, &cBuffer, 0, 0);

        for (auto i : mi.GetModel().GetMeshEntries()) {
            // select texture
            _d3d->GetDeviceContext()->PSSetShaderResources(0, 1, &i._pTexture);
            _d3d->GetDeviceContext()->DrawIndexed(i._numIndices, i._baseIndex, i._baseVertex);
        }
    }

    // Draw vehicles
    for (auto it = _vehicles.begin(); it != _vehicles.end(); it++) {
        Vehicle mi = it->second;
        if (mi.IsHidden()) {
            continue;
        }
        // Store vehicle transformation into constant buffer
        XMMATRIX worldMatrix = mi.GetTransformation() * _worldOffset;
        worldMatrix *= matView * matPerspective;
        XMMATRIX trInvWorld = XMMatrixInverse(nullptr, XMMatrixTranspose(worldMatrix));
        cBuffer.world = worldMatrix;
        cBuffer.invTrWorld = invTrWorld;
        // Store vehicle color into constant buffer
        XMVECTOR vehicleColor = mi.GetColor();
        cBuffer.diffuseColor = vehicleColor;
        cBuffer.specularColor = vehicleColor;
        float glowIntensity = _ambientColorIntensity + mi.GetGlowLevel();
        cBuffer.ambientColor = XMVectorSet(vehicleColor.m128_f32[0] * glowIntensity,
            vehicleColor.m128_f32[1] * glowIntensity,
            vehicleColor.m128_f32[2] * glowIntensity,
            vehicleColor.m128_f32[3] * glowIntensity);
        // TODO: obtain specularPower from model
        cBuffer.specularPower = 32.0f;
        // Send constant buffer
        _d3d->GetDeviceContext()->UpdateSubresource(_d3d->GetCBuffer(), 0, 0, &cBuffer, 0, 0);

        for (auto i : mi.GetModel().GetMeshEntries()) {
            // select texture
            _d3d->GetDeviceContext()->PSSetShaderResources(0, 1, &i._pTexture);
            _d3d->GetDeviceContext()->DrawIndexed(i._numIndices, i._baseIndex, i._baseVertex);
        }
    }

    // print FPS info
    _d2d->PrintInfo();

    // switch the back buffer and the front buffer
    _d3d->GetSwapChain()->Present(0, 0);
}

```

HLSL code:

```
cbuffer ConstantBuffer {
    matrix world;
    matrix rotation;
    matrix trinvworld;
    float4 camposition; // position of the camera
    float4 lightpos; // the diffuse light's vector
    float4 diffusecol; // the diffuse light's color
    float4 ambientcol; // the ambient light's color
    float specularpow; // the specular light's power
    float4 specularcol; // the specular light's color
}

Texture2D Texture;
SamplerState ss;

struct VOut {
    float4 color : COLOR;
    float2 texcoord : TEXCOORD0;
    float4 position : SV_POSITION;
};

VOut VShader(float4 position : POSITION, float3 normal : NORMAL, float2 texcoord : TEXCOORD) {
    VOut output;

    // VERTEX POSITION TRANSFORMATION
    // Calculate the position of the vertex in the world
    float4 worldposition4 = mul(world, position);
//  float3 worldposition = mul((float3x3)world, position.xyz);
    output.position = worldposition4

    // AMBIENT LIGHT & NORMAL TRANSFORMATION
    float4 color = ambientcol;
    float3 norm = normalize(mul((float3x3)trinvworld, normal));
    //float3 norm = normalize(mul((float3x3)world, normal));

    // DIFFUSE LIGHT
//  float3 lightpos3 = lightpos.xyz;
//  float3 lightvec = normalize(lightpos3 - worldposition);
    float4 lightvec = normalize(lightpos - worldposition4);
    lightvec = -lightvec;
    float lightintensity = saturate(dot(norm, lightvec)); // calculate the amount of light

    // SPECULAR LIGHT
    //float3 camposition3 = camposition.xyz;
    float3 camvec = normalize(camposition - worldposition4);
    camvec = -camvec;
    float3 reflectedlight = reflect(lightvec, norm);

    float specularfactor = saturate(dot(reflectedlight, camvec));
    float dampedfactor = pow(specularfactor, specularpow);
    float4 finalspecular = dampedfactor * specularcol;

    // COMBINE ALL LIGTHS TOGETHER
    color += diffusecol * lightintensity + finalspecular;
    output.color = saturate(color);

    // TEXTURE
    output.texcoord = texcoord;

    return output;
}

float4 PShader(float4 color : COLOR, float2 texcoord : TEXCOORD) : SV_TARGET
{
    return color *Texture.Sample(ss, texcoord);
}

```

The normals are part of loaded models. The models are loaded using Assimp Importer:

```
Model::Model(const char* pFile, ID3D11Device* dev) {
    const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);
    _pScene = _imp.ReadFile(pFile, aiProcess_FlipUVs | aiProcess_FixInfacingNormals | aiProcess_MakeLeftHanded |
        aiProcess_GenSmoothNormals | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType);
    if (!_pScene) {
    }else {
        if (_pScene->mNumMeshes < 1) {
        }
        else {
            // Process all meshes
            for (unsigned int m = 0; m < _pScene->mNumMeshes; m++) {
                _pMesh = _pScene->mMeshes[m];
                MeshEntry me;
                me._baseVertex = Model::_objectVertices.size();
                me._baseIndex = _objectIndices.size();
                if (_pMesh) {
                    // Load vertices
                    Model::_objectVertices.reserve(Model::_objectVertices.size() + _pMesh->mNumVertices);
                    for (unsigned int i = 0; i < _pMesh->mNumVertices; i++) {
                        const aiVector3D* pPos = &(_pMesh->mVertices[i]);
                        const aiVector3D* pNormal = (_pMesh->mNormals != nullptr) ? &(_pMesh->mNormals[i]) : &Zero3D;
                        const aiVector3D* pTexCoord = (_pMesh->HasTextureCoords(0)) ? &(_pMesh->mTextureCoords[0][i]) : &Zero3D;
                        VERTEX v;
                        v.pos.x = pPos->x; v.pos.y = pPos->y; v.pos.z = pPos->z;
                        v.normal.x = pNormal->x; v.normal.y = pNormal->y; v.normal.z = pNormal->z;
                        //v.normal.x = 1.0f; v.normal.y = 0.0f; v.normal.z = 0.0f;
                        v.textCoord.x = pTexCoord->x; v.textCoord.y = pTexCoord->y;
                        Model::_objectVertices.push_back(v);
                    }

                    // Load indices
                    _objectIndices.reserve(_objectIndices.size() + (_pMesh->mNumFaces * 3));
                    for (unsigned int i = 0; i < _pMesh->mNumFaces; i++) {
                        if (_pMesh->mFaces[i].mNumIndices == 3) {
                            _objectIndices.push_back(_pMesh->mFaces[i].mIndices[0]);
                            _objectIndices.push_back(_pMesh->mFaces[i].mIndices[1]);
                            _objectIndices.push_back(_pMesh->mFaces[i].mIndices[2]);
                            me._numIndices += 3;
                        }
                    }

                    // Process material of the mesh
                    if (_pScene->HasMaterials()) {
                        aiMaterial* material = _pScene->mMaterials[_pMesh->mMaterialIndex];
                        aiString aiTextureFile;
                        me._materialIndex = _pMesh->mMaterialIndex;
                        // Load texture file
                        if (material->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
                            material->GetTexture(aiTextureType_DIFFUSE, 0, &aiTextureFile);
                            // Convert aiString to LPWSTR
                            size_t size = strlen(aiTextureFile.C_Str()) + 1; // plus null
                            wchar_t* wcTextureFile = new wchar_t[size];
                            std::shared_ptr<wchar_t> sp(wcTextureFile, std::default_delete<wchar_t[]>());
                            size_t outSize;
                            mbstowcs_s(&outSize, wcTextureFile, size, aiTextureFile.C_Str(), size - 1);
                            LPWSTR textureFile = wcTextureFile;
                            CreateWICTextureFromFile(dev, nullptr, textureFile, nullptr, &(me._pTexture), 0);
                            if (me._pTexture == nullptr) {
                                CreateDDSTextureFromFile(dev, nullptr, textureFile, nullptr, &(me._pTexture), 0);
                            }
                        }
                    }
                    // If no texture found, use the default one
                    if (me._pTexture == nullptr) {
                        CreateWICTextureFromFile(dev, nullptr, L"models/default.jpg", nullptr, &(me._pTexture), 0);
                    }
                    _entries.push_back(me);
                }
            }
        }
    }
}

```

And the D3D scene is initialized by D3D class.

D3D.h

```
#pragma once

#include <d3d11.h>
#include <directxmath.h>
#include <vector>
#include "RushHour.h"
#include "D3DSupplementary.h"

class D3D {
public:
    D3D() = delete;
    D3D(HWND hWnd);
    D3D(D3D&&) = default;
    D3D& operator= (D3D&&) = default;
    ~D3D();
    // D3D must not be copied, as it would release all elements after copy
    D3D(const D3D&) = delete;
    D3D& operator=(const D3D&) = delete;

    void CreateVertexBuffer(std::vector<VERTEX> OurVertices);
    void CreateIndexBuffer(std::vector<UINT> OurIndices);

    IDXGISwapChain* GetSwapChain() const { return _swapChain; };
    IDXGIDevice* GetDXGIDevice() const { return _dxgiDevice; }
    ID3D11Device* GetDevice() const { return _dev; }
    ID3D11DeviceContext* GetDeviceContext() const { return _devCon; }
    ID3D11RenderTargetView* GetBackBuffer() const { return _bBuffer; }
    ID3D11DepthStencilView* GetZBuffer() const { return _zBuffer; }
    ID3D11Buffer* GetCBuffer() const { return _cBuffer; }
    ID3D11Buffer* GetVBuffer() const { return _vBuffer; }
    ID3D11Buffer** GetVBufferAddr() { return &(_vBuffer); }
    ID3D11Buffer* GetIBuffer() const { return _iBuffer; }
    ID3D11InputLayout* GetLayout() const { return _layout; }
    ID3D11RasterizerState* GetRState() const { return _rs;  }
    ID3D11SamplerState* GetSState() const { return _ss; }
    ID3D11SamplerState** GetSStateAddr() { return &(_ss); }

private:
    IDXGISwapChain* _swapChain;             // swap chain interface
    IDXGIDevice* _dxgiDevice;
    ID3D11Device* _dev;                     // device interface
    ID3D11DeviceContext* _devCon;           // device context
    ID3D11VertexShader* _vs;                // vertex shader
    ID3D11PixelShader* _ps;                 // pixel shader
    ID3D11InputLayout* _layout;             // layout
    ID3D11RenderTargetView* _bBuffer;       // backbuffer
    ID3D11DepthStencilView* _zBuffer;       // depth buffer
    ID3D11Buffer* _cBuffer;                 // constant buffer
    ID3D11Buffer* _vBuffer;                 // vertex buffer
    ID3D11Buffer* _iBuffer;                 // index buffer

    // State objects
    ID3D11RasterizerState* _rs;            // the default rasterizer state
    ID3D11SamplerState* _ss;               // sampler state

    void CreateDevice(HWND hWnd);
    void CreateDepthBuffer();
    void CreateRenderTarget();
    void SetViewport();
    void LoadShaders();
    void CreateConstantBuffer();
    void InitRasterizer();
    void InitSampler();
};

```

D3D.cpp:

```
#include "stdafx.h"
#include <d3dcompiler.h>
#include "CommonException.h"
#include "D3D.h"

D3D::D3D(HWND hWnd) {
    // this function initializes and prepares Direct3D for use
    CreateDevice(hWnd);
    CreateDepthBuffer();
    CreateRenderTarget();
    SetViewport();
    LoadShaders();
    CreateConstantBuffer();
    InitRasterizer();
    InitSampler();
}

D3D::~D3D() {
    // switch to windowed mode
    if (_swapChain) _swapChain->SetFullscreenState(FALSE, NULL);

    // release all the stuff
    if (_zBuffer) _zBuffer->Release();
    if (_layout) _layout->Release();
    if (_vs) _vs->Release();
    if (_ps) _ps->Release();
    if (_vBuffer) _vBuffer->Release();
    if (_iBuffer) _iBuffer->Release();
    if (_cBuffer) _cBuffer->Release();
    if (_swapChain) _swapChain->Release();
    if (_bBuffer) _bBuffer->Release();
    if (_rs) _rs->Release();
    if (_ss) _ss->Release();
    if (_dev) _dev->Release();
    if (_devCon) _devCon->Release();
}

void D3D::CreateDevice(HWND hWnd) {
    DXGI_SWAP_CHAIN_DESC scd;
    ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

    // fill the swap chain description struct
    scd.BufferDesc.Width = SCREEN_WIDTH;                    // set the back buffer width
    scd.BufferDesc.Height = SCREEN_HEIGHT;                  // set the back buffer height
    scd.BufferCount = 1;                                    // one back buffer
    scd.BufferDesc.RefreshRate.Numerator = 0;                                   // refresh rate: 0 -> do not care
    scd.BufferDesc.RefreshRate.Denominator = 1;
    scd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;     // use 32-bit color
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;      // how swap chain is to be used
    scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;     // unspecified scan line ordering
    scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;                     // unspecified scaling
    scd.OutputWindow = hWnd;                                // the window to be used
    scd.SampleDesc.Count = 4;                               // how many multisamples
    scd.SampleDesc.Quality = 0;
    scd.Windowed = RUNINWINDOW;                             // windowed/full-screen mode
    scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;     // allow full-screen switching by Alt-Enter

    D3D_FEATURE_LEVEL featureLevel;

    // create a device, device context and swap chain using the information in the scd struct
    if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL,
        D3D11_CREATE_DEVICE_BGRA_SUPPORT /* This flag is necessary for compatibility with Direct2D */,
        NULL, NULL, D3D11_SDK_VERSION, &scd, &_swapChain, &_dev, &featureLevel, &_devCon))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create the Direct3D device!");
    } else if (featureLevel < D3D_FEATURE_LEVEL_11_0) {
        throw CommonException((LPWSTR)L"Critical error: You need DirectX 11.0 or higher to run this game!");
    }

    if (FAILED(_dev->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<LPVOID*>(&_dxgiDevice)))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to get Direct3D DXGI device!");
    }
}

void D3D::CreateDepthBuffer() {
    // create the depth buffer texture
    D3D11_TEXTURE2D_DESC texd;
    ZeroMemory(&texd, sizeof(texd));
    texd.Width = SCREEN_WIDTH;
    texd.Height = SCREEN_HEIGHT;
    texd.ArraySize = 1;
    texd.MipLevels = 1;
    texd.SampleDesc.Count = 4;
    texd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    texd.Usage = D3D11_USAGE_DEFAULT;
    texd.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    ID3D11Texture2D *pDepthBuffer;
    if (FAILED(_dev->CreateTexture2D(&texd, NULL, &pDepthBuffer))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer texture!");
    }

    // create the depth buffer
    D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
    ZeroMemory(&dsvd, sizeof(dsvd));
    //dsvd.Format = DXGI_FORMAT_D32_FLOAT;
    dsvd.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
    if (FAILED(_dev->CreateDepthStencilView(pDepthBuffer, &dsvd, &_zBuffer))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer!");
    }
    pDepthBuffer->Release();
}

void D3D::CreateRenderTarget() {
    // create backbuffer and render target
    ID3D11Texture2D *pBackBuffer;
    if (FAILED(_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&pBackBuffer)))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to get Direct3D depth buffer!");
    }
    if (FAILED(_dev->CreateRenderTargetView(pBackBuffer, NULL, &_bBuffer))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D depth buffer!");
    }
    pBackBuffer->Release();
    _devCon->OMSetRenderTargets(1, &_bBuffer, _zBuffer);
}

void D3D::SetViewport() {
    // set the viewport
    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = SCREEN_WIDTH;
    viewport.Height = SCREEN_HEIGHT;
    viewport.MinDepth = 0;
    viewport.MaxDepth = 1;

    _devCon->RSSetViewports(1, &viewport);
}

void D3D::LoadShaders() {
    // load and compile vertex and pixel shader
    ID3D10Blob *VS, *PS;
    D3DCompileFromFile(L"shaders.shader", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "VShader", "vs_4_0", 0, 0, &VS, NULL);
    D3DCompileFromFile(L"shaders.shader", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "PShader", "ps_4_0", 0, 0, &PS, NULL);
    if (FAILED(_dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &_vs))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D vertex shader!");
    }
    if (FAILED(_dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &_ps))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D pixel shader!");
    }
    _devCon->VSSetShader(_vs, 0, 0);
    _devCon->PSSetShader(_ps, 0, 0);

    // create the input layout object
    D3D11_INPUT_ELEMENT_DESC ied[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    };

    if (FAILED(_dev->CreateInputLayout(ied, 3, VS->GetBufferPointer(), VS->GetBufferSize(), &_layout))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D input layout!");
    }
    _devCon->IASetInputLayout(_layout);
}

void D3D::CreateConstantBuffer() {
    // constant buffer
    D3D11_BUFFER_DESC bd;
    ZeroMemory(&bd, sizeof(bd));
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof(CBUFFER);
    bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    if (FAILED(_dev->CreateBuffer(&bd, NULL, &_cBuffer))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D constant buffer!");
    }
    _devCon->VSSetConstantBuffers(0, 1, &_cBuffer);
}

void D3D::CreateVertexBuffer(std::vector<VERTEX> OurVertices) {
    // create the vertex buffer
    D3D11_BUFFER_DESC bd;
    ZeroMemory(&bd, sizeof(bd));
    bd.Usage = D3D11_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof(VERTEX) * OurVertices.size();
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    if (FAILED(_dev->CreateBuffer(&bd, NULL, &_vBuffer))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D vertex buffer!");
    }

    // copy the vertices into the buffer
    D3D11_MAPPED_SUBRESOURCE ms;
    if (FAILED(_devCon->Map(_vBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to map Direct3D vertex buffer!");
    }
    memcpy(ms.pData, OurVertices.data(), sizeof(VERTEX) * OurVertices.size());
    _devCon->Unmap(_vBuffer, NULL);
}

void D3D::CreateIndexBuffer(std::vector<UINT> OurIndices) {
    // create the index buffer
    D3D11_BUFFER_DESC bd;
    ZeroMemory(&bd, sizeof(bd));
    bd.Usage = D3D11_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof(UINT) * OurIndices.size();
    bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    bd.MiscFlags = 0;
    if (FAILED(_dev->CreateBuffer(&bd, NULL, &_iBuffer))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to create Direct3D index buffer!");
    }

    // copy the indices into the buffer
    D3D11_MAPPED_SUBRESOURCE ms;
    if (FAILED(_devCon->Map(_iBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to map Direct3D index buffer!");
    }
    memcpy(ms.pData, OurIndices.data(), sizeof(UINT) * OurIndices.size());
    _devCon->Unmap(_iBuffer, NULL);
}

void D3D::InitRasterizer() {
    D3D11_RASTERIZER_DESC rd;
    rd.FillMode = D3D11_FILL_SOLID;
    rd.CullMode = D3D11_CULL_BACK;
    rd.FrontCounterClockwise = TRUE;
    rd.DepthClipEnable = TRUE;
    rd.ScissorEnable = FALSE;
    rd.AntialiasedLineEnable = FALSE;
    rd.MultisampleEnable = FALSE;
    rd.DepthBias = 0;
    rd.DepthBiasClamp = 0.0f;
    rd.SlopeScaledDepthBias = 0.0f;
    if (FAILED(_dev->CreateRasterizerState(&rd, &_rs))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to creat Direct3D rasterizer state!");
    }
}

void D3D::InitSampler() {
    D3D11_SAMPLER_DESC sd;
    ZeroMemory(&sd, sizeof(sd));
    sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    sd.MaxAnisotropy = 16;
    sd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sd.BorderColor[0] = 0.0f;
    sd.BorderColor[1] = 0.0f;
    sd.BorderColor[2] = 0.0f;
    sd.BorderColor[3] = 0.0f;
    sd.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sd.MinLOD = 0.0f;
    sd.MaxLOD = FLT_MAX;
    sd.MipLODBias = 0.0f;
    if (FAILED(_dev->CreateSamplerState(&sd, &_ss))) {
        throw CommonException((LPWSTR)L"Critical error: Unable to creat Direct3D sampler state!");
    }
}

```

I hope I have provided all important parts of the code. Just for case, the complete code can be found here.

Another thing I don't understand in my app might not be connected with my problem at all, but maybe it is connected so I rather mention it here:

Transformation matrices are ok to be stored into constant buffer in original form (== not transposed). As far as I understood from articles I found (e.g. here) the CPU stores arrays in row-major format while HLSL needs them in column-major format so I must transpose all matrices before I store them into the constant buffer. But in my project it works without transposed matrices. When I transpose them, the scene is completely broken.

# Answer
> 0 votes
Your "world" matrix isn't really a world matrix. It's a world/model view projection matrix. That means it varies with your viewpoint, causing all your lighting calculations that depend on it to also vary with viewpoint.

You'll want to send (up to) three matrices down the pipe:

1. Object-to-World matrix, transforming model space positions to world space.

Use this matrix to get your world positions for comparing against your worldspace light & camera positions for your worldspace lighting calculations.
2. Model View Projection or MVP matrix, transforming model space positions into world space, into view space, and ultimately into perspective projection space.

Use this matrix (or optionally a View-Projection matrix multiplied by the worldspace position calculated in step 1) to produce your `SV_POSITION` for projecting your vertices onto the screen.
3. Inverse Transpose of 1, if you're using non-uniform scales anywhere.

Use this to transform your normal vectors. If all your scales are uniform, then you can re-use the World matrix in step 1 for this task too.

---
Tags: c++, directx11
---


# Question
Title: For Visual Studio Community 2017, 'Unreal Engine Installer' option is not available
On Visual Studio Community Installer, I cannot find 'Unreal Engine Installer' under 'Desktop Developemtn with C++' - 'Optional'. According to the tutorials I am learning, the 'Unreal Engine Installer' should be availbl.e

I have Visual Studio installed on 'C:' and Unreal installed on 'H:'; can this be the problem?

# Answer
You can find this under `Mobile and Gaming -> Game Development With C++ -> Optional` in the current version of VS installer.
> 1 votes

---
Tags: unreal-4, visual-studio
---


title: P2P network hiding positions?

text:
# Question
Title: P2P network hiding positions?
I have been working on a P2P architecture for secure gaming and I have divided the problem into five sub-problems:

* Unlawful modification of sent game state
* Accurately drop cheaters
* Agreeing on a game state
* Avoiding "look ahead" cheat
* Hiding sensitive information from opponents

The first four I have pretty much all solved but it is the last one which I am having trouble with.

Before I go into details I just want to ask if there's anything I've missed in my list of making a "cheat proof" p2p network. I am not interested in cheats such as using aimbots, I am only interested in making the p2p network as secure as a centralized server.

So in my effort so far on hiding sensitive information I've focused on the position of players in a game where the position of your opponent should not always be known. The problem then becomes how to determine if you should send you position to your opponent without knowing the position of your opponent.

I have ruled out methods such as the opponent sending multiple false positions for you to compare yours too since your opponent can easily abuse such a system since he will get your position if one of the false positions happened to be "visible" from your position.

The method I have been focusing on one in which you receive a "visual field" from your opponent and can thereby determine if you should send your position or not. This is however a problem in games such as League of Legends where the visual field of your opponent is also highly sensitive information. I have tried to solve this by transforming the visual field using a singular matrix meaning you cannot go from the transformed version of the visual field back to the original version, but since it is a linear transformation you can still figure out if your position is inside the visual field or not.

This does not however work perfectly, the exact visual field cannot be restored after transformation, but information about the "slopes" in the visual field (the visual field is constructed by several lines, and the slope of each line can be determined) can be restored and this can be used to relatively inexpensively reconstruct the original visual field.

In essence, what I need is a function which can determine if a position is "visible" or not, and reconstructing this function/visual field has to be so computationally demanding that once you are done reconstructing the visual field it is no longer relevant for the game in action. Is there any super smart person out there who happens to know of such a method?

*Edit* People seam kind of confused about the whole "vision field" so I aim to give a more detailed explanation here. The vision field consists groups of a set of lines, you can easily check if a position is inside one of these groups by just checking which side of the line your position is, if it's on the same side for all lines in that group you know it's inside that group and thus inside the vision field.

The information being sent however is not this line, but a transformation of the line and the transformation (2 by 2 singular a matrix), you can still check which side of the line your position is on by first transforming it using the transformation you received and comparing that value to the transformed line. The key here is that the transformation is singular, meaning it is impossible to find an inverse to go back to the original line. However it is possible to determine the slope of the line which makes reconstructing the line by just checking on which side of the transformed line a lot of points lie until you have pinpointed the origin of the line a lot computationally cheaper than if you did not know the slope of the line.

What I am looking for is a method for determining if a point is inside of an area, where reconstructing the area from the method is either impossible (which I doubt exists since you can always brute force it) or very computationally heavy.

# Answer
I think that even if you had an irreversible algorithm for a vision field, people could still gain advantage by calculating if nearby points to them would result in an intersection of that location and an opponents visual field would intersect. In a bad case (of a large enough vision field to map ratio) you could calculate by process of elimination the exact point of your enemy.

I think instead maybe all connected peers should announce which part of the map they are in, to determine if it possible if they can see each other or not. First split the map into 2x2 or 2x2x2 if the 3rd dimension is important. Then everyone tells each other if they are in 1,0 1,1 0,1 or 0,0. If they are not in the same quadrant, their conversation is over until next check. This protects their exact location. If they exist in the same quadrant, they will split this space up into 4 new quads, and continue until they determine that they are close enough to be seen by each other.

Of course there are problems with the borders of the quadrants, but it should be solvable by additional queries to neighboring quadrants.
> 1 votes

# Answer
Don't take this as a definitive answer, the topic is really broad (I won't be suprised if someone flag your question infact).

You can solve it by using some players as server, **and when a player is used as server it cannot participate in the game of players that are actually playing that server**.

If your game is not too demanding you could as well run multiple servers from the same player machine (of course that would be useful, since not all players can run as server due to NAT problems, thanks you IPv6!!).

The main problem here is that since a random player will be used as server, there's a slight chance it will be a "compromised" player or that it will pass the simulation to a "compromised" player, allowing sensitive information to be passed on (well, in reality at that point the server could send arbitrary data and force the win anyway).

If you use a central server to check authorizations and logins then you could allow to organize games better and to ban players easily (however that would no longer be a pure P2P network).

**You could also divide the world into slices and compute a hash of the visible slices, but this could be easily tricked, the most common visible slices will allow to build a table of hashes pretty quickly.**

To me your question is like trying to search for a cryptographic function. The test should be quick, but brute force should be slow..

The simplest thing that comes to my mind (also related to my work) is to use some quick vision recognition algorithm (Augmented reality-like).

If you manage to make a quick "snapshot" of your location (similiar to slices), than can be recognized only when placed around something visible then you are going to have it. Especially if there are timed elements in the map that allow to generate quick throw away recognition patterns.

However, even if such algorithms become pretty fast even on mobile, I don't think those will be fast enough for a First Person shooter.

Also if you make them too fast, you will have fake positives! And a player can anyway create a game that try some "Common visuals" so that one of the visuals match positive to the feature detection algorithm.

I will not be surprised the only possible solution to your problem would be possible in Quantum Computing, and within some years someone publish a paper prooving that intrinsic limit in P2P networks.
> -1 votes

# Answer
When you say 'Hiding sensitive information from opponents', you mean you want to avoid people with packet sniffers from listening to your traffic and getting info about your game?

If so, there's an easy answer to this; most AAA games (and certainly console games) use encryption. In fact, its so common that many of the networking middlewares used in games already have packet encryption built-in.

Usually it works like this: When you open a connection to another machine, before the socket becomes active, a Key exchange happens. I know that on XBox it used to be Diffie-Hellman key exchange; I've no idea if they still use it now. Then once you have your keys, all data sent is encrypted using the keys and unencrypted on receipt. If someone uses a sniffer to read your packets, they will look like gibberish and it's unlikely they can decrypt them since they don't have the keys. (Advanced hackers may be able to get them by accessing the process memory of the running game, but that is rare and unlikely.)

The only exception to the encryption rule is VoiceChat data; by law in the US, voice chat must be sent in-the-clear so that the CIA can listen in if they want to. Consoles usually provide a way to tag voice data so that it's not encrypted.
> -3 votes

---
Tags: networking, multiplayer
---


title: Implementing Spine animations in Libgdx

text:
# Question
Title: Implementing Spine animations in Libgdx
I've been searching a lot for a guide on how to implement 2D animations exported from Spine to Libgdx, but all I could find was outdated tutorials and source codes. I can handle basic Libgdx but Spine seems to be completely different. I was there, there, and also on lots of other sites (low reputation level won't let me post more links) but still I've got no idea how to do it. Does anyone know how to add those animations properly? (doesn't matter if it's json or binary) Preferably paste some code showing how to display something like spineboy so that I can see exactly what needs to be done. Any other suggestions appreciated..

# Answer
> 9 votes
Here is an official Spine 2D example where they load Spineboy into a game.

https://github.com/EsotericSoftware/spine-superspineboy

The following 4 lines are used to read a texture atlas and skeleton data as well as making some animation state data.

```
TextureAtlas playerAtlas = new TextureAtlas(Gdx.files.internal("spineboy/spineboy.atlas"));
SkeletonJson json = new SkeletonJson(playerAtlas);
SkeletonData playerSkeletonData = json.readSkeletonData(Gdx.files.internal("spineboy/spineboy.json"));
AnimationStateData playerAnimationData = new AnimationStateData(playerSkeletonData);

```

You also need a spritebatch and a skeleton renderer object.

```
SpriteBatch batch = new SpriteBatch();
SkeletonRenderer skeletonRenderer = new SkeletonRenderer();

```

The skeleton data and animation state data can then be used to create a new Skeleton and Animation State object.

```
Skeleton skeleton = new Skeleton(playerSkeletonData);
AnimationState animationState = new AnimationState(playerAnimationData);

```

You then play animations like so.

```
animationState.setAnimation(0, "walk", true); // trackIndex, name, loop

```

Then each render call, you update the animation state with delta time and apply the animation state to the skeleton.

```
animationState.update(delta);
animationState.apply(skeleton);

```

After applying the animation state to the skeleton, you can now render the skeleton.

```
batch.begin();
skeletonRenderer.draw(batch, skeleton);
batch.end();

```

# Answer
> 1 votes
After update the animation and apply it to the skeleton I had to add one more line to the render loop

```
skeleton.updateWorldTransform();

batch.begin();
skeletonRenderer.draw(batch, skeleton);
batch.end();

```

---
Tags: java, android, libgdx, spine
---


# Question
Title: Error building Player: CommandInvokationFailure: Failed to re-package resources. See the Console for details
I get following error while building to Android with Unty 5.2.2f1 (with a new&clean project).

**Notes:** I use GPGS 0.9.27 and Soomla Core 1.2.1 and Profile 2.2.1 and maximum supported Facebook package for soomla profile.

```
Error building Player: CommandInvokationFailure: Failed to re-package resources. See the Console for details.
E:\Programlar\Android SDK Tools\build-tools\22.0.1\aapt.exe package --auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" -I "E:/Programlar/Android SDK Tools\platforms\android-22\android.jar" -F bin/resources.ap_ --extra-packages android.support.v7.appcompat:com.facebook.android:com.google.example.games.mainlibproj:com.google.android.gms.base:com.google.android.gms:com.google.android.gms.drive:com.google.android.gms.games:com.google.android.gms.nearby:com.google.android.gms.plus:com.soomla.SoomlaApp:android.support.v4 -S "F:\Test\Temp\StagingArea\android-libraries\appcompat-v7-23.1.1\res" -S "F:\Test\Temp\StagingArea\android-libraries\facebook\res" -S "F:\Test\Temp\StagingArea\android-libraries\play-services-base-8.3.0\res" -S "F:\Test\Temp\StagingArea\android-libraries\play-services-basement-8.3.0\res" -S "F:\Test\Temp\StagingArea\android-libraries\play-services-drive-8.3.0\res" -S "F:\Test\Temp\StagingArea\android-libraries\play-services-games-8.3.0\res" -S "F:\Test\Temp\StagingArea\android-libraries\play-services-nearby-8.3.0\res" -S "F:\Test\Temp\StagingArea\android-libraries\play-services-plus-8.3.0\res" -S "F:\Test\Temp\StagingArea\android-libraries\support-v4-23.1.1\res"

stderr[
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-hdpi\com_facebook_button_like_background.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable\com_facebook_button_like_background.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xhdpi\com_facebook_button_like_background.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xxhdpi\com_facebook_button_like_background.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable\com_facebook_button_like_background_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-hdpi\com_facebook_button_like_background_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xhdpi\com_facebook_button_like_background_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xxhdpi\com_facebook_button_like_background_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable\com_facebook_button_like_icon.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-hdpi\com_facebook_button_like_icon.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xhdpi\com_facebook_button_like_icon.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xxhdpi\com_facebook_button_like_icon.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable\com_facebook_button_like_icon_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-hdpi\com_facebook_button_like_icon_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xhdpi\com_facebook_button_like_icon_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xxhdpi\com_facebook_button_like_icon_selected.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable\com_facebook_close.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-ldpi\com_facebook_close.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-hdpi\com_facebook_close.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\facebook\res\drawable-xhdpi\com_facebook_close.png: libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
F:\Test\Temp\StagingArea\android-libraries\appcompat-v7-23.1.1\res\values-v23\values-v23.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.

F:\Test\Temp\StagingArea\android-libraries\appcompat-v7-23.1.1\res\values-v23\values-v23.xml:30: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.

]
stdout[
Configurations:
 (default)

Files:
  AndroidManifest.xml
    Src: () AndroidManifest.xml

Resource Dirs:
Including resources from package: E:\Programlar\Android SDK Tools\platforms\android-22\android.jar
applyFileOverlay for drawable
trying overlaySet Key=ic_plusone_medium_off_client.png
trying overlaySet Key=ic_plusone_small_off_client.png
trying overlaySet Key=ic_plusone_standard_off_client.png
trying overlaySet Key=ic_plusone_tall_off_client.png
trying overlaySet Key=common_full_open_on_phone.png
trying overlaySet Key=common_ic_googleplayservices.png
trying overlaySet Key=common_google_signin_btn_icon_dark.xml
trying overlaySet Key=common_google_signin_btn_icon_dark_disabled.9.png
trying overlaySet Key=common_google_signin_btn_icon_dark_focused.9.png
trying overlaySet Key=common_google_signin_btn_icon_dark_normal.9.png
trying overlaySet Key=common_google_signin_btn_icon_dark_pressed.9.png
trying overlaySet Key=common_google_signin_btn_icon_light.xml
trying overlaySet Key=common_google_signin_btn_icon_light_disabled.9.png
trying overlaySet Key=common_google_signin_btn_icon_light_focused.9.png
trying overlaySet Key=common_google_signin_btn_icon_light_normal.9.png
trying overlaySet Key=common_google_signin_btn_icon_light_pressed.9.png
trying overlaySet Key=common_google_signin_btn_text_dark.xml
trying overlaySet Key=common_google_signin_btn_text_dark_disabled.9.png
trying overlaySet Key=common_google_signin_btn_text_dark_focused.9.png
trying overlaySet Key=common_google_signin_btn_text_dark_normal.9.png
trying overlaySet Key=common_google_signin_btn_text_dark_pressed.9.png
trying overlaySet Key=common_google_signin_btn_text_light.xml
trying overlaySet Key=common_google_signin_btn_text_light_disabled.9.png
trying overlaySet Key=common_google_signin_btn_text_light_focused.9.png
trying overlaySet Key=common_google_signin_btn_text_light_normal.9.png
trying overlaySet Key=common_google_signin_btn_text_light_pressed.9.png
trying overlaySet Key=common_plus_signin_btn_icon_dark.xml
trying overlaySet Key=common_plus_signin_btn_icon_dark_disabled.9.png
trying overlaySet Key=common_plus_signin_btn_icon_dark_focused.9.png
trying overlaySet Key=common_plus_signin_btn_icon_dark_normal.9.png
trying overlaySet Key=common_plus_signin_btn_icon_dark_pressed.9.png
trying overlaySet Key=common_plus_signin_btn_icon_light.xml
trying overlaySet Key=common_plus_signin_btn_icon_light_disabled.9.png
trying overlaySet Key=common_plus_signin_btn_icon_light_focused.9.png
trying overlaySet Key=common_plus_signin_btn_icon_light_normal.9.png
trying overlaySet Key=common_plus_signin_btn_icon_light_pressed.9.png
trying overlaySet Key=common_plus_signin_btn_text_dark.xml
trying overlaySet Key=common_plus_signin_btn_text_dark_disabled.9.png
trying overlaySet Key=common_plus_signin_btn_text_dark_focused.9.png
trying overlaySet Key=common_plus_signin_btn_text_dark_normal.9.png
trying overlaySet Key=common_plus_signin_btn_text_dark_pressed.9.png
trying overlaySet Key=common_plus_signin_btn_text_light.xml
trying overlaySet Key=common_plus_signin_btn_text_light_disabled.9.png
trying overlaySet Key=common_plus_signin_btn_text_light_focused.9.png
trying overlaySet Key=common_plus_signin_btn_text_light_normal.9.png
trying overlaySet Key=common_plus_signin_btn_text_light_pressed.9.png
trying overlaySet Key=com_facebook_button_blue.xml
trying overlaySet Key=com_facebook_button_blue_focused.9.png
trying overlaySet Key=com_facebook_button_blue_normal.9.png
trying overlaySet Key=com_facebook_button_blue_pressed.9.png
trying overlaySet Key=com_facebook_button_check.xml
trying overlaySet Key=com_facebook_button_check_off.png
trying overlaySet Key=com_facebook_button_check_on.png
trying overlaySet Key=com_facebook_button_grey_focused.9.png
trying overlaySet Key=com_facebook_button_grey_normal.9.png
trying overlaySet Key=com_facebook_button_grey_pressed.9.png
trying overlaySet Key=com_facebook_button_like.xml
trying overlaySet Key=com_facebook_button_like_background.png
trying overlaySet Key=com_facebook_button_like_background_selected.png
trying overlaySet Key=com_facebook_button_like_icon.png
trying overlaySet Key=com_facebook_button_like_icon_selected.png
trying overlaySet Key=com_facebook_button_like_pressed.png
trying overlaySet Key=com_facebook_button_like_selected.xml
trying overlaySet Key=com_facebook_close.png
trying overlaySet Key=com_facebook_inverse_icon.png
trying overlaySet Key=com_facebook_list_divider.9.png
trying overlaySet Key=com_facebook_list_section_header_background.9.png
trying overlaySet Key=com_facebook_loginbutton_silver.xml
trying overlaySet Key=com_facebook_logo.png
trying overlaySet Key=com_facebook_picker_item_background.xml
trying overlaySet Key=com_facebook_picker_list_focused.9.png
trying overlaySet Key=com_facebook_picker_list_longpressed.9.png
trying overlaySet Key=com_facebook_picker_list_pressed.9.png
trying overlaySet Key=com_facebook_picker_list_selector.xml
trying overlaySet Key=com_facebook_picker_list_selector_background_transition.xml
trying overlaySet Key=com_facebook_picker_list_selector_disabled.9.png
trying overlaySet Key=com_facebook_picker_magnifier.png
trying overlaySet Key=com_facebook_picker_top_button.xml
trying overlaySet Key=com_facebook_place_default_icon.png
trying overlaySet Key=com_facebook_profile_default_icon.png
trying overlaySet Key=com_facebook_profile_picture_blank_portrait.png
trying overlaySet Key=com_facebook_profile_picture_blank_square.png
trying overlaySet Key=com_facebook_tooltip_black_background.9.png
trying overlaySet Key=com_facebook_tooltip_black_bottomnub.png
trying overlaySet Key=com_facebook_tooltip_black_topnub.png
trying overlaySet Key=com_facebook_tooltip_black_xout.png
trying overlaySet Key=com_facebook_tooltip_blue_background.9.png
trying overlaySet Key=com_facebook_tooltip_blue_bottomnub.png
trying overlaySet Key=com_facebook_tooltip_blue_topnub.png
trying overlaySet Key=com_facebook_tooltip_blue_xout.png
trying overlaySet Key=com_facebook_top_background.xml
trying overlaySet Key=com_facebook_top_button.xml
trying overlaySet Key=com_facebook_usersettingsfragment_background_gradient.xml
trying overlaySet Key=abc_ab_share_pack_mtrl_alpha.9.png
trying overlaySet Key=abc_action_bar_item_background_material.xml
trying overlaySet Key=abc_btn_borderless_material.xml
trying overlaySet Key=abc_btn_check_material.xml
trying overlaySet Key=abc_btn_check_to_on_mtrl_000.png
trying overlaySet Key=abc_btn_check_to_on_mtrl_015.png
trying overlaySet Key=abc_btn_colored_material.xml
trying overlaySet Key=abc_btn_default_mtrl_shape.xml
trying overlaySet Key=abc_btn_radio_material.xml
trying overlaySet Key=abc_btn_radio_to_on_mtrl_000.png
trying overlaySet Key=abc_btn_radio_to_on_mtrl_015.png
trying overlaySet Key=abc_btn_rating_star_off_mtrl_alpha.png
trying overlaySet Key=abc_btn_rating_star_on_mtrl_alpha.png
trying overlaySet Key=abc_btn_switch_to_on_mtrl_00001.9.png
trying overlaySet Key=abc_btn_switch_to_on_mtrl_00012.9.png
trying overlaySet Key=abc_cab_background_internal_bg.xml
trying overlaySet Key=abc_cab_background_top_material.xml
trying overlaySet Key=abc_cab_background_top_mtrl_alpha.9.png
trying overlaySet Key=abc_control_background_material.xml
trying overlaySet Key=abc_dialog_material_background_dark.xml
trying overlaySet Key=abc_dialog_material_background_light.xml
trying overlaySet Key=abc_edit_text_material.xml
trying overlaySet Key=abc_ic_ab_back_mtrl_am_alpha.png
trying overlaySet Key=abc_ic_clear_mtrl_alpha.png
trying overlaySet Key=abc_ic_commit_search_api_mtrl_alpha.png
trying overlaySet Key=abc_ic_go_search_api_mtrl_alpha.png
trying overlaySet Key=abc_ic_menu_copy_mtrl_am_alpha.png
trying overlaySet Key=abc_ic_menu_cut_mtrl_alpha.png
trying overlaySet Key=abc_ic_menu_moreoverflow_mtrl_alpha.png
trying overlaySet Key=abc_ic_menu_paste_mtrl_am_alpha.png
trying overlaySet Key=abc_ic_menu_selectall_mtrl_alpha.png
trying overlaySet Key=abc_ic_menu_share_mtrl_alpha.png
trying overlaySet Key=abc_ic_search_api_mtrl_alpha.png
trying overlaySet Key=abc_ic_voice_search_api_mtrl_alpha.png
trying overlaySet Key=abc_item_background_holo_dark.xml
trying overlaySet Key=abc_item_background_holo_light.xml
trying overlaySet Key=abc_list_divider_mtrl_alpha.9.png
trying overlaySet Key=abc_list_focused_holo.9.png
trying overlaySet Key=abc_list_longpressed_holo.9.png
trying overlaySet Key=abc_list_pressed_holo_dark.9.png
trying overlaySet Key=abc_list_pressed_holo_light.9.png
trying overlaySet Key=abc_list_selector_background_transition_holo_dark.xml
trying overlaySet Key=abc_list_selector_background_transition_holo_light.xml
trying overlaySet Key=abc_list_selector_disabled_holo_dark.9.png
trying overlaySet Key=abc_list_selector_disabled_holo_light.9.png
trying overlaySet Key=abc_list_selector_holo_dark.xml
trying overlaySet Key=abc_list_selector_holo_light.xml
trying overlaySet Key=abc_menu_hardkey_panel_mtrl_mult.9.png
trying overlaySet Key=abc_popup_background_mtrl_mult.9.png
trying overlaySet Key=abc_ratingbar_full_material.xml
trying overlaySet Key=abc_scrubber_control_off_mtrl_alpha.png
trying overlaySet Key=abc_scrubber_control_to_pressed_mtrl_000.png
trying overlaySet Key=abc_scrubber_control_to_pressed_mtrl_005.png
trying overlaySet Key=abc_scrubber_primary_mtrl_alpha.9.png
trying overlaySet Key=abc_scrubber_track_mtrl_alpha.9.png
trying overlaySet Key=abc_seekbar_thumb_material.xml
trying overlaySet Key=abc_seekbar_track_material.xml
trying overlaySet Key=abc_spinner_mtrl_am_alpha.9.png
trying overlaySet Key=abc_spinner_textfield_background_material.xml
trying overlaySet Key=abc_switch_thumb_material.xml
trying overlaySet Key=abc_switch_track_mtrl_alpha.9.png
trying overlaySet Key=abc_tab_indicator_material.xml
trying overlaySet Key=abc_tab_indicator_mtrl_alpha.9.png
trying overlaySet Key=abc_text_cursor_material.xml
trying overlaySet Key=abc_textfield_activated_mtrl_alpha.9.png
trying overlaySet Key=abc_textfield_default_mtrl_alpha.9.png
trying overlaySet Key=abc_textfield_search_activated_mtrl_alpha.9.png
trying overlaySet Key=abc_textfield_search_default_mtrl_alpha.9.png
trying overlaySet Key=abc_textfield_search_material.xml
trying overlaySet Key=app_banner.png
trying overlaySet Key=app_icon.png
applyFileOverlay for layout
trying overlaySet Key=com_facebook_friendpickerfragment.xml
trying overlaySet Key=com_facebook_login_activity_layout.xml
trying overlaySet Key=com_facebook_picker_activity_circle_row.xml
trying overlaySet Key=com_facebook_picker_checkbox.xml
trying overlaySet Key=com_facebook_picker_image.xml
trying overlaySet Key=com_facebook_picker_list_row.xml
trying overlaySet Key=com_facebook_picker_list_section_header.xml
trying overlaySet Key=com_facebook_picker_search_box.xml
trying overlaySet Key=com_facebook_picker_title_bar<message truncated>

```

How to fix this?

# Answer
I fixed this error by going to **SDK Manager** and downloading **latest API** (it is Android 6.0 - API 23 while i'm writing this).

**Note:** *You don't have to download documentation or samples if you don't need, because they two take a while to download.*

Also make sure that you have **latest versions** of "**Extras/Android Support Repository**" and "**Extras/Google Repository**".
> 1 votes

# Answer
I have deleted the 24.0.0 build tools folder from `Android\sdk\build-tools` and it worked amazingly ..
> 1 votes

# Answer
deleting plugins / android / google-play-services\_lib / res / values / common\_attrs removed this error..

source: http://forum.unity3d.com/threads/failed-to-re-package-resources-help.345837/
> 0 votes

---
Tags: android, unity, google-play-services
---


# Question
Title: Scene2D viewport affects all other cameras despite having a separate one
I have two cameras initialized as such:

```
val mainCamera: OrthographicCamera by lazy { OrthographicCamera(WIDTH * ZOOM, HEIGHT * ZOOM) }
val guiCamera: OrthographicCamera by lazy { OrthographicCamera(WIDTH, HEIGHT) }

override fun initialize() {
    mainCamera.setToOrtho(false, WIDTH * ZOOM, HEIGHT * ZOOM)
    mainCamera.update()

    guiCamera.setToOrtho(false, WIDTH, HEIGHT)
    guiCamera.update()
}

```

Where `WIDTH` and `HEIGHT` values are `960f` and `640f` respectively and zoom is `0.5f` for `mainCamera`.

`mainCamera` is used for showing everything game related (following the player mainly) and doesn't use Scene2D, while `guiCamera` is used for displaying the GUI and is exclusively used within a Scene2D stage and is set in stages constructor like this:

```
private val stage: Stage by lazy { Stage(StretchViewport(WIDTH, HEIGHT, cameraSystem.guiCamera), batch) }

```

However when I change the viewport of the stage to `FitViewport` it seems that everything is shrunk and letterboxed, even the `mainCamera`.

I expected that using `FitViewport` with a specific camera would only perform scaling on entities using that camera, not on the whole scene.

Is this how it should work or am I doing something wrong? Sprite and map rendering systems render to the `mainCamera` and all rendering systems use the same batch, however I've also tried instantiating the stage with it's own dedicated batch so it had both it's own camera and a batch and still everything was shrunk.

P.S: The language used is *Kotlin* so the syntax is a little different from *Java* however most of the concepts are the same and straightforward. I'd only like to explain the `by lazy` syntax to those not familiar with *Kotlin*. `by lazy` means that the property won't be initialized until it's accessed for the first time. It allows me to define a final/constant (`val`) property but delay it's initialization until libgdx context is properly initialized and until artemis-odb system dependencies are injected.

# Answer
I just figured this out. You need 2 viewports and need the cameras assigned to those viewports. Then before you render you need to call apply() on those viewports so glViewport is set and used.

More info at the official docs: https://github.com/libgdx/libgdx/wiki/Viewports#multiple-viewports
> -1 votes

---
Tags: libgdx, viewport, scene2d
---


# Question
Title: C# JSONs not formatting array of objects stored inside another object.
I know the title is a bit confusing because I don't really know how to phrase this. This is what I have:

```
[System.Serializable]
public class Sector
{
    public string name;
    public Vector3 sectorPosition;
    public float sectorRadius;

    public buildingComponent[] components;

}
[System.Serializable]
public class buildingComponent : ScriptableObject
{
    public string componentType;
    public Vector3 componentPosition;
    public Vector3 compenentRotation;

}

```

When I try converting this into a json string like this:

```
        Sector ssector = new Sector();
        ssector.name = "sTom";
        ssector.sectorPosition = Vector3.up;
        ssector.sectorRadius = 2;
        ssector.components = new buildingComponent[3];
        print("component length " + ssector.components.Length);
        ssector.components[1] = new buildingComponent();

        ssector.components[1].componentPosition = new Vector3 (1, 2, 3);

        string sdata = JsonUtility.ToJson(ssector);

```

I end up with the following:

```
{"name":"sTom","sectorPosition":{"x":0.0,"y":1.0,"z":0.0},"sectorRadius":2.0,"components":[{"instanceID":0},{"instanceID":-341752},{"instanceID":0}]}`

```

The components array is not actually being formatted, it's only saved with an instanceId or whatever this does. Is there any solution to this or will I have to go with an alternative formatting. I just want to save this data on a server but I only get one string to do so, so I have to format everything into one string. Thanks in advance!

# Answer
> 0 votes
I am really new to Unity but have a C# developer so I did some digging and found the this forum question on Unity's site.

I think this is what you are looking for as an answer. It would appear that Unity's serialization of Monobehaviour has some magic on the backend that tells it what it requires only through those instance IDs.

This may also be of some help. He recommends saving the information explicitly.

---
Tags: unity, c#, file-format, json
---


title: Unity - Tile based river generation

text:
# Question
Title: Unity - Tile based river generation
I have made a map generation in my tile based game. It almost exactly does what I want, except for 1 thing. The rivers look like this:

The problem with this is, the water is not realistic. It are just some spots random over the world. I want to make a realistic river generation. Which would include different sizes (between 5 and 20 block wide), branches, lakes and different depths (by changing the colour of the water). What is the best way to do that?

Here is an Simcity 4 example of what I mean with realistic rivers:

My code:

```
waterOffsetX = Random.Range (10f, 300000f);
waterOffsetX = Mathf.Round (waterOffsetX) + 0.5f;
waterOffsetY = Random.Range (10f, 300000f);
waterOffsetY = Mathf.Round (waterOffsetY) + 0.5f;

for (float x = -gridX; x < gridX; x += 1)
{
    for (float y = -gridY; y < gridY; y += 1)
    {
        Vector3 spawnPos = new Vector3 (x, y, 0);
        float perlinWater = Mathf.PerlinNoise (x * seedWaterX + waterOffsetX , y * seedWaterY + waterOffsetY);

        if (perlinWater > perlinThresholdWater) {
        GameObject waterTile = Instantiate (water, spawnPos, Quaternion.identity) as GameObject;
    }
    }
}

Values:
seedWater (X & Y) = 0.1
Grid (X & Y) = 50
perlinThresholdWater = 0.6

```

# Answer
I wouldn't use straight perlin noise for this. The closest I would get would be to use something like Perlin Worms to generate the data for plotting the rivers.

However, I'd take a procedural generation approach. My answer here is where I'd start. You'll build the river backwards. Pick an end point for your river at some point along the edge of your map. Choose an end width, like your 20 tiles for a wide river. From there, you'll step away from that edge of the map, plotting the course of the river. Each step, there's a chance of:

1. Change direction. Weighted chance. Higher weight to continue straight, then to turn left or right, with a preference towards the opposite direction of the end.
2. Branch. The river splits its current path into two, dividing its current width between the two paths. Each new path takes its own steps.
3. Reduce in width. This accounts for water that's being added to the river that's too small for a tile.

Each of these options can happen more or less frequently depending on the width of the river. For example, you may want to change direction much less often when the river is wide, and more frequent direction changes when it's narrow.

```
Path
{
    width
    startingPoint

    pointWidths
    lastPointWidth
    currentDirection

    Step()
    {
         stepChoice = GetStepChoice(width) //weighted chance to decide what to do
         switch(stepChoice)
             changeDirection: //change the current direction
                 currentDirection = GetNewDirection(currentDirection)
             reduceWidth:
                 width--
             branch:
                 newWidth = divideWidth(width)
                 width = width - newWidth
                 RiverMaker.addPath(new path(newWidth, lastPoint))
             noChange:
                 //Do nothing, just step forward below

          lastPointWidth = (lastPoint+currentDirection, width)
          pointWidths.add(lastPointWidth)
    }
}

RiverMaker
{
    Path[] paths
    Path[] donePaths
    Start()
    {
        paths.add(new path(20, randomEdgeStartPoint)
        MakeRiver()
    }

    MakeRiver()
    {
        //process each path until there are none
        while(paths.count > 0)
        {
            for each path in paths
            {
                 if(path.isNotEnded)
                    path.Step()
                 else
                    donePaths.add(path)
                    paths.remove(path)
            }
        }
        for each path in donePaths
        {
            //Step through each path, using the width and position
            ApplyPathToWorld(path)
        }
    }
}

```
> 2 votes

# Answer
There is a well-know article on how to generate terrain from 2010, here:

http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/

with an update, here:

https://www.redblobgames.com/maps/mapgen2/

Now, for beginners, you achieve natural rivers without using Voronoi diagrams, if you generate a height map and then plot the river from the river source to the sea or ocean (basically the lowest point on your height map, which is the river end, so to speak), like so:

* a) start location, direction and height
* b) if same direction as last iteration: random direction, but only within 180° angle (to prevent turning back)
* c) find the lower level (height) and move there, if possible
* d) every few steps increase river width (so it gets wider to the sea)
* e) if you hit the water level: done
* f) if you do not hit water level: repeat b), c), d) and e)

Lakes and ponds are different and done in a second step. It means, when you look closer, you see that the SimCity rivers work without lakes, which means that lakes were either added before or after the river creation.

There's more to it, of course. For instance, if you change the direction every turn, well, your river feels weird, so you should change the direction only after a random number of steps. But I hope it helps.

I always work with the combination of height, rainfall and temperature (and wind too, actually). This way, the rainfall map shows where lakes will be. And, lakes and random "river sources" are then where I start rivers. What is great about rivers is that they make your landscape feel less flat, as if there is some hidden height, even if everything is flat.

If you lack a height map, because you are in flat lands, well, just create a fake one and see how the rivers behave. I am sure that SimCity generates additional height maps in order to make rivers more natural.
> 2 votes

---
Tags: 2d, unity, tiles, procedural-generation
---


# Question
Title: How does the double-buffered canvas know when to swap the buffer?
How does the HTML5 canvas know that all the drawing operations are complete and it's time to swap the buffer ? Program can have multiple draw calls at different places so how will it know when is the right time to swap the front and back buffers ?

# Answer
In HTML5, the browser lets you know when it's ready to paint the next frame via `requestAnimationFrame`. Usually, your "draw" calls happen within this callback.

In traditional games using double-buffering, the game loop itself dictates when the page flip occurs. A simple game loop might look like this:

```
loop {
    update()
    draw()
        // all the draw calls happen here
    flip()
}

```

So it doesn't matter where the draw calls are, at the game loop level it's well defined when they occur - usually between the `update` and `flip`.
> 1 votes

---
Tags: html5, html-canvas, double-buffering
---


title: Infinite sidescrolling terrain in Unity

text:
# Question
Title: Infinite sidescrolling terrain in Unity
I am trying to create a horizontal line at the center of the screen that goes infinitely. I could make the line short and move it with the camera but the shape of my line actually changes as you progress. I am using a line renderer and I am not sure what is the best way to achieve this?

Secondly, the camera keeps moving to the right so I would like those parts of the line that are not visible anymore to get destroyed. I am also not sure how to achieve this since this is one big line I assume?

# Answer
Keep a fixed-size array of line segments wide enough to accommodate your camera at max zoom. These are fed into your `LineRenderer` via `.SetPositions()`.

```
struct LineSegment
{
   Vector2 p0;
   Vector2 p1; //this will be the same as p0 of the next segment
   Color color;
   //etc.
}

LineSegment[] lineSegments = new LineSegment[SIZE];

```

As you move right, you need to get the appropriate `LineSegment` inserted to the start or end of the array (depending on which way you are moving) and shift out old ones (leftmost):

```
//MOVE RIGHT
void MoveCameraRight()
{
    lineSegments[0] = null; //remove leftmost (you don't actually need this line)

    //shift all 1 segments to the left
    for (int i = 1; i < lineSegments.length; i++)
    {
        lineSegments[i - 1] = lineSegments[i];
    }

    //get the new rightmost segment
    lineSegments[lineSegments.length - 1] = RetrieveLineSegmentAt(i);
}

//move left - I'll leave this one to you! very similar.

void RetrieveLineSegmentAt(int i)
{
    //generate procedurally
    //OR
    //retrieve from some larger list, database, or whatever.
}

```

If you ensure that your line segments are always the same width in `x` (even if tilted), you will always know exactly how many elements you need to fill the screen. I'd recommend this - it's easier. If, however, the rotation of individual line segment causes some to be narrower than others, like so:

```
    |\_
   /   \_
  |      \_
 /         \_
|            \_
^             ^
5 wide        10 wide

```

...then you will have to dynamically calculate how many you will need to fill the screen.

I would implement the whole terrain as a 1D heightmap, that is, just a sequence of heights at each evenly-spaced point. Your screen's `lineSegments` array can then be populated from the heightmap. This also means you can avoid dynamic width calculation, keeping things simple.
> 1 votes

---
Tags: unity, terrain, terrain-rendering
---


# Question
Title: How to get buttons to follow the GUI perfectly while also being usable in GameMakerStudio
Basically I'm trying to figure out how to make a button, that you can interact with that shows above the GUI draw event and locks perfectly to the screen.

The current draft I have the button is below the GUI layer so I need it above

The button is functional so thats good

The button does not lock perfectly to the screen when the camera stops it lags behind and has to catch up to the camera no matter what direction I move, I dont want the player to see the button actually following I want all the parts to move seamlessly together.

This is a gif of whats happening

# Answer
The only thing you need to do is make sure you *first* move your View around (the "camera"), *then* you can place the buttons at their relative position to the View. Once you're done with moving the View around, you can be sure there will be no jittering for objects following the View.

Try to change the Step Event with End Step Event, so that the button is moved toward the camera *after* the View has moved.
> 1 votes

---
Tags: game-maker
---