title: Opengl, VAO creation within a class

text:
# Question
Title: Opengl, VAO creation within a class
Creating the VAO for a simple cube within a function in the main file results in the cube being rendered properly:

```
GLuint createCube()
{
    GLuint VBO;
    GLuint VAO;
    GLuint EAO;
    GLfloat vertexData[] = {
        0.5f, -0.5f, -0.5f,
        0.5f, -0.5f, 0.5f,
        -0.5f, -0.5f, 0.5f,
        -0.5f, -0.5f, -0.5f,
        0.5f, 0.5f, -0.5f,
        0.5f, 0.5f, 0.5f,
        -0.5f, 0.5f, 0.5f,
        -0.5f, 0.5f, -0.5f,

    };
    GLuint elementData[] = {
        2-1, 3-1, 4-1,
        8-1, 7-1, 6-1,
        5-1, 6-1, 2-1,
        6-1, 7-1, 3-1,
        3-1, 7-1, 8-1,
        1-1, 4-1, 8-1,
        1-1, 2-1, 4-1,
        5-1, 8-1, 6-1,
        1-1, 5-1, 2-1,
        2-1, 6-1, 3-1,
        4-1, 3-1, 8-1,
        5-1, 1-1, 8-1,

    };

    // make and bind the VAO
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    // make and bind the VBO
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    // make and bind the eao
    glGenBuffers(1, &EAO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EAO);

    //put data into VBO and EAO
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW);

    // connect the xyz to the "vert" attribute of the vertex shader
    glEnableVertexAttribArray(render.get_shader()->attrib("vert"));
    glVertexAttribPointer(render.get_shader()->attrib("vert"), 3, GL_FLOAT, GL_FALSE, 0, NULL);

    // unbind the VAO, EAO, VBO

    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    return VAO;
}

```

However when I move the exact same code for creating the VAO for the cube to another class, a white 2d square renders and a uniform within my vertex shader called MVP gets removed (optimized out?) and the vertex shader doesn't run at all:

```
class cube
{
public:
    cube(Render rendrer)
    {
        GLuint VBO;
        GLuint EAO;
        GLfloat vertexData[] = {
            0.5f, -0.5f, -0.5f,
            0.5f, -0.5f, 0.5f,
            -0.5f, -0.5f, 0.5f,
            -0.5f, -0.5f, -0.5f,
            0.5f, 0.5f, -0.5f,
            0.5f, 0.5f, 0.5f,
            -0.5f, 0.5f, 0.5f,
            -0.5f, 0.5f, -0.5f,

        };
        GLuint elementData[] = {
            2-1, 3-1, 4-1,
            8-1, 7-1, 6-1,
            5-1, 6-1, 2-1,
            6-1, 7-1, 3-1,
            3-1, 7-1, 8-1,
            1-1, 4-1, 8-1,
            1-1, 2-1, 4-1,
            5-1, 8-1, 6-1,
            1-1, 5-1, 2-1,
            2-1, 6-1, 3-1,
            4-1, 3-1, 8-1,
            5-1, 1-1, 8-1,

        };

        // make and bind the VAO
        glGenVertexArrays(1, &VAO);
        glBindVertexArray(VAO);

        // make and bind the VBO
        glGenBuffers(1, &VBO);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);

        // make and bind the eao
        glGenBuffers(1, &EAO);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EAO);

        //put data into VBO and EAO
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW);

        // connect the xyz to the "vert" attribute of the vertex shader
        glEnableVertexAttribArray(rendrer.get_shader()->attrib("vert"));
        glVertexAttribPointer(rendrer.get_shader()->attrib("vert"), 3, GL_FLOAT, GL_FALSE, 0, NULL);

        // unbind the VAO, EAO, VBO

        glBindVertexArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }
    GLuint get_VAO() const
    {
        return VAO;
    }
private:
    GLuint VAO;
};

```

Here is my vertex shader:

```
#version 430

in vec3 vert;
uniform mat4 MVP; // gets removed

out vec3 vertout;

void main(void)
{
    vertout = vert;
    gl_Position = MVP*vec4(vert, 1.0);
}

```

Here is my fragment shader:

```
#version 430
//doesn't run at all
in vec3 vertout;
out vec4 outcolor;

void main(void)
{

    outcolor = mix(vec4(1,0,0,1),vec4(0,1,0,1),dot(vertout, vertout));
}

```

Here is my full code:

```
#include <iostream>
#include <Systems/UI/ui.h>
#include <Systems/Render/render.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
using namespace std;

UI ui(500,500,"Simple game"); // init SDL2 and create opengl context
Render render("/home/a/Desktop/Game/Game/ShaderCode/shadercode"); //object that handles rendering VAOs

int eventHandler()
{
    SDL_Event evnt;
    if(SDL_PollEvent(&evnt)){
        switch (evnt.type) {
        case SDL_QUIT:
            return false;
            break;
        default:
            break;
        }
    }
    return true;
}

//function init of VAO
GLuint createCube()
{
    GLuint VBO;
    GLuint VAO;
    GLuint EAO;
    GLfloat vertexData[] = {
        0.5f, -0.5f, -0.5f,
        0.5f, -0.5f, 0.5f,
        -0.5f, -0.5f, 0.5f,
        -0.5f, -0.5f, -0.5f,
        0.5f, 0.5f, -0.5f,
        0.5f, 0.5f, 0.5f,
        -0.5f, 0.5f, 0.5f,
        -0.5f, 0.5f, -0.5f,

    };
    GLuint elementData[] = {
        2-1, 3-1, 4-1,
        8-1, 7-1, 6-1,
        5-1, 6-1, 2-1,
        6-1, 7-1, 3-1,
        3-1, 7-1, 8-1,
        1-1, 4-1, 8-1,
        1-1, 2-1, 4-1,
        5-1, 8-1, 6-1,
        1-1, 5-1, 2-1,
        2-1, 6-1, 3-1,
        4-1, 3-1, 8-1,
        5-1, 1-1, 8-1,

    };

    // make and bind the VAO
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    // make and bind the VBO
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    // make and bind the eao
    glGenBuffers(1, &EAO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EAO);

    //put data into VBO and EAO
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW);

    // connect the xyz to the "vert" attribute of the vertex shader
    glEnableVertexAttribArray(render.get_shader()->attrib("vert"));
    glVertexAttribPointer(render.get_shader()->attrib("vert"), 3, GL_FLOAT, GL_FALSE, 0, NULL);

    // unbind the VAO, EAO, VBO

    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    return VAO;
}

//class init of VAO
class cube
{
public:
    cube(Render rendrer)
    {
        GLuint VBO;
        GLuint EAO;
        GLfloat vertexData[] = {
            0.5f, -0.5f, -0.5f,
            0.5f, -0.5f, 0.5f,
            -0.5f, -0.5f, 0.5f,
            -0.5f, -0.5f, -0.5f,
            0.5f, 0.5f, -0.5f,
            0.5f, 0.5f, 0.5f,
            -0.5f, 0.5f, 0.5f,
            -0.5f, 0.5f, -0.5f,

        };
        GLuint elementData[] = {
            2-1, 3-1, 4-1,
            8-1, 7-1, 6-1,
            5-1, 6-1, 2-1,
            6-1, 7-1, 3-1,
            3-1, 7-1, 8-1,
            1-1, 4-1, 8-1,
            1-1, 2-1, 4-1,
            5-1, 8-1, 6-1,
            1-1, 5-1, 2-1,
            2-1, 6-1, 3-1,
            4-1, 3-1, 8-1,
            5-1, 1-1, 8-1,

        };

        // make and bind the VAO
        glGenVertexArrays(1, &VAO);
        glBindVertexArray(VAO);

        // make and bind the VBO
        glGenBuffers(1, &VBO);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);

        // make and bind the eao
        glGenBuffers(1, &EAO);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EAO);

        //put data into VBO and EAO
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW);

        // connect the xyz to the "vert" attribute of the vertex shader
        glEnableVertexAttribArray(rendrer.get_shader()->attrib("vert"));
        glVertexAttribPointer(rendrer.get_shader()->attrib("vert"), 3, GL_FLOAT, GL_FALSE, 0, NULL);

        // unbind the VAO, EAO, VBO

        glBindVertexArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }
    GLuint get_VAO() const
    {
        return VAO;
    }
private:
    GLuint VAO;
};

glm::mat4 createMVP()
{
    glm::mat4 Projection = glm::perspective(45.0f, 1.0f / 1.0f, 0.1f, 100.0f);
    glm::mat4 View       = glm::lookAt(
        glm::vec3(4,3,3),
        glm::vec3(0,0,0),
        glm::vec3(0,1,0)
    );
    glm::mat4 Model      = glm::mat4(1.0f);
    glm::mat4 MVP        = Projection * View * Model;
    return MVP;
}

int main()
{

    // create cube via class
    cube cube_object(render);
    GLuint class_VAO = cube_object.get_VAO();

    //create cube via function
    //GLuint function_VAO = createCube();

    // mvp matrix
    glm::mat4 MVP = createMVP();

    bool running = true;
    while(running){
        running = eventHandler();

        //render.draw(function_VAO,36,MVP); // works

        render.draw(class_VAO,36,MVP); //doesnt work

        ui.swapBuffer();
    }

    return 0;
}

```

Does creating a VAO within a class cause these problems? Or is it something else?

# Answer
> 0 votes
You're passing the `Render` instance to your `cube` class by value. This is probably copying or reinitializing a bunch of state.

Remember that you can make classes non-copyable for cases like this. I *always* make systems/module classes like that non-copyable to avoid bugs like these. For things like your `cube` you'll also have problems (you'll end up deleting your VAO twice if you make a copy of the class). I think you're also leaking your VBO and your IBO.

For the future, no, being in a class itself *cannot* be the problem. A C++ class is just a way of organizing code; they're practically syntactical sugar for C structs and functions.

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


# Question
Title: How often do big MMORPG update the physics?
As far as I understand, most big games use fixed timestep to have a stable simulation.

Regarding the **game server**, which "frame rate" do they impose? Or said it another way, what fixed timestep do they tend to use?

I know many would say: "As fast as they can get away with". I'd like to know how fast is that, if you have direct experience of established MMORPG.

# Answer
> 7 votes
Second Life implements physics on the server side using Havok, and locks updates to 45 per second.

https://community.secondlife.com/t5/General-Discussions/SIM-FPS-is-maxed-out-at-45/td-p/181120

Earlier versions around 2005-2006 let the physics updates float as high as the server would allow. An uncomplicated region with few scripted objects could run at 800 updates per second... For better efficiency and consistency, they later locked it to 45.

(In Second Life, frame rate depends on each client's CPU and graphics power. World accuracy depends on network performance.)

# Answer
> 24 votes
I've worked on a couple of game servers, including a suite of them for an MMO.

In general, they don't have physics at all. In the few situations where physics are necessary (jumping, primarily) we let clients calculate their own physics, and we just deny anything that's too outlandish (players moving too fast for too long, going much higher than they should have been able to jump, etc).

Servers also typically don't have 'timesteps'. They don't normally think in "frames per second" at all. Instead, we know when we last heard from someone and what they were doing back then, and then when we hear from them again a little while later on we hear about what they're doing now, and so we update our internal state to match. There's no need to rigorously simulate everything server-side; we can just record the things the clients tell us and do some checks to make sure that what the clients say happened looks plausible to us.

# Answer
> 11 votes
Besides the other good answers given, I want to add the fact that some physics commonly is not driven by the server or even know about by the server and is a common trick to make the world seem more rich without adding overhead to the networking or server side processing.

For instance there might be debris you can kick around on the ground or blowing around in the wind that interacts with other objects, or maybe you can push dead bodies around.

If the physics is purely decorational, and doesn't affect movement or gameplay in any way, you can have it happen on the client side completely.

Different players will see things differently (like, if you shoot a can on the ground and it flies away, other players may not see that can fly away) but there are a lot of cases where that doesn't matter that the experience isn't the same for all players, and having client side physics simulations can really improve the look and feel of the online game.

# Answer
> 3 votes
EVE Online, an MMO with a single shard and up to several thousand plaers in big space battles runs its physics on a 1 Hz tick, called the "destiny" tick.

http://community.eveonline.com/news/dev-blogs/fixing-lag-drakes-of-destiny-part-1-1/

The so called "Bloodbath of B-R5RB" is the biggest emergent player fight ever to happen in an online game to date ("the 21 hour long conflict involved over 7,548 player characters overall and a maximum of 2,670 players in the B-R5RB system at one time", according to https://en.wikipedia.org/wiki/Bloodbath\_of\_B-R5RB).

---
Tags: mmo, fixed-timestep
---


# Question
Title: sfml/opengl, two objects of same class are sharing variables
whenever I use the none-default constructor, it only adds to the coordinates of the previous class(in an array)

```
wall_1x1 wall[2] = {
    wall_1x1(0, -2, 0), //first argument is x, second z, and third ry
    wall_1x1(1, -2, 0)
};

```

the second object in the array will be behind the first object(by -2 z) and if I give the first object an ry of 90, all the other objects will have the same rotation.

```
#pragma once
#ifndef WALL_1X1_H

#include <GL\glew.h>
#include <SFML\Graphics.hpp>

class wall_1x1 {

public:
  wall_1x1();
  wall_1x1(float x, float z, float ry);
  ~wall_1x1();
  void up();

private:
  float m_x;
  float m_z;
  float m_ry;
  GLuint tex;
  sf::Image data;
};

#endif

```

and the .cpp class:

```
#include "wall_1x1.h"

GLfloat verts[] = {
  0, 0, 0,
  1, 0, 0,
  1, 1, 0,
  0, 1, 0
};

GLfloat coords[] = {
  0, 0,
  2, 0,
  2, 2,
  0, 2
};

wall_1x1::wall_1x1() {
  m_ry = 0;
  m_x = 0;
  m_z = 0;
}

wall_1x1::wall_1x1(float x, float z, float ry) {
  m_ry = 0;
  m_x = 0;
  m_z = 0;

  m_x = x;
  m_z = z;
  m_ry = ry;

  data.loadFromFile("wall1.png");

  glGenTextures(1, &tex);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexImage2D(
    GL_TEXTURE_2D,
    0,
    GL_RGBA,
    data.getSize().x,
    data.getSize().y,
    0,
    GL_RGBA,
    GL_UNSIGNED_BYTE,
    data.getPixelsPtr());
}

wall_1x1::~wall_1x1() {
}

void wall_1x1::up() {
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  glVertexPointer(3, GL_FLOAT, 0, verts);
  glTexCoordPointer(2, GL_FLOAT, 0, coords);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTranslatef(m_x, 0, m_z);
  glRotatef(m_ry, 0, 1, 0);
  glDrawArrays(GL_QUADS, 0, 4);
  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}

```

and the important parts in main:

```
wall_1x1 wall[2] = {
    wall_1x1(0, -2, 0),
    wall_1x1(1, -2, 0)
};
....

wall[0].up();
wall[1].up();

```

# Answer
You can see the value of your member variables in your debugger, and it will show you the correct values.

Your problem lies in that the matrix transformation commands of legacy OpenGL are accumulating on top of each other.

If you want to start from a known state, you need to look into the functions that let you load an identity matrix, push and pop on the matrix stacks, and load/store matrices.
> 1 votes

---
Tags: opengl, sfml, oop, c++
---


# Question
Title: How to select random points within grid meeting min/max distance requirements from each other?
I have a 2D grid map that is relatively large. I'd like to pick some semi-random points all over it (say N points). The rule I want to ensure here, though, is that any selected points are at least M distance from every other selected point but no more than L distance from at least one other point.

Is there a fairly elegant way of doing this without having every new point's distance calculated for every existing point (being less computationally expensive as well)?

I imagine the rules could be met by something like partitioning the map out into rectangular segments and just kind of flood-fill randomly from one inner segment outwards, but I'm having a little trouble visualizing that where my L, M, and N values are randomly chosen (L is of course greater than or equal to M, but not entirely sure what the rules will be for M or N or even the size of the map).

The reason for this whole thing is a procedural waypoint system that I can then build a 2D dungeon crawler type map by using a path finding system to create tiles from waypoint to waypoint essentially.

If this is too vague or any other issues, just let me know and I'll happily try to explain further.

**Edit: To give some hard numbers as an example, say the full grid is 2,000 by 1,000 total possible points. Assume you want 5,000 total waypoints spread fairly randomly across the map. Each of the 4,000 points need to be (euclidean distance) greater than 20 from every other point and less than 30 away from at least one other point.**

# Answer
Every point must be greater then 20 and less then 30 away from each other.

```
Red    is the Point.
Purple is the radius 20 from point. If any point is placed here it means it is inside the radius of another point.
Green  is radius 30 from point.
White  is out side. No points should be placed here because it means that point will be 30 units away from any other point.

```

Next simply add a point randomly in a green space and fill in its neighbors. Each point is now greater then 20 and less then 30 from every other point.

Im guessing you will store your grid of points as a object that contains the state of the square.

There is also this method maybe this is what you were looking for in the first place :D
> 3 votes

# Answer
Your point selection rules can be satisfied by a Poisson-Disk sampling distribution & can be solved in O(n) with Bridson's algorithm. Basically, the algorithm divides the output region into a grid of cells sized relative to the minimum allowable distance, such that only one point can appear in each cell. Then, when you consider adding a new point, you only need to check a disk shaped collection of neighboring cells as opposed to the entire list of points. With respect to your problem, the cell & neighborhood size will account for your M parameter, the disk radii will account for your M parameter. Your N parameter is handled by terminating when enough points have been generated.

Mike Bostock has a nice animation showing the algorithm in progress.

The standard implementation is only concerned with a fixed minimal distance between points. amitp mentioned Herman Tulleken's Poisson Disk sampling article; it includes an adaptation to for varying the minimum distance across the resulting image/map which may make it better suited for your problem. It also includes source code.
> 1 votes

# Answer
Here's an idea of how it might go. Keep in mind the more points you create the less random their placing will be.

```
For(int i=0; i<3999; i++){
    array.add(new Point(random.int(x);
    random.int(y));
}

For(int i=0; i<3999; i++){
    int dist = Point.calcDistance(array.get(i),array.get(i++));
    //distance formula between two points: sqrt((x2-x1)^2+(y2-y1)^2))

    if(dist < 20 && dist> 30){
        array.remove(i++); //or create another one
    }
}

```
> 0 votes

---
Tags: 2d, mathematics, procedural-generation
---


# Question
Title: Getting the topleft, topright, bottomleft and bottomright points of a shape in Unity3D?
I have a 4-point shape that is defined in screen space by the user. They can draw the 4 points, one at a time, in any order they wish.

I am using a List of Vector2's to store the screen co-ordinates of each point.

Now what I'm trying to do is figure out how to get which of each of those 4 points are the topleft, topright, bottomleft and bottomright points of this shape, but I'm not having any luck.

I've tried using topleft = MinX, MinY etc, but obviously this doesn't work as the topleft point doesn't necessarily contain both the MinX and MinY value.

Can anyone point me in the right direction.

Thanks

# Answer
> 2 votes
supposing you already do some validation like Lars Viklund said, i suggest this aproach.

Let p0 , p1 , p2 , p3 be your points ordered by Y from top to bottom (or by X from L to R) :

```
//(very) pseudocode
  If p0.X < p1.X
       p0 is topleft
       p1 is topright
  else
       p0 is topright
       p1 is topleft
  end if
  If p2.X < p3.X
       p2 is bottomleft
       p3 is bottomright
  else
       p2 is bottomright
       p3 is bottomleft
  end if

```

# Answer
> 1 votes
A completely unambigious answer to your question cannot be found.

I would say that it's important that you determine the parameters within you're willing to accept shapes, and figure out how you can indicate this to the user.

There are many corner cases:

* shapes like a `<>` diamond,
* shapes where the lines cross (if lines are predetermined);
* shapes where points coincide.

A validation would probably be something like this:

* reject shape if line segments overlap;
* reject shape if points are too close or lines are too short;
* reject shape if angles seem too strange.

Once you've got a reasonably validated shape, you can attempt to classify points.

A sketch for a classification would be to compute an axis-aligned bounding box for your points and find the point that most closely agrees with a corner. Given a candidate point, you can iterate around the shape and verify the next point against the next corner.

---
Tags: geometry
---


title: LOVE Physics - Joint Stretching

text:
# Question
Title: LOVE Physics - Joint Stretching
After asking a similar question yesterday I've come across another problem with using joints in box2D / LOVE and trying to create a weighted chain.

Everything is set up as follows, I've tried to remove most of the fluff:

Each link is created as a body/shape pair then joined together and added to a links table.

```
    for i = 1, segments, 1 do

        link = {}

        link.body = love.physics.newBody(world, xpos, ypos, "dynamic")

        if (i == segments) then
            link.shape = love.physics.newCircleShape(endlink_radius) --Ending link
        else
            link.shape = love.physics.newCircleShape(link_radius)
        end

        link.fixture = love.physics.newFixture(link.body, link.shape) --Fix bodies to shapes

        table.insert(links,link)

        ypos = ypos + link_distance

    end

```

Links are joined together using rope joints to allow for some springy-ness:

```
    for i = 2, #links, 1 do

        x1,y1 = links[i-1].body:getPosition()
        x2,y2 = links[i].body:getPosition()
        links[i-1].join = love.physics.newRopeJoint(links[i-1].body, links[i].body, x1, y1, x2, y2, link_distance, true )

    end

```

The player controls the first element of the chain and holds the table of links, its created as follows:

```
local body = love.physics.newBody(world, 300, 100, "kinematic")
local shape = love.physics.newCircleShape(3)
local fixture = love.physics.newFixture(body, shape)
local chain = _chain.new(world)

```

Joined to the chain:

```
x1,y1 = body:getPosition()
x2,y2 = links[1].body:getPosition()
join = love.physics.newRevoluteJoint(body, links[1].body, x1, y1, x2, y2, true )

```

The player tracks the mouse cursor, determines a velocity and moves towards it by setting the linear velocity of the first chain element:

```
    body:setLinearVelocity(velocity.x, velocity.y)

```

And this very nearly works, you can pull the chain around quite nicely using the mouse (directing the top pink element), however if you keep spinning the chain it begins to stretch and pull away from the first element:

Any ideas on how to solve this?

I've tried using different joints and parameters, adding a reinforcing joint from the first link to the last, adjusting body weights and altering the update iterations but can't seem to find anything effective.

Many thanks.

# Answer
I found a fix for this by adjusting the world update time interval.

Initially the world was being once per frame updated using delta t, the time since the previous update.

```
world:update(dt)

```

From what I understand, by splitting this down into several smaller updates the forces being generated each update are small enough to be kept in check by Box2D.

```
world:update(dt/3)
world:update(dt/3)
world:update(dt/3)

```
> 1 votes

---
Tags: physics, box2d, lua, love2d
---


# Question
Title: Vertex Color won't pass to HLSL shader to be rendered
I should start his question off by saying that i am a begginer in HLSL. I've borrowed some shader code for flat shading from a website i've long since lost. It's works brilliantly for textured models but i cannot seem to get it functioning using vertex colored models. it just seems to always be grey.

My HLSL shader is as follows:

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

float4 AmbientColor = float4(1, 1, 1, 1);
float AmbientIntensity = 0.3f;

float3 DiffuseLightDirection = float3(1, 0, 0);
float4 DiffuseColor = float4(1, 1, 1, 1);
float DiffuseIntensity = 1.0f;

texture ModelTexture;
sampler2D textureSampler = sampler_state {
    Texture = (ModelTexture);
    MinFilter = Linear;
    MagFilter = Linear;
    AddressU = Clamp;
    AddressV = Clamp;
};

struct VertexShaderInput
{
    float4 Position : SV_Position0;
    float4 Normal : NORMAL0;
    float4 Color : COLOR0; //Added in by me
    float4 TextureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : SV_Position0;
    float4 PositionWorld : TEXCOORD0;
    float4 Color : COLOR0; //Added in by me
    float4 TextureCoordinate : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
    output.PositionWorld = worldPosition;
    output.Color = input.Color; //Added in by me
    output.TextureCoordinate = input.TextureCoordinate;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float3 Normal = cross(ddy(input.PositionWorld.xyz), ddx(input.PositionWorld.xyz));
    Normal = normalize(Normal);

    float lightIntensity = dot(Normal, DiffuseLightDirection);
    float4 lightColor = lightIntensity * DiffuseColor * DiffuseIntensity + AmbientColor *     AmbientIntensity;
    lightColor.a = 1;

    float4 textureColor = tex2D(textureSampler, input.TextureCoordinate);
    textureColor.a = 1;

    //return saturate(textureColor * lightColor);
    return saturate(input.Color * lightColor); //Added in by me
}

technique FlatTextured
{
    pass Pass1
    {
        VertexShader = compile vs_4_0 VertexShaderFunction();
        PixelShader = compile ps_4_0 PixelShaderFunction();
    }
}

```

As you can see I've temporarily commented out the line which uses the texture color for shading and tried to replace it with vertex color. I've also highlighted in the code which lines i've changed to attempt to use vertex coloring.

At the moment this only produces grey shaded models. I know there is vertex data on the models because i can use MonoGame's built in BasicEffect to see the coloring.

What am i doing wrong? How can i modify the existing shader to use vertex color instead of texture color?

**Edit: Additional information**

I've tried using the BasicEffect in monogame to draw my objects and the vertex colors are coming through fine. It seems that i should be able to see the colors with my shader but i am not.

With the BasicEffect

With My Effect

**Edit: Additional Information**

Here is the code in the draw method i am using. The un-commented part is using my shader, while the commented part is the BasicEffect that is set up when the model is loaded.

```
flatShadedEffect.CurrentTechnique = flatShadedEffect.Techniques["Flat"];

        foreach (ModelMesh mesh in modelobject.Model.Meshes) {

            foreach (ModelMeshPart part in mesh.MeshParts) {
                part.Effect = flatShadedEffect;
                part.Effect.Parameters["View"].SetValue(camera.GetView());
                part.Effect.Parameters["Projection"].SetValue(camera.GetProjection());
                part.Effect.Parameters["World"].SetValue(modelobject.GetWorld());
            }

            //foreach (BasicEffect effect in mesh.Effects) {
            //    effect.World = modelobject.GetWorld();
            //    effect.View = camera.GetView();
            //    effect.Projection = camera.GetProjection();
            //}

            mesh.Draw();
        }

```

# Answer
So after a few days of digging i finally found this question which is asking the exact same thing as me. He fixed the issue by using in my opinion a dirty hack.

This involves getting the vertex colors from the original BasicShader when the model is created. The when it comes to draw, that color is passed in a parameter to the shader which in-turn uses it as the parts diffuse color. This produces the image i want, but is a bit hack-ish..

I will keep the question open in case a better answer present itself.

The Result:
> 1 votes

---
Tags: hlsl, monogame
---


# Question
Title: Should a mesh consist of triangles or quads?
Currently I am a bit puzzled. I am writing my master thesis about procedural mesh and texture generation and for that I am writing a Blender Add-On to generate low poly planets with physical physically based rendering textures.

This blog (http://blog.digitaltutors.com/modeling-with-quads-or-triangles/) says that it's better to use quads instead of triangles and n-gons. The wireframe looks cleaner, subdivides are more logic and having edge loops. Another blog about this topic can be found here http://blog.digitaltutors.com/ngons-triangles-bad/

But I also read this Why do game engines convert models to triangles compared to keeping it as four side polygon which says that in the end everything is converted to triangles. So I would assume that it's better to use triangles from the beginning so that the engine doesn't need to convert quads to triangles.

**And now I don't know if it's better to use triangles or quads.**

I could think of it this way:

* For modeling use quads, because it's easier to manipulate a quad-mesh.
* When modeling is done convert to triangles and export the mesh. But I think this is altering the low poly art style.
* Use in a Game Engine.

If I read the *ngons-triangles-bad* blog post it says that there could be render issues with triangles. So why do engines than convert the mesh to triangles?!

Am I missing something important?

Any advice or more info? Thanks!

# Answer
> 8 votes
A mesh should consist of what it needs to consist of.

Certain modelling operations are made significantly easier to implement, or provide better visual results, when the mesh is represented as quads. Your linked article does a decent job of provided a brief survey, and also touches on the edge-loop benefits which are useful even in simple modelling.

However, modern graphics cards only work with triangles, so at some point the mesh data must be converted to triangles.

Consequently, a reasonable rule of thumb is model using quads (particularly if your art pipeline is going to be making extensive use of algorithms that are better-suited to quads), and convert to triangles after the stage in the pipeline where the modelling is done, for example during the export/bake process that turns meshes into the optimal engine format.

If you're not doing anything in your art pipeline that benefits from quads, and you prefer triangle modelling for some reason, that's fine too.

---
Tags: modelling-techniques
---


# Question
Title: Do I need to use SteamWorks in my game to have it on steam?
Do I need to use SteamWorks in my game to have it on steam? The website talks about it however it does not state it is necessary so I am asking if it is.

I am not asking *how* to do it I'm asking *if* I need to do it.

# Answer
> 5 votes
No you do not. Everything Steam provides is optional to use by the developer.

If I remember correctly The Binding of Isaac, the original one, was written in Flash and had no chance of ever integrating the C++ Steam SDK. As a result there was no Steamworks support or Steamworks DRM on the game.

---
Tags: steam
---


title: LibGDX - Managing a Minimap

text:
# Question
Title: LibGDX - Managing a Minimap
I'm making a top-down strategy game so I thought a minimap is a must. I'm using Scene2D to display my GUI and since the minimap is technically a part of the GUI, I used the stage camera to position the minimap. Below is how I'm rendering the minimap.

```
    shape.setProjectionMatrix (stage.getCamera ().combined);
    shape.begin (ShapeType.Filled);
    shape.setColor (Color.CYAN);
    shape.rect ((Constants.RENDER_WIDTH - 500) + ship.getX () / 30, ship.getY () / 30, 5, 5);
    shape.end ();

    shape.setProjectionMatrix (stage.getCamera ().combined);
    shape.begin (ShapeType.Line);
    shape.setColor (Color.YELLOW);
    shape.rect (Constants.RENDER_WIDTH - 500, 0, 500, 500);
    shape.setColor (Color.WHITE);
    shape.rect ((Constants.RENDER_WIDTH - 500) + (camera.position.x) / 30, (camera.position.y - camera.viewportHeight / 2) / 30, Constants.RENDER_WIDTH / 30, Constants.RENDER_HEIGHT / 30);
    shape.end ();

```

The first ShapeRenderer (shape) call renders the ship marker, which is currently a small square. The second renders the bounds of the minimap which is 500x500. RENDER\_WIDTH and RENDER\_HEIGHT are the width and height that I'm plugging into camera as viewport dimensions (1920x1080). The map is 15000x15000, so I'm dividing the ship location by 30 so that it is always in the range of 0-500. However, when I move the camera around I actually end up being able to see the ship before the minimap says I should, which is illustrated below. I'm fairly certain it's due to the zoom level of the camera, but I haven't figured out how to incorporate that other than multiplying the width and height of the display of where the camera is (the white box), by the current zoom level, which didn't work.

# Answer
> 1 votes
I've managed to get it working by fiddling around and it would seem that this works as I wanted.

```
   `shape.setColor (Color.WHITE);
    shape.rect ((Constants.RENDER_WIDTH - 500) + (camera.position.x - (camera.viewportWidth * camera.zoom) / 2) / 30, (camera.position.y - (camera.viewportHeight * camera.zoom) / 2) / 30, (Constants.RENDER_WIDTH * camera.zoom) / 30, (Constants.RENDER_HEIGHT * camera.zoom) / 30)`

```

# Answer
> 1 votes
Well if you are incorporating zoom with your camera you have to multiple the rectangle by that. It also depends from where the camera actually zooms, I believe this is the center of the camera but it might be bottom left too.

Something like this should leave you with the correct rectangle size.

```
shape.rect ((Constants.RENDER_WIDTH - 500) + (camera.position.x) / 30,
   (camera.position.y - camera.viewportHeight / 2) / 30,
   Constants.RENDER_WIDTH / (30 * zoom), Constants.RENDER_HEIGHT / (30 * zoom));

```

You might need to reposition the rectangle by half the size to get centered properly. I advice you to deconstruct that long overload with formula's into something simpler.

```
Rectangle miniMap = new Rectangle(); //Here you create the minimap rectangle so you have access to it's numbers.
Rectangle miniCam = new Rectangle(); //

//First we set it's width so we have access to it when we want to position the camera.

miniCam.setWidth((minimap.getWidth() / 30) * zoom); //First get the normal miniCam size only then we should multiply it by zoom.
miniCam.setHeight((minimap.getHeight() / 30) * zoom);

minicam.setX(miniMap.x + (camera.position.x / 30) - (miniCam.getWidth() / 2);
// (miniCam.getWidth() / 2) to center it
minicam.setY(miniMap.y + (camera.position.y / 30) - (miniCam.getHeight() / 2);

```

Now draw your rectangle with it. Using this method makes it easier for you but especially other to read your code and see what is going on. It helps breaking down the problem to smaller bits.

---
Tags: libgdx, camera
---


# Question
Title: How do you allow networking code to be written in the later stages of the development?
I'm currently in the early progress of writing a game which I eventually will want to improve in most aspects.
How can I skip out on writing network code yet leaving it fairly easily implemented, that is, not having to rewrite the entire game just to add it.
What do I have to keep in mind?

I have a component pattern where I separate physics/collision-detection, game logic, data types and animating/rendering from each other.
How do I write a client and server that doesn't have any network code implemented yet can be tested locally?
What should I do in the client and what should I do in the server? Should I sort of just pretend I have network code finished and send messages between server and client and account for delays etc. even though there will be none?

**Edit:** It's planned to be a top down RPG. Simple multiplayer where you host a server for your friends is what I'm thinking, so cheating isn't that much of an issue (who would like to play with cheating friends?). Still I'd like to go with a "The server is always right"-approach.

**Edit 2:** I guess I'm looking for some pointers on what my mind set should be like. How should I handle keyboard input, animating, etc, instead of just applying every effect/change instantly. Hmmm, I may need to read up properly on networking before going anywhere after all, which was what I had hoped to get away from by making a network skeleton of some sort that could work locally.

# Answer
> 12 votes
Without knowing more about the exact game you're writing, and how you're writing it, it is very difficult to say generic solutions to your problem.

However, you may want to consider this decision you're taking of leaving the networking code to the end, depending on how crucial networking is for your game.

What I mean is that, if you're writing a network heavy game, such as an MMORPG, it may not be wise to leave networking to the end.

That considered, if the impact you expect for networking code is low (as in, not having networking code at all is not game-breaker), then it could be appropriate to leave it for a later (but not too late) stage.

Remember that -writing- networking code is not the same as -thinking- about it. As you make decisions about how your game is made, you should consider how this would affect networking decisions, and if the expected impact is high, maybe implement it as a stub that gives some generic information, and then when it's time to write the networking code, it is just a matter of plugging it in where you left the stub.

So, for instance, if you're making an online chess game, you may have a function called `ExecuteMove()` which is called in some way when a move is input by mouse, and in another way when a move is input by keyboard. At this point, you may want to think about creating a networking stub which, after getting the required data from the other host (this is what you write at a later part), calls `ExecuteMove()`.

That way, as you create your game, you will know which parts are affected by networking code, and when it is time to actually write the networking code, you're several steps ahead.

If this is your first time writing a networked game, consider not thinking too much about anti cheating and stuff like that. Making a networked game is complex enough to require an entire team of highly experienced people to do so for an AAA game, so take it slow, and first make a game that does work, before focusing on more complex topics.

Finally, if this is your first time making a game, don't make it networked, please. Making a game is so complex, that each requirement you add to your game will make it exponentially more complex.

# Answer
> 2 votes
I'm in a similar situation, but I'm trying to do a networked simulation more than a game; but I think that my approach may help your design process.

My approach is along the line of your comment on IPC (inter-process communication).

First, as background I am studying the book "Networked Graphics" by Steed and Oliveira. This provides a good background on various network architectures for games depending on various criteria and game types. It provides a tool to help you decide your game architecture and what exactly you want to put on the network, and what you want to occur locally.

Second, separate the network components into a separate background thread so your initial game development can have the component coded locally, but you are forced to deal with the thread separation. Do not combine them with any other features that will later be "local background" but force them into "potentially remote" background threads.

This should help keep your logic separated and also allow you to simulate network delay factors into the process so you can also see the impact of latency.

# Answer
> 1 votes
If you're learning about all this stuff, why not write a simple single-player Version 1, and once that's working, with your deeper knowledge, rethink the whole thing in-depth for Version 2 that will be multi-player?

# Answer
> 0 votes
Implement a "fake network" class that passes messages between threads, which has the same interface as the network class will have. Later you can elaborate the fake network to have random delays and packet loss. It will always be easier to debug network code with the fake class than with the real network.

---
Tags: c#, networking, multiplayer, architecture
---


# Question
Title: I can't understand the batcher.draw at libgdx
here is the code:

```
batcher.draw(birdMid, bird.getX(), bird.getY(), bird.getWidth() / 2.0f,
             bird.getHeight() / 2.0f, bird.getWidth(), bird.getHeight(),
             1, 1, bird.getRotation());

```

what each parameter in this method presents? Please explain in detail

# Answer
> 1 votes
On my version (1.6.3) there is only one SpriteBatch method that takes 10 parameters.

```
/** Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. The
 * rectangle is offset by originX, originY relative to the origin. Scale specifies the scaling factor by which the rectangle
 * should be scaled around originX, originY. Rotation specifies the angle of counter clockwise rotation of the rectangle around
 * originX, originY. */
public void draw (TextureRegion region, float x, float y, float originX, float originY, float width, float height,
    float scaleX, float scaleY, float rotation);

```

Your IDE most probably supports some button like `Go To Declaration`. Next time you should use that. My guess is that you are supplying a texture instead of a TextureRegion but there is not enough code to proof this.

---
Tags: libgdx, spritebatch
---


title: Isometric Terrain Editor

text:
# Question
Title: Isometric Terrain Editor
I am trying to make an isometric terrain editor. My problem is not to do with making isometric graphics or rendering them, rather it is to do with indexing of tiles.

Let's say I'm making a hill at tile(10,5). This would mean that tile(10,5) will be type corner\_1, tile(11,5) will be corner\_2, tile(10,6) will be corner\_3, and tile(11,6) will be corner\_4. This will create a peak in the middle of the four tiles.

It seems simple to start with, but there are so many possibilities. If we have two hills that cross over each other, we would need inverted corner tiles. If we had a diagonal mountain, the surrounding tiles would need to be turned into diagonal inverted corner tiles. I've already created most of the images for the tiles http://opengameart.org/content/simple-iso-city-work-in-progress. My question is, is there already a set of "rules" I can follow for how terrain modifies itself around surrounding terrain? Or do I have to figure out every combination of tiles myself?

# Answer
If you have the height of each corner you can easily find which tile to use. For example on the following drawing, the tile number 1 has hills on its top corner and left corner. The tile number 2 has a hill on its left corner.

To know which tile to use you would write something like that :

```
if (top_corner_height == LOW
&&  bottom_corner_height == LOW
&&  left_corner_height == LOW
&&  right_corner_height == LOW)
{
    tile = FLAT_TILE;
}
else if (top_corner_height == HIGHT
&&  bottom_corner_height == LOW
&&  left_corner_height == LOW
&&  right_corner_height == LOW)
{
    tile = ...
}
else if (...)
{
    ...
}

```

You just test every case possible.
> 1 votes

---
Tags: 2d, isometric, terrain, tilesets
---


title: Texturing without D3DX

text:
# Question
Title: Texturing without D3DX
Well, i have been online for hours looking for solutions, but i have found none. Im looking for a way to create textures without the function `D3DXCreateShaderResourceViewFromFile`. Since D3DX is deprecated i figured that DirectXTK was the way to go since it is supported officially. I found that i could use the function `CreateWICTextureFromFile`, but whenever i use it i get the following linker errors: LNK2038 mismatch detected for '\_MSC\_VER' value 1800 doesnt match value 1900 in

LNK2019 unresolved external symbol "\__declspec(dllimport) public: void \__thiscall std::\_Container\_base12@std@QAEXXZ referenced in function "public: void \__thiscall std::\_String\_alloc\<0,struct std::\_String\_Base\_types\>\>::\_Free\_proxy(void)".......

any idea why is this happening? (i have both the header included and the DirectXTK.lib library linked into the project)? and is there any simpler way to create textures, without the added whole library just for 1 function?

# Answer
> 2 votes
The error message indicates that you are mixing static libraries built with one version of Visual C++ (VS 2013) with code built with a different version (VS 2015). This is because the Standard C++ Library cannot be 'mixed' in the same application.

If you are using VS 2015, then you should pick the appropriate vcxproj for your platform and toolset using project-to-project references:

* `DirectXTK_Windows10` is for Windows 10 UWP built with VS 2015
* `DirectXTK_Desktop_2015` is for Windows desktop apps built with VS 2015 with 'down-level' compatibility for Windows 7
* `DirectXTK_Desktop_2015_Win10` is for Windows desktop apps built with VS 2015 that requires Windows 10 or later--this config mostly exists for test purposes.

See the DirectX Tool Kit wiki for details.

> NuGet packages for VS 2015 are now published for UWP and Windows desktop.

# Answer
> 0 votes
Probably the .lib file was compiled on a different version of Visual Studio. I don't know about DirextXTK but some library distributions contain multiple versions of libs for different compilers.

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


# Question
Title: Problem restoring the game preffered buffer size after navigating from a XAML page. Monogame
I have implemented to my game a simple leaderboard and submit score pages, which are pages in XAML. I used PreferredBackBufferHeight/Width to set the buffer to be equaly on all devices, whether their screen size is 5 inch, 4.7 or whatever size. Though I thought the problem was solved, now, when I was testing my game on emulator for bigger devices, I encountered a problem when returning back to game page from the xaml page. Let me show you some pics, and you will understand what I am talking about:

Testing on Emulator 4.7 inch:

1) Before entering the leaderboard xaml page (everything normal):

2) After exiting from xaml leaderboard page:

Even if I tried to put the PreferredBackBufferHeight/Width in the function that I call to exit from the leaderboard page, it didn't change anything... :

```
private void NavigateBackToMain()
    {
        var app = App.Current as App;

        if (app.GamePage == null) app.GamePage = new GamePage(string.Empty);
        Game1.statics.graphics.SupportedOrientations = Microsoft.Xna.Framework.DisplayOrientation.LandscapeRight | Microsoft.Xna.Framework.DisplayOrientation.LandscapeLeft;
        Game1.statics.graphics.PreferredBackBufferHeight = Constants.PrefferedBufferHeight;
        Game1.statics.graphics.PreferredBackBufferWidth = Constants.PrefferedBufferWidth;

        Window.Current.Content = app.GamePage;
    }

```

What can I do about my problem?

# Answer
> 1 votes
I think you solved your problem already, but for any future visitors to the site here it is as well.

The problem that you were having was that you never called `Graphics.ApplyChanges()` after you changed your graphics settings. This resulted in the screen not actually being updated, and the smaller screen after exiting is due to an odd orientation bug.

Here's what your code should look like:

```
private void NavigateBackToMain()
{
    ....
    Game1.statics.graphics.SupportedOrientations = Microsoft.Xna.Framework.DisplayOrientation.LandscapeRight | Microsoft.Xna.Framework.DisplayOrientation.LandscapeLeft;
    Game1.statics.graphics.PreferredBackBufferHeight = Constants.PrefferedBufferHeight;
    Game1.statics.graphics.PreferredBackBufferWidth = Constants.PrefferedBufferWidth;

    Game1.statics.graphics.ApplyChanges();
    ....
}

```

---
Tags: xna, monogame, windows-phone-8
---


title: Sprite draw-order in libgdx

text:
# Question
Title: Sprite draw-order in libgdx
From other frameworks I know methods for easy ordering sprites within a spritebatch (to determine if a sprite has to be drawn in front or behind another sprite). For example in MonoGame/XNA this is called `Sprite.depth` or Pyglet has its `OrderedGroups`.

But I cannot find anything like that in libgdx. I've read that libgdx' scene2d has something like that but I don't want to use that as I use a entity system (ashley) and want to keep rendering separeted from the other logic.

What is the appropriate way to set the draw-order of libgdx sprites?

# Answer
> 6 votes
You are correct that libGDX doesn't contain any sort of built-in support for rendering sprites in a certain order. (If it's there, I haven't seen it, and I've been using libGDX for a number of years.)

What I do is create a `SpriteComponent` class that wraps the `Texture` object and emits `x`, `y`, and `z` attributes.

Then in my draw method, I sort all `SpriteComponents` by `z` (ascendingly) and draw them -- so lower-Z items draw first, then higher-Z items on top.

# Answer
> 4 votes
For normal cases, sprite order is determined by the `Spritebatch.draw()` call order. If this is the case:

```
spritebatch.draw(apple);
spritebatch.draw(mango);

```

then `apple` will be drawn first and then `mango` will be drawn on top of that. So `mango` will overlap `apple`.

---
Tags: libgdx, sprites, spritebatch, draw-order
---


# Question
Title: OpenGL 4.5 Primitive Restart vs. Base Index
From how I understand the two techniques (Primitive Restart and Base Index) explained on https://www.opengl.org/wiki/Vertex\_Rendering , they both do the very same thing. Simply spoken, they allow me to put many meshes into the same buffer and then render them as multiple meshes again. **Is my understanding right?**
If my understanding is indeed right, then my next question would be how well either of them works together with indirect rendering and multi-rendering.
Let's just use the following example: I have multiple meshes, which are put together to one entity. Multiple entities are put together to one scene. In a scene, entity attributes, like location, textures,... might change. What would be the most optimized way to render them performance vise? By using glMultiDrawElementsBaseVertex() (is there an indirect version?) or by setting glPrimitiveRestartIndex() and then using glMultiDrawElementsIndirect()?
If there is no indirect variant for the former, **shouldn't the latter be the better choice**?
Of course, there might be a better way of doing things. If so, I would really like to hear it :)

# Answer
> 1 votes
For your first question yes your understanding is right.

Secondly I would argue that doing `Multidraw*Indirect` (without `glPrimitiveRestartIndex()`) would be better for performace (most optimized). The main thing to remember is that each OpenGL call you are doing is calling the OpenGL driver. So the more calls you do the more driver overhead you incurr.

A great place to look at how you can incurr minimal driver overhead is this presentation (slides) and the code @ github.

I'll give a brief example of what you have to do but you can go into more detail of the implementation with the links I've supplied.

---

Basically you fill your buffers (`GL_ARRAY_BUFFER` or `GL_ELEMENT_ARRAY_BUFFER`) and calculate your offsets into each model.

Then populate a draw command in either the form of

```
typedef struct {
        GLuint  _count;
        GLuint  _instanceCount;
        GLuint  _first;
        GLuint  _baseInstance;
    } DAICmd;

```

for `GL_ARRAY_BUFFER` (link on how to render) and

```
typedef struct {
        GLuint  _count;
        GLuint  _instanceCount;
        GLuint  _first;
        GLuint  _baseVertex;
        GLuint  _baseInstance;
    } DEICmd;

```

for `GL_ELEMENT_ARRAY_BUFFER` (link on how to render).

Each commands go into a `GL_DRAW_INDIRECT_BUFFER` and your extra attributes (matrix transforms, texture handles, etc...) go into a `GL_SHADER_STORAGE_BUFFER`.

You can access each attributes by asking OpenGL to generate them (like when you do instance rendering) or you can create a buffer of IDs.

After all this has been done you can do one OpenGL call draw everything you've batched.

---
Tags: opengl
---


# Question
Title: Multithreading in Gamedevelopment, specifically Networking
Let me quick explain my actual setup:

I use 2 Threads, one for networking and one for the main-loop (input, update, render). I have two synchronized queues, one for mainthread-\>networking and one for networking-\>mainthread. When a chunk of bytes arrives, the network-thread decodes a paket. The network-code knows, what each paket is and what it does. It now creates a functor to change the coordinates of an entity, to spawn a new one, or something else. It emplaces this functor in the queue and the main-tread executes every tick all the functors in the queue.

This kinda works for now, but i think i have to change this completely. I might split up some parts of the main-thread, input for example, and stick it in another thread. Also, i might want to add support for plugins written in lua, python or some other language, and i don't want the main-thread to get stuck when the plugin decides to run a long-running task. This would mean, eventually the main thread has to handle a decent number of queues, one for every thread plus one extra for the other direction (thread-\>main). Also, at the moment, the networking needs to have all the pointers to the data-structures it wants to control (For example, it has a ptr to the entitymanager stored, so it can create a functor to spawn a new entity in the entitymanager), thats kinda weird.

Are there common techniques to synchronize threads better? Especially since i have to provide a lot more control over the gamestate and still need to synchronize the other threads with the main-thread, i don't really see a better approach other then the functor-queue, so i hope for some suggestions.

# Answer
> 1 votes
Multithreading in games has always been a difficult thing, hence there are many ideas as how to get stuff done.
I would advice you to use one main thread which is dedicated for drawing and updating entities only (no heavy algorithms or calculations) and one or more (depending on the number of logical CPU cores available) threads which work on AI, physics, etc.
Depending on your needs, you can change that base model. You could for example even make a thread pool, which works on little tasks which you feed to it (which might feel a little like async JavaScript) and then have your main thread render the result. Or you could set constant drawing intervals and have physics, AI,... calculated continously in other threads.
How you go about it heavily depends on what you want to achive and what is the best fit for your scenario.

---
Tags: multithreading
---


title: How do I start and stop a GLSL shader?

text:
# Question
Title: How do I start and stop a GLSL shader?
Is there a way to start and stop a shader?.

I want to use this shader to sweep once over my texture and then stop. Does anybody know how to do that?

```
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
    vec2 r = fragCoord.xy / iResolution.xy;
    r.y = 1.0 - r.y;

    vec4 tex = texture2D(iChannel0,r.xy);
    tex += vec4((sin((r.y)+r.x + iGlobalTime*3.)) + tex)/2.;

    fragColor = tex;
}

```

# Answer
No, that's not how shaders work.

If you want to use a shader to manipulate a texture, you need to set up a render-to-texture operation. Create a result texture, bind it as the render target, bind your input texture as a regular input texture, and bind the shader you want to execute "once."

Render a fullscreen quad mapped with the input texture using the desired shader, and the result will be in the output texture which you can use in subsequent draw operations of real geometry.

Note, however, if you're trying to use this technique to animate the textures on otherwise regular geometry, it is not the most efficient way to do that; better would be to adapt the shaders used for the actual geometry to also include the effect you are trying to animate directly into the texture, as it would require far less resource management and state shuffling, which can be expensive and/or tedious.
> 1 votes

# Answer
no, you cannot stop shaders. That would break the render pipeline and as a result you would break rendering.
Doing such a sweep is simply setting the uniforms to the needed values from your application (for ex. incrementing the texture position values on each iteration). Inside your application, you know the size of the underlying object and can stop using that shader program once the sweep is done.
> 0 votes

---
Tags: opengl, shaders, glsl
---


# Question
Title: How should I render multiple objects in OpenGL?
I am just getting my head wrapped around modern OpenGL. Let's say that I would like to draw 10 objects, how would I structure that? Would I call `glDrawElements(...)` in a for loop 10 times?

```
void render() {
  shader.bind(); // calls glUseProgram
  bindVAO();     // calls glBindVertexArray

  for(int i = 0; i < 10; i++) {
    glDrawElements(....)
  }

  unbindVAO;
  shader.unbind();
}

```

# Answer
Maybe.

Broadly, there are two ways to categorize geometry (triangles you will render):

* either the geometry is *static*, and all sits in the same fixed place in the world, or the geometry is *dynamic* and either moves around in the world or otherwise animates
* the geometry is defined according to a specific vertex format (*this* geometry has a position, normal, and four texture coordinates, *that* geometry has a position, color, and one texture coordinate).

In practice you'll end up with a mixed bag of all kinds of geometry, and it will fall along various points in the spectrum defined by those categories. Where it falls determines how you can most-efficiently render it -- although keep in mind that the most objectively efficient approach is not always the overall best idea.

Geometry that differs in vertex format *generally* needs to be contained within its own buffer, and you'll generally need at least one buffer for each kind of vertex format, so you'll generally need at least one set of binding setup and `glDrawElements` calls for each of those buffers.

Geometry that is totally static, or which all can share the same bind setup for shaders, uniforms (world transform et cetera), can all be lumped into one large buffer and rendered in a single draw call, even if that buffer contains what you'd logically consider many objects. For example, in an RTS game that has a bunch of rocks and other ground clutter which is purely decorative and static, you could put all the rocks in one buffer and render them with one call.

Geometry that is dynamic, and must be updated or animated or otherwise use different bind setup for uniforms, generally will need one draw call for every set of distinct bind setup; note that multiple objects make still share a draw call here, in some cases. You may or may not be able to get away with storing all these objects in one buffer, as well.

You're always going to have to make a choice between various methods depending on the needs of your game. For example, in my aforementioned "rocks" example, it may still be worth breaking the rocks into multiple buffers if your map is large enough so you don't bother rendering objects that aren't even remotely visible.

When you are just learning, it is better to start off simpler. A default of "one buffer and one draw call" per object is not the most efficient but it should be *efficient enough* for quite a while for early forays into the world of OpenGL; once you are more comfortable you can start to explore ways in which you can divorce buffers and draw calls from that 1:1 relationship with logical objects.
> 7 votes

---
Tags: opengl, rendering
---


# Question
Title: How can I create animated card graphics like in Hearthstone?
In the game Hearthstone, there are cards with animated images on them. A few examples:

1. http://www.hearthhead.com/card=281/argent-commander
2. http://www.hearthhead.com/card=469/blood-imp

The animations seem to be composed of multiple effects:

* Particle systems.
* Fading sprites in and out/rotating them
* Simple scrolling textures
* A distortion effect, very evident in the cape and hair of example 1.
* Swirling smoke effects, the light in example 1 and the green/purple glow in example 2.

The first three elements are trivial, what I'd like to know is how the last two could be done. Can this even be done realtime in a game, or are they pre-rendered animations?

# Answer
> 7 votes
I don't know if its relevant any more, But Doug answer's got it right

I just wanted to add that I myself managed to recreate the animations exactly as they are built in the game it self using the same assets, take a look here

Magni:

```
precision highp float;

uniform float uTime;
uniform sampler2D uSampler0;
uniform sampler2D uSampler1;
uniform sampler2D uSampler2;
uniform sampler2D uSampler3;
uniform sampler2D uSampler4;
uniform sampler2D uSampler5;
varying vec2 texCoords;

void main(void) {
  float t = uTime;
  vec3 mask = texture2D(uSampler1,texCoords).rgb;
  vec4 img = texture2D(uSampler0,texCoords);
  img.rg*=1.1;
  vec2 flow = texture2D(uSampler3,texCoords).gr;
  flow.y+=t*3.;
  vec4 plas = texture2D(uSampler2,flow*1.2) * mask.r;
  plas *= 15.5;
  plas *= vec4(0.239, 0.224,0.488,1.);
  vec2 ct = texCoords;
  ct.y -=t*0.5;
  vec4 clouds = texture2D(uSampler4,ct*2.);
  float clouds_a = clouds.a;
  clouds *= 4.5;
  clouds *= vec4(0.275,0.23,0.161,1.);
  clouds_a *= mask.b;
  img += clouds * mask.b;
  img += plas * mask.r ;
  img += (sin(t*15.)+1.) * mask.g * vec4(0.239, 0.224,0.488,1.)*2.;
  ct.x += t * 0.5;
  vec4 clouds_overall = texture2D(uSampler5,ct  * 0.5);
  clouds_overall *= vec4(0.275,0.23,0.161,1.);
  gl_FragColor = img +clouds_overall;
}

```

Medivh:

```
precision highp float;

uniform float uTime;
uniform sampler2D uSampler0;
uniform sampler2D uSampler1;
uniform sampler2D uSampler2;
uniform sampler2D uSampler3;
uniform sampler2D uSampler4;
uniform sampler2D uSampler5;
varying vec2 texCoords;

void main(void) {
  float t = uTime;
  vec2 tc = texCoords;
  tc.x-=t*2.;
  vec4 mask = texture2D(uSampler1,texCoords);
  float bump = texture2D(uSampler4,tc*0.5).r;
  vec4 img = texture2D(uSampler0,vec2(texCoords.x,texCoords.y+bump* 0.055 * mask.g));
  tc = texCoords;
  tc.x-=0.05;
  tc.y+= 0.05;
  vec2 flow = texture2D(uSampler3,tc).rg;
  flow.y+=t;
  flow.y*=2.;
  vec4 plasma = texture2D(uSampler2,flow*1.5);
  plasma.rgb *= vec3(0.52,0.26,0.54);
  plasma *= 3.;
  flow = texture2D(uSampler5,texCoords).rg;
  flow.g+=t;
  vec4 plasma2 = texture2D(uSampler2,flow);
  plasma2 *= 4.;
  plasma2.rgb *= vec3(0.52,0.26,0.54);
  gl_FragColor =img+plasma*mask.r+bump*mask.a*0.35+plasma2*mask.b;
}

```

# Answer
> 4 votes
Some ideas come to mind and their implementation will depend entirely on the engine, tools, and, finally, the work and content pipeline.

## Sprite animation

1. Create the animation using tools like Photoshop and After Effects
2. Render frame by frame into an atlas (sprite sheet)
3. Apply the animation by code
4. Render the card layout on top of that using the proper masking or transparent background if needed.

## Video animation

1. Create the animation using tools like Photoshop and After Effects
2. Export that video into a format readable by the game engine
3. Play the animation by code
4. Render the card layout on top of the video using the proper masking or transparent background if needed

## In-Engine animation

1. Create all the assets for the animation using tools like Photoshop
2. Create the card model inside the engine with all the assets needed
3. Animate using the engine using its custom animation editor and save it
4. Play animation by code when necessary

These are the three types of animation that I know of and I've worked with. There are pros and cons for each one, and in this particular case I'm more inclined to sprite and video animation, because they're less GPU-intensive.

In cases like this one, the simplest approach is probably the right approach.

# Answer
> 2 votes
Both 4&5 are done by UV scrolling a texture over the area, maybe having a mesh over the card that's slightly distorted (in a static way). The blood imp seems to also have a second texture that multiples the first texture and does not UV scroll.

On the whole, they aren't expensive effects. They just aren't as good as they look first glance.

# Answer
> 1 votes
* One way to do that is to just use a video in place of a texture. That video will have to be prepared beforehand and will need to be looping.
* Another way is to have the whole "character, particles, cape moving" scene rendered into a buffer that later in the frame rendering gets used in place of the texture.

I do not have any experience on how to achieve these two solutions in a 3D engine but I think that both are possible in a 2D engine (I think I can make this work in MOAI for example).

# Answer
> 0 votes
Nearly all the effects can be achieved with 2D skeletal animation tools such as Spine. A sprite is basically a texture on a 2D mesh. The mesh is then transformed to make the cape move etc.
Check out the demo reel for examples of such effects. http://esotericsoftware.com/spine-in-depth#Features there are runtimes for most common engines/languages. A similar tool is Spriter: http://www.brashmonkey.com

---
Tags: graphics
---


# Question
Title: libGDX: Why doesn't Gdx.input.isKeyJustPressed() work?
I'm trying to use the method Gdx.input.isKeyJustPressed() to check if the Android BACK button was just pressed. I don't want to use the Gdx.input.isKeyPressed method to avoid multiple calls. Here is my code:

```
public void handleInput() {
    if(Gdx.input.isKeyJustPressed(Input.Keys.BACK)) {
         // show previous screen...
    }
}

public void update(float dt) {
    handleInput();
}

```

But unfortunately this doesn't work. Any ideas?

# Answer
Below code works for me, I get the message when pressing the back button.

```
if (Gdx.input.isKeyJustPressed(Input.Keys.BACK))
        {
            Gdx.app.log("Debug", "Back pressed!");
        }

```

Are you calling below method before the one above?

```
    Gdx.input.setCatchBackKey(true);

```
> 1 votes

---
Tags: java, libgdx, input
---


# Question
Title: Traversing a pre-defined path with a delay in SFML - C++
I want the player to move smoothly & slowly through a vector of co-ordinates that define a path, below is an illustration of what i mean.

```
[P][ ][ ][ ][ ]
[.][ ][ ][ ][ ]
[.][ ][ ][ ][ ]
[.][ ][ ][ ][ ]
[.][.][E][ ][ ]

```

Once the path has been found the player should move between each tile with a visual delay, i have tried to code this behavior in a variety of ways but it seems that this a problem created by running Update/Render on the same thread, i think?

Here is what i tried

```
 if (pathFound)
 {
    for (auto path : waypoint_queue)
    {
        Move(this->character.getPosition(), path)
    }
    waypoint_queue.clear();
    pathFound = false;
} else {  }

```

Running this without a delay in an attempt to lerp between the co-ordinates of each "Next Tile" essentially teleports the player to the final node.

Running this with a delay of 1s for 10 tiles halts the program for 10 seconds then teleports the player to the final node.

How do i go about producing C#-like co-routine behavior that can update variables with a timed delay whilst also rendering them?

Thanks

# Answer
> 1 votes
So @tkausl's answer worked, the player now moves smoothly along the predefined path, here is the updated code:

Edit: Bonus WebM of it working

```
if (pathFound)
{
    // A path has been found
    const float unitsPerTick = 8; // Speed in Units per tick
    auto waypoint = waypoint_queue.front(); // The waypoint in use

    Vector2i movementVector = Vector2i(waypoint.x - this->character.getPosition().x,
        waypoint.y - this->character.getPosition().y);

    float moveVecLength = sqrt((movementVector.x * movementVector.x) + (movementVector.y * movementVector.y));

    if (moveVecLength < 0.2)
    {
        /// Move the player by the movement vector
        this->character.setPosition(this->character.getPosition().x + movementVector.x, this->character.getPosition().y + movementVector.y);
        waypoint_queue.pop_front();
    }
    else {
        /// Normalize the movement vector
        movementVector.x = movementVector.x / moveVecLength;
        movementVector.y = movementVector.y / moveVecLength;

        /// Scale the movement vector by the units per tick
        movementVector = Vector2i(movementVector.x * unitsPerTick, movementVector.y * unitsPerTick);

        /// Move the character by the new movement vector
        this->character.setPosition(this->character.getPosition().x + movementVector.x, this->character.getPosition().y + movementVector.y);
    }

    if (waypoint_queue.empty())
        pathFound = false;
}

```

# Answer
> 2 votes
Your problem is, you're applying **all** waypoints in the same frame, which makes the character appear at the last waypoint directly, without moving at all. What you have to do is take on waypoint per frame and move only this one step. Or, better yet, move **a bit** in direction of the first waypoint, then, if you're near enough, discard the first waypoint.

Pseudo-Code:

```
 if (pathFound)
 {
    const float unitsPerTick = 0.2; //Speed in Units per Tick
    auto waypoint = waypoint_queue->front();
    auto movevec = waypoint->getPosition() - this->character.getPosition();
    if (movevec->getLength() < unitsPerTick ) {
         this->character.move(movevec);
         waypoint_queue->pop();
    } else {
        movevec->normalize()->scale(unitsPerTick);
        this->character.move(movevec);
    }

    if(waypoint_queue->empty())
        pathFound = false;
} else {  }

```

Something like this should do what you want.

---

Edit: Since SMFL's vector class has no such methods here an example how to do the calculations yourself.

Scale a vector `somevector` by `x`

```
somevector *= x;

```

Length of a vector:

```
float length = sqrt(somevector.x * somevector.x + somevector.y * somevector.y);

```

Normalize a vector:

```
somevector /= length; //For length, see above

```

---
Tags: c++, path-finding, sfml
---


# Question
Title: How to send dynamic data to a vertex shader OpenGL ES 2 Android
I'm very new to Android development and OpenGL ES 2.0.

I have been working through a book called "OpenGL ES 2 for Android A Quick Start Guide" which has been useful, but at times I get a bit lost as it doesn't explain some topics in enough depth in my opinion.

I currently have a vertex\_shader.glsl file that looks like the following:

```
uniform mat4 u_Matrix;

attribute vec4 a_Position;
attribute vec4 a_Color;

varying vec4 v_Color;

//uniform double vehicleWidth;
//uniform double screenHeight;

void main() {
    v_Color = a_Color;

    gl_Position = u_Matrix * a_Position;
    //gl_PointSize = vehicleWidth * (2.0 / screenHeight);
    gl_PointSize = 15.0;
}

```

The parts that are commented out is what I wish to implement into the program. The vehicleWidth is something that will be a static value at the start of the page, but can change when the user inputs a different value for it. The screenHeight variable is the minimum value my camera can see in Google Maps. This value will change as often as the user changes the zoom level of the screen.

The information is being sent through two other classes: Color Shader Program

```
public class ColorShaderProgram extends ShaderProgram {
    // Uniform locations
    private final int uMatrixLocation;

    // Attribute locations
    private final int aPositionLocation;
    private final int aColorLocation;

    public ColorShaderProgram(Context context){
        super(context, R.raw.simple_vertex_shader,
            R.raw.simple_fragment_shader);
        // Retrieve uniform locations for the shader program.
        uMatrixLocation = glGetUniformLocation(program, U_MATRIX);
        //Retrieve attribute locations for the shader program.
        aPositionLocation = glGetAttribLocation(program, A_POSITION);
        aColorLocation = glGetAttribLocation(program, A_COLOR);
    }

    public void setUniforms(float[] matrix){
        // Pass the matrix into the shader program.
        glUniformMatrix4fv(uMatrixLocation, 1, false, matrix, 0);
    }

    public int getPositionAttributeLocation() {
        return aPositionLocation;
    }

    public int getColorAttributeLocation() {
        return aColorLocation;
    }
}

```

And the Shader Program:

```
public class ShaderProgram {
    // Uniform constants
    protected static final String U_MATRIX = "u_Matrix";
    protected static final String U_TEXTURE_UNIT = "u_TextureUnit";

    // Attribute constants
    protected static final String A_POSITION = "a_Position";
    protected static final String A_COLOR = "a_Color";
    protected static final String A_TEXTURE_COORDINATES = "a_TextureCoordinates";

    // Shader program
    protected final int program;
    protected ShaderProgram(Context context, int vertexShaderResourceId,
                        int fragmentShaderResourceId){
        // Compile the shaders and link the program.
        program = ShaderHelper.buildProgram(
            TextResourceReader.readTextFileFromResource(
                    context, vertexShaderResourceId),
            TextResourceReader.readTextFileFromResource(
                    context, fragmentShaderResourceId));
    }

    public void useProgram() {
        // Set the current OpenGL shader program to this program.
        glUseProgram(program);
    }
}

```

My question is, how do I set up the vertex\_shader.glsl file so that I can send in dynamic information every time it renders?

**EDIT:** Also, how would I alter my ColorShaderProgram/ShaderProgram classes to allow me to send dynamic information into the GLSL file?

# Answer
You're already halfway there since you send matrix data every frame.

A little bit of history. `attribute`s used to be called `varying` because their value varies depending on the vertex in the buffer. `uniform`s are called such because their data is uniform across every vertex of the buffer. Since your matrix is `uniform` the GPU can handle it being changed at runtime since it's just one blob of data for the whole buffer. See what I'm getting at? You're already changing your `uniform` matrix every frame. Your matrix is "dynamic".

So just do what you did with the matrix.

When you setup your shader, you can get the location of the `vehicleWidth` `uniform` in your shader with:

`uVehicleWidth = glGetUniformLocation(program, "vehicleWidth");`

Then in your `setUniforms` method you can just send the vehicle width with:

`glUniform1f(uVehicleWidth, vehicleWidth);`

Just make sure that `vehicleWidth` is actually updated every frame.

The `glUniformX` calls are documented here: http://docs.gl/es2/glUniform
> 1 votes

---
Tags: android, opengl-es2
---


# Question
Title: How can I improve the efficiency of my procedural terrain generation and smoothing?
I'm developing an algorithm that generates infinite procedural terrain. It is currently inefficient. How can I improve it?

The algorithm starts by generating a 16×16 height-map with simplex noise per terrain tile, then goes through a few "smoothing iterations" (averaging height relative to neighbors, and adjusting height to look connected).

# Answer
With Simplex noise, lower frequencies are smoother and higher frequencies are bumpier. The first thing to try is to use a lower frequency, and take out the smoothing step.

I have a rough demo here — use a lower freq start and freq range to see smoother noise, or use a higher freq start or range or see bumpier noise.
> 1 votes

# Answer
Always hard to answer a "best way" question, it really depends on what you want to generate.

But anyway, you say you are smoothing out the vertices in relation to it's neighbor. But the smoothing should already be done by the noise itself with the correct parameters. You can generate all kinds of noise patterns with multiple iterations of different parameters and just just build your map on that final noise result, whether that is a tile map with smooth gradients of color a map of blocks or voxels or a terrain mesh.
> 0 votes

# Answer
You could also not re-invent the wheel and use some already existing library for noise-generation.

I recommend libnoise2, which is highly optimized and uses SSE/2/3/4/AVX to speed up the process and does a great job. It also has multiple generators and multiple parameters which make later terrain varieties easier to implement.

You could also use libnoise, which has much more options, but is a bit slower.

Another way you can speed up your terrain generation is parallellism. Most CPUs already run 4 cores, so your gain can be well above 50%.
> 0 votes

---
Tags: performance, procedural-generation
---


title: How do I counteract FXAA blur?

text:
# Question
Title: How do I counteract FXAA blur?
FXAA is a cheap post processing anti-aliasing method which works great with deferred pipelines where traditional MSAA may not be a viable option. It's also easier to implement than alternatives such as SMAA.

Unfortunately, as a quick Google search will show, a lot of PC gamers hate it because even when setting the shader to its best quality settings it still adds a slight blur to the outputted image. This is particularly noticeable when a scene has textures with fine detail and/or small specular highlights.

Is there a way to counteract this blur without reintroducing significant aliasing?

# Answer
Coming from a graphic design background, one solution I usually use for making blurry images appear sharper is to overlay noise. Of course, adding random noise does not look good. The noise must be relevant to the underlying material. The classic case is making a material look weathered in Photoshop by using grunge textures and setting their layers to multiply/dodge/burn/etc.

So, how do we take the image outputted by the FXAA shader and extract some relevant noise? Again, Photoshop has the answer. Some of oldest effects in the program such as blur, sharpen, edge extract and emboss are created with what are known as convolution matrices.

The matrix we're interested in has various names, though I've always known it as 'edge extract' and it looks like this:

```
 0, 0, 0
-1, 1, 0
 0, 0, 0

```

To apply this effect we want to take the output of the FXAA shader as input and render a fullscreen quad. Then in the fragment shader we sample 9 texels with the fragment position at the centre. Multiply each sampled colour by the corresponding number in the matrix, then add all of these multiplied samples together. Below is a sample fragment shader written in GLSL that achieves this:

```
#version 330 core
out vec4 out_colour;
uniform sampler2D blit_map;
uniform vec2 screen_size;

void main()
{
    vec4 sum = vec4(0.0);
    vec2 offset[9] = vec2[](vec2(-1.0, 1.0), vec2(0.0, 1.0), vec2(1.0, 1.0),
                            vec2(-1.0, 0.0), vec2(0.0, 0.0), vec2(1.0, 0.0),
                            vec2(-1.0, -1.0), vec2(0.0, -1.0), vec2(1.0, -1.0));
    float kernel[9] = float[](0.0, 0.0, 0.0,
                             -1.0, 1.0, 0.0,
                              0.0, 0.0, 0.0);

    for (int i = 0; i < 9; i++)
    {
        vec4 colour = texture2D(blit_map, (gl_FragCoord.xy + offset[i]) / screen_size);
        sum += colour * kernel[i];
    }

    out_colour = sum;
}

```

If all goes correctly you should end up with something that looks like this (the original image was a height-mapped grassy terrain with some trees):

We now have some noise relevant to our underlying image, so lets add it back onto the original output we received from the FXAA shader.

```
#version 330 core
out vec4 out_colour;
uniform sampler2D blit_map;
uniform vec2 screen_size;

void main()
{
    vec4 sum = vec4(0.0);
    vec2 offset[9] = vec2[](vec2(-1.0, 1.0), vec2(0.0, 1.0), vec2(1.0, 1.0),
                            vec2(-1.0, 0.0), vec2(0.0, 0.0), vec2(1.0, 0.0),
                            vec2(-1.0, -1.0), vec2(0.0, -1.0), vec2(1.0, -1.0));
    float kernel[9] = float[](0.0, 0.0, 0.0,
                             -1.0, 1.0, 0.0,
                              0.0, 0.0, 0.0);

    for (int i = 0; i < 9; i++)
    {
        vec4 colour = texture2D(blit_map, (gl_FragCoord.xy + offset[i]) / screen_size);
        sum += colour * kernel[i];
    }

    float sharpen_amount = 0.25;
    out_colour = (sum * sharpen_amount) + texture2D(blit_map, gl_FragCoord.xy / screen_size);
}

```

You'll note we also scaled the sum before adding it onto the original colour. The blur caused by FXAA is subtle, therefore the sharpening should also be subtle so you'll want to keep the sharpening amount low.

You've probably noticed by now that this shader isn't as cheap as it could be. There are nine texture lookups, most of which add nothing to the final image as they're multiplied by zero. As a final step, let's optimize the shader.

```
#version 330 core
out vec4 out_colour;
uniform sampler2D blit_map;
uniform vec2 screen_size;

void main()
{
    vec4 colour = texture2D(blit_map, gl_FragCoord.xy / screen_size);
    vec4 sum = colour + (texture2D(blit_map, (gl_FragCoord.xy + vec2(-1.0, 0.0)) / screen_size) * -1.0);

    out_colour = (sum * 0.25) + colour;
}

```
> 5 votes

---
Tags: antialiasing, post-processing, blur
---


title: Android OpenGL EGL context lost

text:
# Question
Title: Android OpenGL EGL context lost
I'm developing simple Android game in OpenGL ES 2.0 and the development stage is getting closer to publishing game on play store, but I'm still unsure about EGL context behaviour on different devices.

GLSurfaceView Android documentation says:

> A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView \> clients are required to call onPause() when the activity pauses and onResume() when the \> activity resumes. These calls allow GLSurfaceView to pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate the OpenGL display.

Problem is that I don't want my game to recreate and reload all textures after every activity change or home button press, it really breaks user experience, so I don't invoke onPause and onResume methods on my GLSurfaceView in order to not loose my OpenGL assets. This approach works perfectly on some devices I've tested - Nexus 7 and Lenovo Yoga Tab 2, but I'm afraid it may cause some unexpected results on some specific devices. What are the drawbacks of this approach? Can I workaround EGL context lost in some other way?

I've read many resources about this subject but most of them are related to Android in version 2.x and were written 3-4 years ago. I'm targeting minimum API 16 which is Android 4.1.x, so maybe there are some new ways to work this out?

I did use some custom GLSurfaceView implementations as the one from Chris Pruett's game Replica Island but as I've said those workarounds were targetting older Android versions and still they didn't let me solve my problem. I was also trying using setPreserveEglContextOnPause method on GLSurfaceView but it doesn't seem to work.

# Answer
> 1 votes
It's not just the EGL Context that gets lost; Android can (and will) simply kill any application running in the background when it's running low on resources and needs to reclaim them. There's simply no guarantee that your app won't have been unloaded since you last left it.

> When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.
>
> Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.

Android documentation on stopping Activities

> In situations where the system needs more memory it may kill paused processes to reclaim resources. Because of this, you should be sure that all of your state is saved by the time you return from this function.

Android API onPause() method

Also, see the accepted answer to this question. The documentation on setPreserveEglContextOnPause indicates that it only works on devices that support multiple OpenGL contexts.

In short, you can't guarantee anything. Best to find another workaround.

---
Tags: opengl, android
---


# Question
Title: Is C++ "still" preferred in game development?
I am a 2D Game Programmer.Some programming languages which I am good at are C,Java ,C#. I also know Actionscript 2.0,3.0 and some javascript. I'm interested in learning 3D Game programming. So far from the research I have accumulated by googling and reading different game development forums and articles. I've noticed that most programmers tend to prefer C++.Also in an online game programming teaching course I noticed they prefer to teach C++ and Visual C++ as the starting course. The reason I am asking this question since I would like to know the "strength" difference of C++, C# and Java for 3d game programming.

Also include links to **good** 3d game programming articles for the already 2d game programmer.

P.S : IMHO , I also find C++ to be cryptic.

# Answer
> 30 votes
Yes, C++ is the language used most often (though some people do still use C).

There are numerous reasons for this. Sheer momentum is one - it's simply the language that has been used for years, a lot of tech already exists and people are comfortable with it, so changing is not going to happen overnight.

Then there is the issue of control. Game developers are control freaks, and we like to know everything that is going on in our code. C++ gives us that control, C# and Java (to pick on the two alternatives you mention) take control away. In many ways that might be a good thing, but game coders don't like it :)

Finally there's the simple practical issue that the SDKs for various platforms are very C++ centric. Using another language inevitably involves writing wrappers, cross-compiling down to VMs, and possibly (in the case of some console development) it's not allowed by the platform holder (they really don't like people doing JIT compiling, for a start).

# Answer
> 4 votes
C++ is still preferred as you can see on pretty much any publication on the topic of game development. I personally am currently using C for my diving into game development for the simple reason that the C++ code I write abuses templating features, uses RAII extensively, dynamic memory allocation and other things that you just should not do in game code from what I have seen so far.

Sticking to C forces me to be minimalistic and think about what I'm doing. It can be harder at times when you have to reimplement something the STL gives you for free, but on the upside I feel I write cleaner code and have a better time debugging that thing.

# Answer
> 1 votes
I'm personally not a fan of C++, and I prefer Java. However, most people in the industry do use it and it's the easiest language to convert to other platforms without wrappers and virtual machines.

However, sometimes other languages work out pretty good for game development. I use Java with LWJGL and it is amazing. So if you want to start with 3D programming and OpenGL without having to learn C++, try out LWJGL with Java, because it's very lightweight and I think it's actually C++ code running through JNI.

Maybe in the long run you might want to switch to C++, but you can start and practice with C# or Java. Because most game code comes from experience with the language, but you should try and practice OpenGL with a language you're comfortable with. Also, while you're practicing graphics, you should also try out GLSL with OpenGL, it has very C-like syntax

---
Tags: c++, 3d, game-industry
---


# Question
Title: Unity NGUI Arial Label looks different in iOS after updating Unity to 5.1.1
I am using NGUI and I have a UILabel. It uses Unity dynamic font Arial. Bold. No effects.

This is how it looks in the Unity editor:

And that's how I want it to look. When I build it in iOS, it looks the same. Great.

Then I updated Unity to 5.1.2. In editor it still looks the same, but now in an iOS build I get this:

The label looks different. It looks like a different font and style.

This line of code:

```
Debug.Log("Using " + label.trueTypeFont + "  " + label.fontStyle + " size " + label.fontSize);

```

And regardless of being in Unity's editor or the iOS device, I get this:

> Using Arial (UnityEngine.Font) Bold size 24

So apparently this is indeed Arial. And the size is supposedly the same. Then, what is wrong?

This occurs on all iOS devices I use (iPhone 6+, iPhone 6, iPad Mini 3, etc...) with the latest iOS version. I also have the latest NGUI. I think it was the Unity update itself.

What happened? What do I do? I want the old look. I suppose that I can grab an older Unity and use one of my backup projects, but this new Unity actually has several fixes I'd like to have so...

**Edit**: Confirmed that Unity 5.0.1 doesn't have this problem. It occurs in newer versions like 5.1.1.

# Answer
Solved a similar issue on Android Unity 5.1.1 by removing and re-importing the actual font file into my project. Also have seen problems when using just the default `Arial` font face without actually importing my own font asset into the project.

Do me a solid and try importing an actual Arial (or any other font for that matter) TTF or OTF into the scene and using that file in the reference for your next build. I think the problem relies either in Unity linking to its "included" version of Arial when building for mobile / tablet devices. At least that is what has worked for me in 5.0.1 and 5.1.1
> 1 votes

# Answer
Use BMFont to generate the font sprite atlas, and use that as an NGUI font, not a Unity font. Then you will get the exact look you want, instead of having version specific fonts.

There is a tutorial here on Youtube, showing how to use BMFont and import into NGUI.
> 0 votes

---
Tags: unity, ios, ngui
---


title: OpenGL calls from a different thread?

text:
# Question
Title: OpenGL calls from a different thread?
I understand OpenGL is not thread-safe, but at the same time, Google seems to be giving me mixed responses.

---

I have a LibGDX game that functions normally, UI/rendering/logic on the same thread, everything is happy.

However, at a certain point, the user can initiate a process which involves a progress bar and lots of **slow rendering** (to off-screen FBOs). Right now I'm doing this on that one single thread, resulting in locking-up of the UI. I currently break out of the loop periodically in order release the lock on the UI every now and then.

**What I'd like to happen** is for another thread to be created at this point, and for all of the slow rendering to happen on it while the main UI/rendering/logic thread just displays a progress bar (without locking up of course).

---

**Since both threads will be using OpenGL at the same time, is this possible?**

# Answer
An OpenGL context may be current on at most one thread at a time. If you make a context current in one thread, it will be made uncurrent in the previous thread. So while you can migrate contexts between threads, you can not do so in any concurrent manner.

While there is the existence of shared contexts and shared resources, those are not exactly in the fast path and you'd need to do some work to get them set up, if at all available.
> 2 votes

# Answer
**tl;dr: NO.**

Long answer:
As @LarsViklund pointed out, you will have significant trouble using multiple threads to render. OpenGl is kinda bad at multithreading, so don't.
If your rendering is slow **it's not because of slow OpenGL calls.** Your architecture is just bad. You can improve it by moving away all your logic (UI events, physics, AI,...) from your rendering thread. That way, there will be more frequent updates and your UI will not lock up. Also the overall experience wil be a lot smoother. There are many models for multithreading.
Maybe also take a look at my answer about multithreading: Multithreading in Gamedevelopment, specifically Networking
> 2 votes

# Answer
Alternatively, you can break up your long, slow render parts to intersperse with your UI updates.

Slow part takes too long? Break it into multiple draws. Each draw is still too long? Fill a smaller area.

It might be a little bit inside out, but it's a way to do it all in one thread.
> 1 votes

# Answer
My understanding is that the goal is to have a background "high quality render" while still updating an on-screen progress bar and eventually producing a still image from the background process.

The easiest way to do this will probably involve having two separate OpenGL contexts, each set as 'current' on one thread.

The first one renders your progress bar (or whatever else is needed) to the main screen, from your UI thread, as normal.

The second context handles your lengthy rendering process from a background thread, and renders into an FBO.

These may or may not be shared contexts. If they're shared contexts, they can share model data (ie: the second context can render using VBOs, textures, etc. created in the first context, which may be useful depending on your application), but this will make rendering slower in both contexts, primarily due to driver-imposed memory fences around that shared data. On the other hand, you'll be able to convert the rendered image directly into a texture that will be accessible to the first context, without pulling the data back to the CPU.

If they're not shared contexts then rendering will be somewhat quicker, but you'll need to separately load any required model data into the second context, and you'll need to pull the final rendered image back to the CPU and then explicitly load it into the first context as a texture, so that it can be used from there.

To get the final rendered image to the screen using shared contexts, you just need to either convert the FBO contents into a glTexture; that glTexture will be available from the first context (once synch has completed between the two contexts).

If not using shared contexts, then use glReadPixels() to get the rendered pixels back out of the second context, and then use those pixels to create a texture inside the first context.

Either way, you're left with a texture of the rendered scene that you can use from within the first rendering context; the one that's rendering to the main screen.
> 1 votes

---
Tags: opengl, java, multithreading
---