# Question
Title: glGetProgramInfoLog returning empty string while glGetProgramiv claims that the program did not successfully link
I am currently trying to write a basic program using OpenGL 3.3, and I am encountering an issue: glGetProgramInfoLog is returning an empty string while glGetProgramiv is saying that there is an error when linking my shader program.

The problematic code follows:

```
//load shaders
GLuint vertexShader = loadShader("shader.vert", GL_VERTEX_SHADER);
GLuint fragmentShader = loadShader("shader.frag", GL_FRAGMENT_SHADER);

//link program
programId = glCreateProgram();
glAttachShader(programId, vertexShader);
glAttachShader(programId, fragmentShader);
glLinkProgram(programId);

//check for errors
GLint success = 5; //for debugging to make sure it wasn't 0 by default and glGetProgramiv wasn't writing to it
glGetProgramiv(programId, GL_LINK_STATUS, &success);
if(!success){
    GLchar infoLog[1024];
    glGetProgramInfoLog(programId, 1024, nullptr, infoLog);
    throw std::runtime_error(std::string("Failed to link OpenGl shader program material: ") + infoLog);
}

//delete shaders
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);

```

When I attempt to run my program, the runtime\_error is thrown with the following termination message:

```
terminate called after throwing an instance of 'std::runtime_error'
  what():  Failed to link OpenGl shader program material:

```

I confirmed through my debugger that the `success` variable is bring written to (see comment in code), and that glGetProgramInfoLog is writing the first byte of infoLog to all zeroes, thus making it a null-terminated string of length 0.

What am I doing incorrectly here?

Information:
GPU: Nvidia GTX 1070
OS: Ubuntu Linux 17.10 x64
Display server: Xorg
Driver version: 384.111 (latest in official Ubuntu repositories)
Compiler: g++ (Ubuntu 7.2.0-8ubuntu3) 7.2.0
Kernel Version: 4.13.0-25-generic
Windowing Library: SFML version 2.4.2+dfsg-4 (as described here) (version from apt-cache policy command)

Things I have tried:

* Modifying error checking code to check `GL_INFO_LOG_LENGTH`, which returns 0 despite GL\_LINK\_STATUS returning GL\_FALSE (also 0.
* Compiling the program and testing on Windows 10 running on the same hardware, since I don't have access to any sufficiently different gpu for better testing, in an attempt to rule out a driver error that may only exist on Linux. The same thing happens on Windows.

I have also posted this question to reddit, where no useful answers came up (link).

Full program source:

```
#include <SFML/Window.hpp>
#include <GL/glew.h>
#include <fstream>
#include <sstream>
#include <iostream>

void init();
void update();

GLuint loadShader(const std::string &shaderPath, GLenum shaderType);

sf::Window window;
GLuint programId;
GLuint vbo, vao, ebo;

int main(){
    init();
    while(true){
        update();
    }
}

void init(){
    sf::ContextSettings settings;
    settings.antialiasingLevel = 0;
    settings.majorVersion = 3;
    settings.minorVersion = 3;

    window.create(sf::VideoMode(1600, 900), "PerlinGl", sf::Style::Default, settings);
    window.setActive(true);

    if(glewInit() != GLEW_OK){
        throw std::runtime_error("Failed to initialize GLEW.");
    }

    //load shaders
    GLuint vertexShader = loadShader("shader.vert", GL_VERTEX_SHADER);
    GLuint fragmentShader = loadShader("shader.frag", GL_FRAGMENT_SHADER);

    //link program
    programId = glCreateProgram();
    glAttachShader(programId, vertexShader);
    glAttachShader(programId, fragmentShader);
    glLinkProgram(programId);

    //check for errors
    GLint success = 5;
    glGetProgramiv(programId, GL_LINK_STATUS, &success);
    if(!success){
        GLchar infoLog[1024];
        glGetProgramInfoLog(programId, 1024, nullptr, infoLog);
        throw std::runtime_error(std::string("Failed to link OpenGl shader program material: ") + infoLog);
    }

    //delete shaders
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    //setup "mesh"
    GLfloat vertices[] = {
            -1.0f, -1.0f, 0.0f,
            1.0f, -1.0f, 0.0f,
            1.0f, 1.0f, 0.0f,
            -1.0f, 1.0f, 0.0f
    };
    GLuint indices[] = {
            0, 1, 2,
            2, 3, 0
    };

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glGenBuffers(1, &ebo);

    glBindVertexArray(vao);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), reinterpret_cast<void*>(0));
    glEnableVertexAttribArray(0);
}

void update(){
    sf::Event event;
    while(window.pollEvent(event)){
        switch(event.type){
            case sf::Event::Closed:
                std::terminate();
                break;
        }
    }

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    window.display();
}

GLuint loadShader(const std::string &shaderPath, GLenum shaderType){
    //load source
    std::ifstream fin(shaderPath);
    std::ostringstream sout;

    while(fin){
        std::string line;
        std::getline(fin, line);
        sout << line << std::endl;
    }

    std::string shaderSource = sout.str();
    const char *shaderSourceCString = shaderSource.c_str();

    std::cout << "Shader source: " << shaderSource << std::endl;

    //create shader
    GLuint shader = glCreateShader(shaderType);
    glShaderSource(shader, 1, &shaderSourceCString, nullptr);
    glCompileShader(shader);

    //test for errors
    GLint success;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
    if(!success){
        GLchar infoLog[1024];
        glGetShaderInfoLog(shader, 1024, nullptr, infoLog);
        throw std::runtime_error("Failed to compile OpenGl shader (" + shaderPath + "): " + infoLog);
    }
}

```

# Answer
I managed to find the error (I should have turned on compiler warnings. that would have saved a lot of trouble). It turned out I was missing a return statement in my `loadShader` function. I finally found it by comparing line-by-line to a working piece of code on the Internet.
> 1 votes

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


# Question
Title: How to calculate how much revenue a game will make?
Let's say I've made a game X.

Things we know about the game:

* It's a board game
* Game will run on PC, Macs, iOS and Android
* Sold through Steam, App Store and Google Play store
* Turn based
* Has few to none competitors on the market
* High-quality art
* Peer reviews and impressions (100 paid impressions) rate this game as 84/100.
* Game is available in 10 world most used languages.
* Game will be advertised through Twitter, Facebook and through bought impressions.

How can I estimate the money the game will make? What it takes for a developer to make an educated guess?

To be clear, I'm not asking anyone to calculate the revenue, rather - how to calculate it myself, what data to look for etc.

# Answer
You can only make educated guesses at this - your revenue will be tied directly to the number of copies of the game you sell, and if there were a way to compute *that* with any accuracy, we'd all be much richer.

Most companies (it's usually publishers, specifically, that do this) do what is essentially market research. They mine data from as many sources as they can, public and private, to get any idea of how well games with similar features did on similar platforms at similar times of the year. If a company has released a similar product themselves, they'll have that specific market data to draw upon, as well.

Today, the indie boom has made this a little easier to do, because there's more publically-available data floating around. SteamSpy, for example, while not perfect, is much better than anything that was available to the small-time developer twenty years ago. Many indies are much more open about their successes (or failures) post-launch, as well, and you can often find postmortems by developers that detail some sales information. For example, the developer of Cogmind (not at all similar to your game) published recaps of year one and year two of the life of his game. If you search around, you may be able to find similar postmortems from developers of games like yours.

Outside of correlative data like the above, you can use more direct numbers from other ways users have engaged with your game before release (if you have them). For example, does your game have a Twitter account? How many followers does it have? How many mailing-list sign-ups do you have? YouTube views or subscriptions to your developer logs? Et cetera. That kind of pre-ship engagement traffic can help give you rough estimates of the order of magnitude (at least) of what your sales could be. Provided you don't turn everybody off with a bad price point, of course.
> 2 votes

---
Tags: business
---


title: Unity: Creating a Plane from 3 Vectors

text:
# Question
Title: Unity: Creating a Plane from 3 Vectors
https://docs.unity3d.com/ScriptReference/Plane-ctor.html

> public Plane(Vector3 a, Vector3 b, Vector3 c); Description: Creates a plane.
>
> The resulting plane goes through the given three points. The points go around clockwise as you look down on the top surface of the plane.

Since there is no Debug.DrawPlane I don't know whether my plane works as expected. Are all 3 Vectors world coordinates? Or are they connected to each other? Can somebody elaborate how this works? Neither can I make any sense of "The points go around clockwise as you look down on the top surface of the plane"

# Answer
> 3 votes
Any three points in space describe a plane that passes through *all* of those points. The points are not "connected" except in the sense that they all lie on the plane you want to describe.

The plane is in the same space that coordinates are, so if you provide world-space coordinates, the plane will be in world space.

The ordering (or winding) of the points, the part that says "the points go clockwise as you..." indicates how the front and back "sides" of the plane are determined. A plane divides 3D space into two halves, determining which side of the plane is the "front" (or top) lets us reliably talk about those two spaces.

What the clockwise bit is saying is... say you have these three points and called `Plane(p0, p1, p2)`:

```
   p1

p0            p2

```

Note how if you trace your finger from `p0` to `p1` to `p2`, your finger moves clockwise. Further you can curl the fingers of your left hand to follow that clockwise direction. When you do that, the direction you can stick your thumb out in represents the normal of the place, and points towards the front half-space of the plane. If you do that while holding your hand up to the monitor, your thumb is probably pointing at your face. Your face is "looking down" on to the "top surface" of this plane because you see the points forming a clockwise traversal.

Note that if you called `Plane(p2, p1, p0)` -- the opposite order -- and your curled the fingers of your left hand to follow that now-counter-clockwise traversal, your thumb would be pointing *towards* the screen. Your face would then be "looking up" at the "bottom surface" of the plane.

The most common reason to care about the front side of the plane is that that is the one things usually collide with. Generally we ignore collisions with the back side of planes, although you can certainly compute them if your game needs it. Often you will need to opt-in to doing so however, as many libraries may assume you just want collisions with the front side.

# Answer
> 4 votes
> Since there is no Debug.DrawPlane

Well, let's make our own tools to help us visualize it then.

```
// Mimics Debug.DrawLine, drawing a plane containing the 3 provided worldspace points,
// with the visualization centered on the centroid of the triangle they form.
public static void DrawPlane(Vector3 a, Vector3 b, Vector3 c, float size,
    Color color, float duration = 0f, bool depthTest = true) {

    var plane = new Plane(a, b, c);
    var centroid = (a + b + c)/3f;

    DrawPlaneAtPoint(plane, centroid, size, color, duration, depthTest);
}

// Draws the portion of the plane closest to the provided point,
// with an altitude line colour-coding whether the point is in front (cyan)
// or behind (red) the provided plane.
public static void DrawPlaneNearPoint(Plane plane, Vector3 point, float size, Color color, float duration = 0f, bool depthTest = true) {
    var closest = plane.ClosestPointOnPlane(point);
    Color side = plane.GetSide(point) ? Color.cyan : Color.red;
    Debug.DrawLine(point, closest, side, duration, depthTest);

    DrawPlaneAtPoint(plane, closest, size, color, duration, depthTest);
}

// Non-public method to do the heavy lifting of drawing the grid of a given plane segment.
static void DrawPlaneAtPoint(Plane plane, Vector3 center, float size, Color color, float duration, bool depthTest) {
    var basis = Quaternion.LookRotation(plane.normal);
    var scale = Vector3.one * size / 10f;

    var right = Vector3.Scale(basis * Vector3.right, scale);
    var up = Vector3.Scale(basis * Vector3.up, scale);

    for(int i = -5; i <= 5; i++) {
        Debug.DrawLine(center + right * i - up * 5, center + right * i + up * 5, color, duration, depthTest);
        Debug.DrawLine(center + up * i - right * 5, center + up * i + right * 5, color, duration, depthTest);
    }
}

```

Or, if you want to play with planes interactively, you can drop this script into an empty scene and toy with its position & inspector parameters to visualize how they affect the geometry of the plane.

```
public class PlaneVisualizer : MonoBehaviour {

    public Vector3 a = Vector3.right;
    public Vector3 b = Vector3.up;
    public Vector3 c = Vector3.forward;

    void OnDrawGizmos() {
        var plane = new Plane(a, b, c);

        // Draw our three input points in world space.
        // b and c are drawn as lollipops from the preceding point,
        // so that you can see the clockwise winding direction.

        Gizmos.color = Color.white;
        Gizmos.DrawWireSphere(a, 0.1f);

        Gizmos.color = Color.gray;
        Gizmos.DrawLine(a, b);
        Gizmos.DrawWireSphere(b, 0.1f);

        Gizmos.color = Color.black;
        Gizmos.DrawLine(b, c);
        Gizmos.DrawWireSphere(c, 0.1f);

        // Draw this object's position,
        // as a lollipop sticking out from our plane,
        // blue-green if in front (in the positive half-space),
        // and red if behind (negative half-space).
        Gizmos.color = plane.GetSide(transform.position) ? Color.cyan : Color.red;
        Gizmos.DrawLine(plane.ClosestPointOnPlane(transform.position), transform.position);
        Gizmos.DrawWireSphere(transform.position, 0.2f);

        // Draw plane normal.
        Gizmos.color = Color.yellow;
        var center = (a + b + c) / 3f;
        Gizmos.DrawLine(center, center + plane.normal);

        // Draw planar grid.
        Gizmos.color = Color.blue;
        var matrix = Gizmos.matrix;
        Gizmos.matrix = Matrix4x4.TRS(center, Quaternion.LookRotation(plane.normal), Vector3.one);
        for(int i = -10; i <= 10; i++) {
            Gizmos.DrawLine(new Vector3(i, -10, 0), new Vector3(i, 10, 0));
            Gizmos.DrawLine(new Vector3(-10, i, 0), new Vector3(10, i, 0));
        }
        Gizmos.matrix = matrix;
    }
}

```

---
Tags: unity, vector
---


# Question
Title: Converting Frame-Dependent Movement to Frame-Independent
I fine-tuned some movement physics for a 2D platformer in a frame-dependent manner and now I want to convert them to frame-independent.

I though this would be as easy as multiplying a few things by 60 (my FPS) and a few other things by a time delta.

Unfortunately, the resultant physics is not the same as the original, especially when I drop the frame rate from 60 fps to 30 fps.

Here's how the **frame-dependent** movement works in my `Player` class, simplified a bit for the purposes of illustration.

```
PLAYER_ACC = 1.5
PLAYER_FRICTION = -0.23
PLAYER_GRAV = 1.75
PLAYER_JUMP = 20

def get_input(self):
    if self.game.input("left"):
        self.acc.x = -PLAYER_ACC
    if self.game.input("right"):
        self.acc.x = PLAYER_ACC
    if self.game.input("up"):
        self.vel.y = -PLAYER_JUMP

def update(self):
    # reset acceleration
    self.acc = vec(0, PLAYER_GRAV)

    # process input
    self.get_input()

    # apply friction
    self.acc.x += self.vel.x * PLAYER_FRICTION     # The faster you're going, the more friction slows you down.

    # calculate velocity
    self.vel += self.acc

    # if the x-velocity approaches 0, set it equal to 0
    if abs(self.vel.x) < 1.5:
        self.vel.x = 0

    # downward velocity cap
    if self.vel.y >= 14:
        self.vel.y = 14

    # adjust position
    self.pos += self.vel + (PLAYER_GRAV * self.acc)    # Got this equation from a tutorial and I like how it feels.

```

Here's my attempt at making it **frame-independent**. My time delta is `self.game.dt`.

```
PLAYER_ACC = 1.5 * 60
PLAYER_FRICTION = -0.23
PLAYER_GRAV = 1.75 * 60
PLAYER_JUMP = 20 * 60

def get_input(self):
    if self.game.input("left"):
        self.acc.x = -PLAYER_ACC
    if self.game.input("right"):
        self.acc.x = PLAYER_ACC
    if self.game.input("up"):
        self.vel.y = -PLAYER_JUMP

def update(self):
    # reset acceleration
    self.acc = vec(0, PLAYER_GRAV)

    # process input
    self.get_input()

    # apply friction
    self.acc.x += self.vel.x * PLAYER_FRICTION    # The faster you're going, the more friction slows you down.

    # calculate velocity
    self.vel += self.acc * self.game.dt

    # if the x-velocity approaches 0, set it equal to 0
    if abs(self.vel.x) < 1.5 * 60:
        self.vel.x = 0

    # downward velocity cap
    if self.vel.y >= 14 * 60:
        self.vel.y = 14 * 60

    # adjust position
    self.pos += (self.vel + (PLAYER_GRAV * self.acc)) * self.game.dt

```

Unfortunately, the resultant physics did not feel the same as my original. Especially when I drop the frame rate from 60 fps to 30 fps.

I was thinking that maybe when I apply the friction to the acceleration, I need to raise it to the time delta, but this didn't help either. I am working at a small resolution (640x360) and I'm not sure if this is impacting anything.

My question is: **How can I convert my current physics to frame-independent?**

There are a few questions similar to this on Game Dev SE already, but none of them has led me to a solution.

# Answer
> 2 votes
There are two main ways of doing frame independent update loops. I highly recommend reading through and understand this: Fix your timestep!

What you are trying to do is a variable timestep update loop, which can work, but it will be non deterministic, as in it might look like that it is frame-rate independent but error will be introduced depending on the frame rate frequency (less FPS, more error). It is best used in systems that produce data that are self-contained and no other systems rely on them. Particle systems or cloth simulation can be such, because they usually have no physical impact on the game world and are purely visual.

For gameplay and physics simulations what usually is recommended practice is the fixed timestep update loop. The basic idea is that you have a predetermined (fixed) amount of simulation resolution for a unit time period. Your fixed timestep resolution is one simulation step per 1/60 seconds, so 60 simulation steps per second. If your overall performance drops to 30 FPS that means that you have to update twice the amount with the same fixed timestep resolution, so 120 simulation steps per second. Basically:

```
static float accumulator = 0.0f; // this is a static or global variable
accumulator += game.elapsedTimeSincePreviousFrameInMilliseconds;

while(accumulator >= 1.0f/60.0f)
{
  UpdateGame();
  accumulator -= 1.0f/60.0f;
}

```

The above code demonstrates a simple case and can be refined further to accumulate for leftover time from the previous update, but that is more involving than to post here. The above mentioned link has all you need, basically.

---
Tags: 2d, physics, movement, frame-rate, timestep
---


# Question
Title: Making Minecraft in 2D. Blocks move when player moves
I want to make a 2D Minecraft game and I have drawn the grass blocks and you can dig but when the palyer moves the dirt moves too. It draws on every block wich the player touches a dirt block because I said that it has to draw it on r.getX() and r.getY() and it changes every time the player moves. Could someone please help me?

This is my code.

```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Gameplay extends JPanel implements ActionListener, KeyListener, MouseListener{
public BufferedImage player;
public BufferedImage grass;
public BufferedImage dirt;
private BufferedImage dbImage;
private Graphics dbg;
private int x = 0;
private int y = 0;
private double velX = 8.0f;
private double velY = 8.0f;
public Rectangle rectangle;
public Rectangle rectangle2;
public Rectangle MouseRect;
public boolean BlockD = false;
public ArrayList<Rectangle> blockList = new ArrayList<Rectangle>();
private int[] xb = {0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650};
private int[] yb = {0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650};
//
public Gameplay(){
    addMouseListener(this);
    addKeyListener(this);
    setFocusable(true);
    try {
        player = ImageIO.read(getClass().getResource("Player.png"));
        grass = ImageIO.read(getClass().getResource("Grass.png"));
        dirt = ImageIO.read(getClass().getResource("Dirt.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void paint(Graphics g){
    dbImage = (BufferedImage) createImage(getWidth(), getHeight());
    dbg = dbImage.getGraphics();
    paintComponent(dbg);
    g.drawImage(dbImage, 0, 0, this);
    repaint();
}

public void paintComponent(Graphics g){
    drawBlock(g);
    rectangle2 = new Rectangle(x, y, 35, 35);
    g.drawString("Jake", x, y);
    for(Rectangle r : blockList) {
        g.drawImage(dirt, (int) r.getX(), (int) r.getY(), this);
    }
    // Draw player after dirt blocks
    g.drawImage(player, x, y, this);
}

public void drawBlock(Graphics g){
    for(int first = 0; first < 10; first++){
        for(int second = 0; second < 10; second++){
            g.drawImage(grass, xb[first], yb[second], this);
        }
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_UP){
        y += -velY;
    }
    else if(e.getKeyCode() == KeyEvent.VK_DOWN){
        y += velY;
    }
    else if(e.getKeyCode() == KeyEvent.VK_LEFT){
        x += -velX;
    }
    else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
        x += velX;
    }
    else if(e.getKeyCode() == KeyEvent.VK_SPACE){
        int blockX = Math.round(x / 50) * 50;
        int blockY = Math.round(y / 50) * 50;
        blockList.add(new Rectangle(x, y));
    }
}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent e) {
    // TODO Auto-generated method stub
    if(e.getButton() == MouseEvent.BUTTON1){

    }
}

@Override
public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub

}
}

```

Thanks.

# Answer
This is exactly what you'd expect to happen. This is the code that draws your dirt blocks:

```
for(Rectangle r : blockList) {
    if(rectangle2.intersects(r)) {
        if(BlockD){
            g.drawImage(dirt, (int) r.getX(), (int) r.getY(), this);
        }
    }
}

```

This code says, `for every rectangle (grass block) on the map, draw a dirt block if the player is standing on that rectangle`. So of course your dirt blocks move when the player moves - that's what you're telling it to do.

I'm guessing what you want to do is create a dirt block on the current block when you press space. This should be a quite simple fix:

```
public Gameplay() {
    addMouseListener(this);
    addKeyListener(this);
    setFocusable(true);
    try {
        player = ImageIO.read(getClass().getResource("Player.png"));
        grass = ImageIO.read(getClass().getResource("Grass.png"));
        dirt = ImageIO.read(getClass().getResource("Dirt.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Remove this code!
    /* for(int first = 0; first < 10; first++){
        for(int second = 0; second < 10; second++){
            rectangle = new Rectangle(xb[first], yb[second], 50, 50);
            blockList.add(rectangle);
        }
    } */
}

public void keyPressed(KeyEvent e) {
    if (...) {
        // Movement code for player
    }
    else if(e.getKeyCode() == KeyEvent.VK_SPACE){
        // Place dirt block at current coordinates
        // Round the coordinates to closest block
        int blockX = Math.round(x / 50) * 50;
        int blockY = Math.round(y / 50) * 50;
        blockList.add(new Ractangle(blockX, blockY, 50, 50));
    }
}

public void paintComponent(Graphics g){
    drawBlock(g);
    g.drawString("Jake", x, y);

    // Draw all dirt blocks
    for(Rectangle r : blockList) {
        g.drawImage(dirt, (int) r.getX(), (int) r.getY(), this);
    }
    // Draw player after dirt blocks
    g.drawImage(player, x, y, this);
}

```

Note that I have changed what `blockList` is used for. Before it was the rectangles for all grass blocks but now it is the rectangles for the dirt blocks.
> 1 votes

---
Tags: movement, viewport
---


# Question
Title: Questions about “minecraft” game optimisation
I'm currently trying to do a basic "minecraft style" game. I know how difficult it is to create a game like this, that's why I juste want to do the base of a game like this. I did a class which creates one block face, another one which handles the creation of the whole block (All the faces), and a Chunk class which stores and renders all blocks.

My chunks are 16x1x16 sized (Just 1 layer of blocks). I did a first optimisation step : I removed all faces that aren't visibles (If two blocks are sided, I don't add the two sided faces). And another optimisation with the frustrum.

One chunk rendered Removing invisble faces

With one chunk rendered, framerates are good, but above 4-5 chunks rendered, framerates are becoming low. I don't know how to optimise more. I heard about VertexBuffers and IndexBuffers, but I don't know how to add them, because I have a lots of Blocks, in a lots of chunks. And maybe, in the future, how manage that if I want to destroy/place blocks ?

So my question is : How I can optimise the game ?

Thank you !

(Excuse my english, i'm a French guy eheh)

# Answer
1. The biggest difference is using VertexBuffers/IndexBuffers. You'll want to draw each chunk as a single Buffer. If you want to destroy-place blocks, you just re-calculate the VertexBuffer and `setData` with new data.
2. You'll want taller chunks. The optimization where you remove all the internal faces works a lot better when you have more internal faces. With 1-block-tall chunks, you're always rendering the internal top faces, which you don't need.
3. Depending on how your shader works, you should be able to merge individual 1x1 squares on the surface into larger rectangles. This blog post shows some comparisons on how the mesh size gets reduced by this optimization.
> 1 votes

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


# Question
Title: Recursively get all combinations of tiles
### Recursively get all combinations of tiles

For a game, I need to calculate all possible combinations of a set of a grid in a 5x5-grid and do some calculations on these.

Some combinations of tiles will match a certain algorithm, which is not important for this part of the code, and if it matches, the player will get some points.

To check if the game is over, a very expensive recursive function needs to run which will check all possible combinations. If it doesn't find one, the game is over.

To speed this up, I need to create a **cache of all the possible combinations.**

What I am asking for help about is how to create a nested list of all combinations, following the **Rules for selection** below.

This will be used to check if the game is over.

### Rules for selection.

1. Tile needs to be adjacent to the previous tile, e.g. directly above, below, to the left or to the right.
2. Tile cannot be on the list of already selected tiles.
3. User must select at least two tiles, up to a maxium of the whole board.
4. If the user selects a different tile, the selection will be cleared, and the user can start over selecting a different tile.

### Goal of selection

This is a numbers-based game, where the goal is to combine some tiles, that together will "add up" to the last selected tile.

I will not go into the details of the algorithm here, so I will use an example of a basic addition-algorithm.

For instance, let's say that the board is like the screenshot below. Here, the user could select tile `1, 2`, and then `3`, and since 1+2=3, the user would get some points. Another example would be selecting `3, 2, 7, 12`, since 3 + 2 + 7 = 12

### Checking for game over.

Now, I would like to add a function which checks if there are any possible moves left, and this would basically need to check every combination of tiles. Since this is very exhaustive, I was thinking of creating a nested list of possible combinations ahead of time, and then while the user is playing it would check those combinations.

### Example grid:

A valid selection above would be `0, 1, 6, 7`, but `0, 10`(rule 1), `0, 5, 0`(rule 2) is not valid.

### What I've tried.

I've tried to create a recursive function, but keeping track of the current path while creating a nested path seems to be very difficult.

I've therefore extracted the relevant code of what I've tried. This is for a grid of 5x5.

> **EDIT:** Code now returns a flat list of combinations, **however it doesn't actually get them all**.

A flat list would be huge, since it repeats the data quite often:

```
[
  [
    0, 5, 10, 15, 20, 21, 16, 11, 6, 1, 2, 7, 12, 17,
    22, 23, 18, 13, 8, 3, 4, 9, 14, 19, 24
  ],
  [
    0, 5, 10, 15, 20, 21, 16, 11, 6, 1, 2, 7, 12, 17,
    22, 23, 18, 13, 8, 3, 9, 4
  ],
  [
    0, 5, 10, 15, 20, 21, 16, 11, 6, 1, 2, 7, 12, 17,
    22, 23, 18, 13, 8, 3, 9, 4, 14, 19, 24
  ],
  [
    0, 5, 10, 15, 20, 21, 16, 11, 6, 1, 2, 7, 12, 17,
    22, 23, 18, 13, 8, 14, 9, 4, 3
  ],
  [
    0, 5, 10, 15, 20, 21, 16, 11, 6, 1, 2, 7, 12, 17,
    22, 23, 18, 13, 8, 14, 9, 19, 24
  ],
  ...(3473 more objects)
]

```

It would be a lot better if I could nest these into an object.

### Current code

```
// A list of all neighbours. I've just inlined it here, since my actual functions for creating it are inside an object.
const neighboursArray = [[5, 1], [6, 2], [7, 1, 3], [8, 2, 4], [9, 3], [10, 6], [1, 11, 5, 7], [2, 12, 6, 8], [3, 13, 7, 9], [4, 14, 8], [5, 15, 11], [6, 16, 10, 12], [7, 17, 11, 13], [8, 18, 12, 14], [9, 19, 13], [10, 20, 16], [11, 21, 15, 17], [12, 22, 16, 18], [13, 23, 17, 19], [14, 24, 18], [15, 21], [16, 20, 22], [17, 21, 23], [18, 22, 24], [19, 23], [20]]

const nested = (position) => {
  const paths = []
  const getAllNeighbours = (pos, path) => {
    // console.log('checking', pos, path)
    // Lookup neighbours for this pos
    const neighbours = neighboursArray[pos]
      // Make sure neighbours are not in list of already selected path.
      .filter((tile) => path.indexOf(tile) < 0)
      if (neighbours.length === 0) {
        paths.push(path)
      }
      for (const neighbour of neighbours) {
        path = [...path, neighbour]
        getAllNeighbours(path[path.length -1 ], path)
      }
      }

  getAllNeighbours(position, [position])
  return [paths]
}

```

### Example of output

I've created part of the tree-structure visually for position 0. As you can see, nodes can have 0-3 children (the first can have 4 children), up to 24 levels deep for a 5x5-grid. The deeper the level, it tends to have fewer children as there would be less possibilities available.

# Answer
> 1 votes
So my best attempt would be something like this :

1. Initialize a **x** per **y** array, let's call it **map**.
2. Let the player chose an **authorized** path following your neighbour rules.
3. Keep the choosen tiles in memory in another array, let's call this one **path**.
4. Once the path is valided, remove all the **path** tiles from **map** so you don't have to care about them anymore.
5. Clear **path** array.
6. Check if **at least two tiles** can be chose by running a simple loop on **map** array which breaks if a pair is found. This way you don't have to iterate through all possibilities, only one is enough for the game to go on.
7. **If a pair exists**, go back to step 2, **if not**, it's game over.

This induces the following behavior : *The more tiles in **map** array, the more possible combinations exists, the quicker it is for the algorithm to find at least one possible combinations. The less tiles in **map** array, the less possible combinations exists, maybe even none ! But if less tiles exists, less imaginable combinations are possible.*

I let you think about the mathematical function that can compute if two tiles are neighboured or not, i guess you already have it ;)

Hope it helps

# Answer
> 1 votes
I figured out a way to do this. There might be more effective ways, but it works. It now generates first an array of all possible combinations, and then creates a nested object from that.

From this I generated two files, to compare sizes. The array is now huge, at 80 MB (7.8 MB compressed), while the nested object is 8.4 MB (424 KB), a reduction of almost 90%.

```
// A list of all neighbours. I've just inlined it here, since my actual functions for creating it are inside an object.
const neighboursArray = [[5, 1], [6, 2], [7, 1, 3], [8, 2, 4], [9, 3], [10, 6], [1, 11, 5, 7], [2, 12, 6, 8], [3, 13, 7, 9], [4, 14, 8], [5, 15, 11], [6, 16, 10, 12], [7, 17, 11, 13], [8, 18, 12, 14], [9, 19, 13], [10, 20, 16], [11, 21, 15, 17], [12, 22, 16, 18], [13, 23, 17, 19], [14, 24, 18], [15, 21], [16, 20, 22], [17, 21, 23], [18, 22, 24], [19, 23], [20]]

const getCombinationsForPosition = (position) => {
  const getAllNeighbours = (pos, path) => {
    // Lookup neighbours for this pos
    const neighbours = neighboursArray[pos]
      // Make sure neighbours are not in list of already selected path.
      .filter((tile) => path.indexOf(tile) < 0)
      paths.push(path)
      for (const neighbour of neighbours) {
        const p = [...path, neighbour]
        getAllNeighbours(p[p.length -1 ], p)
      }
      }

  getAllNeighbours(position, [position])
}

function assign(obj, prop) {
    if (prop.length > 1) {
        var e = prop.shift();
        assign(obj[e] = Object.prototype.toString.call(obj[e]) === "[object Object]" ? obj[e] : {},
               prop);
    } else
        obj[prop[0]] = -1;
}

const length = neighboursArray.length
const paths = []
const nesty = {}

for (var i = 0; i < length; i++) {
  getCombinationsForPosition(i)
}
paths.map(path => assign(nesty, [...path]))

const sorted = paths.sort((a,b) => a.length - b.length)
while (sorted[0].length < 2) {
  sorted.shift()
}

```

---
Tags: javascript, recursion
---


# Question
Title: Using Fragment Color to store individual bits (GLSL) may introduce issues if OpenGL does any evaluation of the floats before writing them to memory
I need to be able to output individual bits from a fragment shader.

I need a lot of bits per fragment too, otherwise I will face a tremendous performance drag.

Let's say that we have a whole bunch of single-direction lights, let's say 128 of them.

Let's also say that we have already rendered their depth buffers and have a huge FBO

Well, from the player-camera's perspective, All we really need to know from the depth buffer is whether or not an individual screen pixel is in a shadow or not.

I want to do a mid-level pass in my algorithm (Trust me- I have a reason) for testing whether or not a screen pixel is in the shadow of a particular light

As in, all the pixels have boolean values for each light stored in them

The thing is, I don't want Numlights of these buffers.

I would like to pack as many lights into one of these "Boolean Buffers" as I call them as possible. I want to be memory efficient.

(NOTE: I've devised a way to mix this with the shadow map generation too, i'm really trying to reduce the amount of gpu memory my algorithm uses)

Booleans are either 1 or 0. Conveniently, computers store data as ones and zeros.

This includes the output of a fragment, which is four GLfloats.

I'm wondering if it would be possible to manipulate individual bits of a GLfloat, to the maximum bitdepth of a float.

This would allow me to run through all my depth buffers (32 buffers at a time, even) and calculate the cansee/cannotsee of all my lights, 32 at a time (OpenGL allows for 32 texture units at once)

My depth buffers are stored as textures.

My algorithm theoretically works, however ANY evaluation of the floats' values when they are being read from or written to GPU memory will cause my algorithm to fail (Although it wouldn't crash...).

E.g. if Not-a-Number floats get evaluated as all zeros in bits (rather than directly copying the bits regardless of evaluation) then my boolean buffer will fail!

My algorithm also fails if there is any sort of clamping or estimation applied to the floats.

**My questions are then as such:**

1. Are there any float values (in bits) that will be evaluated and copied incorrectly to/from GPU memory when a fragment is rendered or the texture2d call in glsl reads it?
2. Is there any clamping or evaluation or estimation done on the output floats of a fragment shader? What are they?
3. Is there a better way of outputting as many bits as possible from a fragment shader, that wouldn't have any weirdnesses? (E.g. changing the rendering mode to doubles or ints or something)

but... I would also like to tell you...

```
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    In case you're curious what I'm using it for...
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

```

I'm developing a brand-new low-memory-footprint and relatively computationally efficient light and shadow rendering technique for rendering thousands of lights (my current plan is 128 per middle-pass FBO, as the bitdepth of a GLfloat is 32 and there are 4 floats output by the fragment shader... RGBA) which uses shadow mapping but I need to use middle-pass buffers filled with boolean data for whether or not a shadow can "see" a light. Using this along with of course all the light locations in the scene I can generate the lighting buffer (Stores the net color change of fragments due to lighting) using relatively few passes (For unidirectional lights, the number of passes to generate the lighting color buffer would be equivalent to 1 + Numlights(1 per light)(NumShadowmaps) + Numlights/128/32 (rounded up, next highest int)(Number of Middlepass BooleanBuffers) + Numlights/128/32/31 (rounded up, next highest int)(Number of Cumulative light color change buffer passes, 31 b/c we need to pass in the old cumulative buffer alongside all those boolean buffers)

if I was able to find someway to store more than 128 bits per fragment, say 256, then I could store even more lights! 1+Numlights + Numlights/256/32 + Numlights/256/32/31! SO MANY LIGHTS, SO FEW PASSES, SO LITTLE MEMORY! :D

The pass to generate the lighting color buffer of course gets a couple vector operations more complicated with every new light, but since the shader for my lighting color buffer automatically checks all its uniform variables to see if they are valid and only calculates what it needs to, and since I seperated out the shadowmapping process, it is not a huge impact. An additional shadowmap is usually the only additional complexity, with only shadowmaps that increase the number of middlepasses (multiples of 32) or cumulative color change passes (multiples of 128 times 31). Cumulative color change passes are additive, so there is no recursive effect or anything. We're not getting an infinite series of 1+1/32+1/(128\*31)+...

if I ever manage to make it a reality, i'll see what I can do about uploading an open-source demo. I've been studying shadow algorithms for a couple weeks and very few algorithms seem to solve this apparent light-number-limit and computational complexity problem as efficiently as I do.

My solution becomes even more efficient with more unit textures allowed.

If I bothered to write much larger textures made up of a lot of smaller textures (I've heard this called "texels" but I hate the name), it could be even more efficient but I'm somewhat new to OpenGL and I don't feel like coding a huge complicated texel mess right now. it would actually decrease performance for a small number of lights too, and make the overhead for rendering the final pass larger.

# Answer
> 1 votes
> 3) Is there a better way of outputting as many bits as possible from a fragment shader, that wouldn't have any weirdnesses? (E.g. changing the rendering mode to doubles or ints or something)

If you're using at least OpenGL 3.0, you can just use integer buffers and bypass the complexity of floats entirely. Just bind a buffer of type `GL_RGBA32UI` to `GL_COLOR_ATTACHMENT0`, and do something like this in your shader:

```
#version 300
layout(location = 0) out uvec4  frag_color_uint_output;

void main(void)
{
    uint myBits = whatever; // 32 bits of data.
    uint myBits2 = whatever; // 32 bits of data.
    uint myBits3 = whatever; // 32 bits of data.
    uint myBits4 = whatever; // 32 bits of data.
    frag_color_uint_output = uvec4( myBits, myBits2, myBits3, myBits4 );
}

```

---
Tags: opengl, glsl, shadow-mapping
---


# Question
Title: Shooting function in pygame w/ 2 Players
I'm trying to program a shooting function in my game using pygame. Process:

* Player one will press 'Space' and shoot their type of projectile
* Player two would press 'E' and shoot their type of projectile
* Player one's projectile would collide with player two but not player one (and vice versa).

I'm not sure how to code this function properly. Here's my code so far:

```
Initalize
import pygame, math
WHITE = (255, 255, 255)
#Creating sprites

class Player(pygame.sprite.Sprite):

    def __init__(self, color, width, height):

        super().__init__()
        #Config
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        # Draw
        pygame.draw.rect(self.image, color, [0, 0, width, height])

        # Fetch
        self.rect = self.image.get_rect()

    def right(self, pixels):
        self.rect.x += pixels
    def left(self, pixels):
        self.rect.x -= pixels
    def up(self, pixels):
        self.rect.y -= pixels
    def down(self, pixels):
        self.rect.y += pixels

pygame.init()
# Config
RED = ( 255, 0, 0)
BLUE = ( 43, 255, 230)
ORANGE = ( 255, 170, 0)
BLACK = (0, 0, 0)

SCREENWIDTH = 400
SCREENHEIGHT = 500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Squares Fight")

group1 = pygame.sprite.Group()

player1 = Player(BLUE, 50, 50)
player2 = Player(ORANGE, 50, 50)
player1.rect.x = 5
player1.rect.y = 5
player2.rect.x = 345
player2.rect.y = 445

group1.add(player1, player2)

loop = True
startend = False
startanew = True
clock = pygame.time.Clock()
font = pygame.font.SysFont("berlinsansfb", 72)
text = font.render("Fight!", True, WHITE)

# Game Loop
while loop:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        loop = False

        #Logic
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
                player1.left(3)
        if keys[pygame.K_RIGHT]:
                player1.right(3)
        if keys[pygame.K_UP]:
                player1.up(3)
        if keys[pygame.K_DOWN]:
                player1.down(3)
        if keys[pygame.K_a]:
                player2.left(3)
        if keys[pygame.K_d]:
                player2.right(3)
        if keys[pygame.K_w]:
               player2.up(3)
        if keys[pygame.K_s]:
               player2.down(3)

    collision = pygame.sprite.collide_rect(player1, player2)
    if collision == True:
            group1.remove(player1, player2)
            startend = True
    group1.update()
    if startend == True:
            pygame.display.set_caption("They destroyed eachother! Press space to do it again")
            startanew = True
    if startanew == True and keys[pygame.K_SPACE]:
            group1.add(player1, player2)
            pygame.display.set_caption("Squares Fight")
            startend = False
    # Drawing
    screen.fill(BLACK)
    screen.blit(text,
                (200 - text.get_width() // 2, 240 - text.get_height() // 2))
    group1.draw(screen)

    # Closing
    pygame.display.flip()
    clock.tick(60)
    #Indentation isnt right because how i needed to format this
 pygame.quit()

```

What else do I need to add to accomplish this task?

# Answer
> 1 votes
The way you handle multiple objects that do the same thing (such as a bullet) in Pygame is by using groups. Groups are an efficient way to run the same code for a group of objects. For example:

```
class Bullet():
    def move(self):
        self.x += 1

bullet1 = Bullet()
bullet2 = Bullet()
bullet3 = Bullet()

bullet_group = pygame.sprite.Group() #Make new group
bullet_group.add(bullet1, bullet2, bullet3) #Add objects to group

bullet_group.move() #Execute move() method for all objects in group

```

So let's say you wanted to make bullets from Player 2 only hit Player 1. First of all, the best way to make two different types of bullets that will move the same way is to make a parent class, **BulletParent**. Then, to get proper collisions you would most likely want to make the **BulletParent** class a child of the **pygame.sprite.Sprite** class.

```
class BulletParent(pygame.sprite.Sprite):

```

Then you can make some kind of **move()** method inside the **BulletParent** class to move the bullet.

```
class BulletParent(pygame.sprite.Sprite):
    def __init__(self, direction):
        super().__init__()
        self.direction = direction

    def move(self):
        #add moving code here
        pass

```

Now, you can make two child classes of the **BulletParent** class, let's say **Bullet1** (for Player 1) and **Bullet2** (for Player 2). This is important because we need a way to know which bullet belongs to which player. Once you have made those classes, you need to check if each player has pressed their shoot button. Let's make one function to check key presses and make the **bullet1\_group** and **bullet2\_group**:

```
bullet1_group = pygame.sprite.Group()
bullet2_group = pygame.sprite.Group()

def check_keys():
    keys = pygame.keys.get_pressed()

    #Arrows keys and WASD presses

    if key[pygame.K_SPACE]:
        bullet1 = Bullet1(player1.direction) #may need to add direction variable for player1
        bullet1_group.add(bullet1)

    if key[pygame.K_a]:
        bullet2 = Bullet2(player2.direction) #may need to add direction variable for player2
        bullet2_group.add(bullet2)

```

This will make new bullets every time one of the shoot keys is pressed. Now we can make a function that returns if Player 1 is hit and make another to do the same for Player 2. We can use the **pygame.sprite.spritecollideany()** function to see if anything has collided with our players. It will return a Sprite if anything has collided and None if not.

```
def player1_hit():
    collide = pygame.sprite.spritecollideany(player1, bullet2_group)
    if collide == None: return False
    else: return True

def player2_hit():
    collide = pygame.sprite.spritecollideany(player2, bullet1_group)
    if collide == None: return False
    else: return True

```

We can make a function that moves both bullet groups:

```
def move_bullets():
    bullet1_group.move()
    bullet2_group.move()

```

Finally, you can add the **check\_keys** and **move\_bullets**functions to the main loop, and add some logic to use with the **player1\_hit** and **player2\_hit** functions.

Hope this helped and I hope you continue programming no matter the problem!

---
Tags: collision-detection, pygame
---


title: Binding c++ templated functions to lua

text:
# Question
Title: Binding c++ templated functions to lua
I have started using Lua as a scripting language for my game engine. It works perfectly for things like input, audio etc. However, I'm now trying to bind my entity component system functions which make heavy use of templates.

For example, getting a component of an entity in c++ would look like this:

```
uint32 entity = 1;
Transform &transform = registry.get<Transform>(entity);

```

and adding a component to an entity:

```
registry.add<Velocity>(entity, 0.0f, 0.0f);

```

From what I can tell, Lua cannot handle templated functions - I would have to bind a new function for each component e.g `getTransformComponent(entity)`. This obviously isn't great and becomes a huge pain for the end user. I've had a look around and can't find anything that is particually helpful for my problem. I see a few people suggesting things like `getComponent("Transform")` but I don't see how this would be implemented in c++ as my components are PODs, no base 'Component' class?

# Answer
> 2 votes
This is a general interop problem with C++ features. If you want to target other languages, you often have to forego many of them by the time you reach the other language calling your functions. Besides templates, another example is exceptions. You can't necessarily throw exceptions from C++ into another language to catch, so often you have to swallow (catch) any exceptions thrown and translate them into, say, error codes at your API boundaries.

There are two main strategies I would suggest for your case depending on the maturity of your engine and how difficult it is to change the central interface designs.

The first is to use a Lua binding library which covers the grunt work for you when binding template instantiations. The last one I used of this sort was many years back and there might be more popular ones now, but I used LuaBind in the past without too much pain. While Lua naturally can't generate C++ code, LuaBind will let you export a template instantiation like `Registry::get<Transform>` to a Lua function of your choice of name, like `getTransform`. It'll generate all the code to bind such a template instantiation to Lua for you automagically at compile-time. Since it's also a compile-time code generator written using C++ templates, it can understand C++ template instantiations and export them to Lua.

That still means you have to export every single template instantiation you use and would have to introduce new binding code every time you introduce a new component type, but it's the most direct way to, in essence, "export a template instantiation to Lua" while still preserving type safety (at least runtime type checking on the Lua side) and so forth. As a bonus LuaBind also lets you export function overloads. Normally Lua can't handle overloaded functions, but LuaBind lets you export multiple functions with the same name to Lua and effectively generates code which does type checking and branching for you based on the type of the parameter passed in to the Lua function. As yet another bonus, IIRC LuaBind will also generate the functions with their own catch blocks to swallow any exceptions and translate them to Lua errors with pcalls before reaching Lua.

The downside I found to this approach aside from the grunt work for binding was actually compile times. For big codebases with APIs that span several hundred header files, it wasn't unusual for me to find that the source file containing my Lua bindings took almost 15 minutes to build, and that build time is there any time you change anything in the entire SDK. On the plus side though, I was able to do things like export std::vector instantiations to Lua, like `std::vector<int>` as `VectorI` in Lua, `std::vector<float>` as `VectorF` in Lua, and so forth. It's pretty cool to be using instantiations of a standard library class template from another language without too much work.

> I would have to bind a new function for each component e.g getTransformComponent(entity). This obviously isn't great and becomes a huge pain for the end user.

This is an unavoidable conceptual requirement with templates. After all, if we use `std::vector<T, Alloc>` for example, there are an infinite number of combinations of code it could generate based on what `T` and `Alloc` are. Same goes for your `get<T>` method. We can't generate an infinite amount of code to export, so you have to explicitly specify which template instantiations to generate and which to export at the very least. The above suggestion with libraries like LuaBind at least minimize the grunt work down to a minimum. You can export a finite amount of generated code to be called from a target language, but you can't export metacode to be generated against a code generator from your language to another (unless your target language has an FFI which can generate, compile, and link C++ template instantiations on the fly in a JIT-like fashion -- that actually seems conceptually feasible given how C++ JITs are cropping up these days... OMG, I just JIMPed thinking about how cool it would be).

**C API**

The second approach is similar to the existing suggestions. Forego the templates (static polymorphism) and type safety for your "base API". Make it more C-like with functions that accept some kind of component ID like a string or integer and make them return a uniform type regardless of the type of component we're retrieving, like an index or void pointer.

However, because this is dangerous and error-prone, you can write some wrappers on the Lua side to re-impose type safety, as well as wrappers on the C++ side to re-impose type safety (and you're free to use templates all you want for the wrappers).

This is actually the least painful way I've ever experienced after binding C++ code to multiple embedded languages (Lua, Python, and Java) using a variety of libs (SWIG, LuaBind, boost::python, JNI, Lua modules, Python modules, etc). Basically create a C API or C-like API and bind that to Lua. If you do that, you can even use LuaJIT which comes with an FFI that can import dylib-exported C functions and call them directly from Lua without any binding work whatsoever. It's also the most universally language-friendly, since many languages can interop with a C API but would choke on C++ features like function overloading, vtables, constructors, destructors, templates, exceptions, etc.

As opposed to:

But it would be painful to apply if your engine is already mature. And it's not free of its share of grunt work unless you want to work with raw C-like code in Lua and C++, e.g. You'll still most likely want to wrap the C API into idiomatic code in the target language (Lua tables and C++ classes in your case). But among all the alternative solutions I tried, the C API approach was the most painless one I've encountered so far. The point of exporting a C API is to aim for a "lowest common denominator" API that all languages of interest can understand and work with. C language features are often that "lowest common denominator".

Note that a C API doesn't mean you have to implement those API functions in C. You can use a header which only uses C language features and still use a C++ source file using all sorts of C++ language features to implement it.

Also just as a side note, I don't recommend trying to make Lua's garbage collector extend the lifetime of your components. I worked in code that tried to do that with Python's GC and it was some of the most error-prone code I ever encountered, prone to logical leaks and slicing and so forth by trying to mix and match two very different memory models and using two different garbage collectors against each other. Think of what Lua stores as a garbage-collected "handle" to your component (if you wrap it in tables as opposed to directly working with light userdata or indices) which could be invalidated before the GC collects it, not something that is actually extending the lifetime of a component, and your life should be much easier.

> I see a few people suggesting things like getComponent("Transform") but I don't see how this would be implemented in c++ as my components are PODs, no base 'Component' class?

You'd still have to write some code, somewhere, that casts what `getComponent` returns which might be like an integer indicating a component index or `void*` or `Component*` (but still requiring a down-cast even in that case) before you can get at the actual component data.

The way I do it is that my API functions don't even work with, say, `CMotion*`. They work with `ComponentIndex`:

```
struct ComponentIndex
{
    int32_t type;
    int32_t index;
};

```

... which means I've completely lost compile-time type safety, since you can pass a component index pointing at a `CSprite` to a system that wants `CMotion`. However, it can still do runtime type-checking using that `type` field, and I've implemented a rich set of C++ libraries to make it easy to grab component data from these indices in a way that automates the type-checking for debug builds using a C++ template interface. When you're doing interop, it often helps to think of convenience and safety as a separate problem to be solved through wrappers instead of something to be achieved upfront, since a lot of the features relating to type safety and the most convenient and idiomatic usage are very language-specific and not understood by other languages.

The first goal is to find that lowest common denominator which all languages can understand which is usually neither safe nor convenient nor idiomatic. Then in the target language, build a set of wrappers which impose the safety and convenience and "idiomatic-ness".

# Answer
> 0 votes
I had this same issue when I was implementing my entity-component model.

In the end I settled on having separate methods for getting components, but using my lua bindings I access them like properties. My syntax looks like this:

```
local actor = linkActor() -- links script to the actor
local script = actor.controller -- get our script controller
local events = actor.components.events -- our event component, where unique events and callbacks happen
local animator = actor.components.animator -- our animation component, controls our animations

script.initialize = function()
    assert(events ~= nil)
    assert(animator ~= nil)

    -- upon being hit, this function will be called
    events:listen('on_hit', function(event)
        animator:play('hit')
    end)

end

```

This was the only solution I was happy with in the end - it's clear to understand and use, and that was my primary purpose.

# Answer
> 0 votes
Altough it is popular to access components via templates (most common implementation I stumbled across so far), only few developers consider implementing access like in the following snippet:

```
entitiy.component('transform');
// ... OR ...
// when you're not afraid of operator overloading.
entity['transform'];

// When you implement more magic, you can still access your
// type via templates
entity.component<Transform>();

```

Using a *clean* approach, one would create a base class for components, note, however, that a plain **void pointer** should be sufficient, since we know, which objects we're trying to access.\*

Following this pattern, it should be easy to bind the getter to Lua.

I'd recommend to wrap the function on the Lua side, so that casting is being handled automatically by the function and a global component registry.

* Yes, I know that this solution can lead to nasty bugs, when applied badly. But, when you know, what you're doing, it can be a great (and sometimes necessary) tool.

---
Tags: c++, entity-system, component-based, scripting, lua
---


# Question
Title: What can I do with the 4th component of gl_Position?
When I set `gl_Position` I usually assign it such as `gl_Position = vec4(in_position, 1.0)` where `in_position` as a vector of three components representing a vertex of my model.

But looking up tutorials and such I cannot find anything explaining what the 4th component of the `gl_Position` vec4 is doing aside from making the vector big enough so matrix transformations can be applied to it.

**Q**: What can I do with the 4th component of gl\_Position / what does it influence in the rendering process?

# Answer
`gl_Position` is a Homogeneous coordinates. Homogeneous coordinates are needed for perspective projection.

Note, if a vector `vec4(x, y, z, 1.0)` is multiplied by a perspective projection matrix, this results in a Homogeneous coordinates.

The projection matrix describes the mapping from 3D points of a scene, to 2D points of the viewport. The projection matrix transforms from view space to the clip space. The coordinates in the clip space are transformed to the normalized device coordinates (NDC) in the range (-1, -1, -1) to (1, 1, 1) by dividing with the `w` component of the clip coordinates.
At Perspective Projection the projection matrix describes the mapping from 3D points in the world as they are seen from of a pinhole camera, to 2D points of the viewport.
The eye space coordinates in the camera frustum (a truncated pyramid) are mapped to a cube (the normalized device coordinates).

This means the position in normalized device space is calculated like this:

```
vec3 ndc = gl_Position.xyz / gl_Position.w;

```

If you manually set the `w` component of `gl_Position`, this causes a reciprocal scaling of the position in normalized device space.
> 14 votes

# Answer
It's not particularly useful for you but you should definitely leave it at 1. It's used when applying transformations to the model.

Matrix multiplication can only multiply numbers, it can't add. That makes moving objects impossible unless the 4th component exists. Let's look at an example: If we want to move the vector

$$\vec v = \begin{bmatrix}a \\ b\\c\end{bmatrix}$$

by

$$\vec d = \begin{bmatrix}x\\y\\z\end{bmatrix}$$

Then we use the

$$T = \begin{bmatrix} 1 & 0 & 0 & x\\ 0 & 1 & 0 & y\\ 0 & 0 & 1 & z\\ 0 & 0 & 0 & 1 \end{bmatrix}$$

matrix and give \\$\vec v\\$ a fourth component. When we multiply them together, then the result is going to be

$$ \vec r = T\space \cdot\space\vec v = \begin{bmatrix} 1 \cdot a + 0 \cdot b + 0 \cdot c + x \cdot 1\\ 0 \cdot a + 1 \cdot b + 0 \cdot c + y \cdot 1\\ 0 \cdot a + 0 \cdot b + 1 \cdot c + z \cdot 1\\ 0 \cdot a + 0 \cdot b + 0 \cdot c + 1 \cdot 1\\ \end{bmatrix} = \begin{bmatrix} a + x\\ b + y\\ c + z\\ 1 \end{bmatrix} $$

The second use for the 4th component is perspective division. A projection matrix basically normalizes and copies the z component to the w. OpenGL then automatically divides the x, y and z components by it.
> 11 votes

---
Tags: shaders, glsl, vertex-shader
---


# Question
Title: Scene with Node graph thread safe, with important efficeny
I will try to be as explicit as I can, and I apologize for my grammar...

I am working on a game engine (specifically on the Render part) and I am facing some conception choice that will involve a lot of code and I would like to do the good one on first try. I am actually working on the Scene graph. I have to specify, that the engine have to be thread safe, and c++11/14 compliant while limiting the user mistake (not allowing engine user moving a pointer that shouldn't be moved...). So my issue is that I do not know how to give the access too engine user and keep the thread safety without killing performance with 10000 of cache misses or if it is needed to be able to search for a specific Node (when you build the tree don't you know wich Node you will use?).

Actually I started with a tree of Node something very standar

Each Node know all of its child and they know their parents. For efficiency purpose every Node who will contain meshes, with associated texture will stock them in a Scene object who will old a pointer on every Node who hold a mesh (for querying the scene transformation matrix of the mesh). The scene will also hold the root Node of the scene.

My question is How should I handle the link between A Node and its family?

One of the solution I thinked about is to use the Observer design pattern. Use shared\_ptr between Node and it's family then only provide NodeObserver to the engine user. But with this solution I don't know how to link the scene ressource holding to the nodes because a shared\_ptr will introduce unbreakable cycle and a wear\_ptr will introduce to much cache\_miss and to much synchronization (at least a lock on every Node every frame...) I could use a naked pointer stored into the Scene object, and at the end of its life Node destructor should removeit from the Scene?

I will be very happy if anyone know how to do that. Thank you in advance for your time and your help.

# Answer
I can't give you a complete solution as I never bothered to try to make a universal, thread-safe scene graph (a bit too ambitious given the teams and environments I worked with), but I think this answer will provide a huge potential puzzle piece.

**Kill the Scene Root!**

I don't use the concept of a "scene root". If I did, every single thing I insert to the scene would have to be inserted to the scene root and store all kinds of links with all kinds of shared data. I do have a tree component like this:

```
struct CTreeNode
{
     // I often need bottom-up traversal where the user
     // selects a child/leaf and then wants immediate access
     // to its parent, so I store a parent link.
     int parent;

     int next_sibling;
     int first_child;
};

```

... but I only use that and attach that to an entity when I genuinely *need* parenting, like in a bone or rigid body hierarchy. And the root of that is not the scene root, so there's little shared data. The root for a robot might be its pelvis/hips, not the root of the entire scene. We basically take this:

... and turn it into this:

And that might seem like it's just trading a "scene root child list" for a "flat scene list", but the second doesn't have to be a linked structure; it can be a totally different data structure and data type. You could use an unrolled list or `tbb::concurrent_vector` or something else very friendly for concurrency and `memcpy` and so forth if you're aiming to try to make these central data structures thread-safe. You don't have to get tunnel visioned on trying to make the entire tree and manipulations on a single node thread-safe if this flat "root child list" is stored in a separate data structure from the tree nodes.

**Different Characteristics, Common Cases and Rare Cases**

The root child list is very different in nature from the rest of the branches/children since it's usually going to store a massive list of analogical children and inserting/removing children would potentially be an extremely common case (possibly occurring every single frame), while the branches in the scene will often have much fewer children and may rarely ever need to modify the hierarchy. The average number of children the root node need could be in the range of hundreds of thousands to millions, while the average for everything else that needs to serve as a parent is 3. Those are radically different requirements.

There's very few reasons for a bone hierarchy to ever change. You might just load the skeletal data for a character and that's that, the parent/child relationships never change beyond that point. Meanwhile you might be inserting and removing elements to/from the scene many, many times per frame. When you have radically different use characteristics like that, it often helps to use a different data structure.

It makes things a lot easier if you don't try to use one node data structure to rule them all here and treat the "flat scene list" as a separate concept/data structure without an actual "scene root" because, again, the data structure and usage and common case/rare case characteristics are vastly different between the analogical scene root child list and, say, the children's children. Trying to cram that all into one analogical "node" structure for everything is likely to cause more grief than help, and *especially* if you're trying to multithread hierarchical manipulation and traversal.

**Multithreading**

And I think if you start with that concept of eliminating the idea of a scene root which every single thing in your scene/game world is parented to, it should help a whole lot if you are trying to multithread manipulations and access of the graph. That'll give you many independent graphs with little shared data instead of one graph with shared root data for everything.

**Implicit Scene Root**

If you want to actually do the analogical "whole scene transformation", you can special case that and multiply everything by a matrix without storing parent/child links for every single thing in your scene. If you need to display a scene outline in your level editor, again you can special case and pretend like the scene root exists by doing flat iteration over the entities in your scene that don't have a tree node component attached or have, say, -1 stored for the `parent` (which in my case indicates a root). You don't actually have to have a real root node for the entire scene and link everything to it and store all this extra shared data. You can deduce that implicitly that every entity without a tree node attached or with a null parent (or `parent` set to -1 if you use indices like me) is an immediate child of the analogical scene root (which isn't actually stored as a node in memory).

**Caching Preorder Traversal**

Another thing that mitigates cache misses since linked structure traversal is inherently not very cache-friendly usually is that I have a function which outputs a flat array of indices using preorder traversal of the tree (which, again, is a small tree with an entity in the scene as its root, not the entire massive scene as its root), and each set of child indices is sorted. I generally don't traverse the tree except to output this flat array of indices whenever the tree has changed. Since the indices are gathered using preorder traversal, you can update motion matrices in a straight sequential fashion over the resulting array while processing things in proper order (parents before children).

**`shared_ptr/weak_ptr`**

On the use of `shared_ptr/weak_ptr`, I generally don't bother and just refer to things by index when components depend on each other. Again with my tree node:

```
struct CTreeNode
{
     int parent;
     int next_sibling;
     int first_child;
};

```

... the links just use plain old integers as indices to entities. What I do is when the node is destroyed (I can register destructors for a component type through the component registry -- can't use C++ dtors directly since the ECS uses a C API for interop with many different languages), I just update the links to exclude the node, removing it from its parent and setting the links of its children to `-1` (null, i.e.).

Now I could see how `shared_ptr` might become very helpful in a multithreading context to ensure that the lifetime of a resource is extended until after a thread is finished processing it, but I always found the benefits of `shared_ptr` to often be outweighed by its cons (easy to introduce logical leaks by accident, expensive atomic ref counts, having to heap allocate everything including the ref counter, etc). Instead I often found it useful to just make sure all systems do their processing from a "process" callback/event, even systems running in other threads. If they try to destroy/remove any entity/component during these processing events, the removal is deferred until a small time slice (very short-lived lock) when systems are no longer processing.

I find that much easier to deal with and so much cheaper and just much more predictable to reason about when things should be destroyed in between system processing instead of at the granular level of all shared pointers to a resource being released whenever and from wherever (hard to predict when/where that will be in a complex codebase if you're using shared ownership a lot). I find it so much easier to have an explicit "removal" function I can count on to remove components and entities, but also knowing that's safe to use because it's not actually going to remove a component if systems are still being processed (in the same thread or other threads). If you can unify your codebase this way as opposed to having "rogue threads" storing their own persistent references to game state for who knows how long, life becomes so much easier.

Because in my cases at least, a scene entity/component should be removed when the user requests to remove it from the editor *unless* there are systems still processing, at which point it should be removed as soon as possible when they're not. Explicit removal is so much easier in these cases than implicit and hoping that every relevant part of your system will release those strong references soon after.

Another thing about `shared_ptr` in a team environment at least is that once you publicly expose a `shared_ptr` to something in some interface (using `shared_ptr` for implementation details is not nearly as problematic), you can't stop it from spreading. You can't prevent people (at least not forcefully, maybe with very careful standards) from storing more `shared_ptrs` to the same resource, including third party plugin developers writing code completely outside of your team's control, and it only takes one of them to be careless and forget to release the `shared_ptr` to extend a resource's lifetime far longer than appropriate, introducing logical leaks into your application, and I've had that happen a lot in the past where third parties ended up storing a `shared_ptr` to something expensive like a mesh, at which point it wasn't freed at the right time when the user requested to remove it (not even close). So I've always been weary about its usage, since it can easily be misused in horrific ways to the point where it can become impossible to reason about when anything will ever be freed and destroyed since code that's not even in your team's control could be extending the lifetime of objects way, way longer than they should persist.
> 1 votes

# Answer
A tree structure like a scene graph is diametrically opposed to the operation of multithreaded programming. What happens if someone adds or removes a single node? The whole thing collapses. It's also a bit unpleasant because it already causes lots of cache misses.

So first off I would forget about using a scene graph, or at least using it directly. Any safe way of using it is going to be way too slow. That's not to say that you can't have both a scene graph and a specific collision structure, though.

I would recommend a flat structure ie an area that has all of the transforms calculated out. Then each frame you recalculate everything in a second buffer (perhaps what you are using as the actual scene graph) and then copy everything over in one memcopy to the collision structure.

It's a big topic to cover in an answer to an online question so if none of this makes any sense then this is a good place to get started: http://realtimecollisiondetection.net/
> 0 votes

---
Tags: multithreading, scene-graph, c++
---


# Question
Title: OnTriggerEnter : is it called in both collider object?
I've 2 object: a Player and a Bonus object.

In both script I've "OnTriggerEnter" script.

In Player OnTrigger I: Take Bonus value and add it to my Player (health, point, ammo)

In Bonus OnTrigger I: Play audio (when take it), Play Particle System and so on...

But, it seems it's called only Player's OnTriggerEnter ... Why ?

In Unity, if I have OnCollision/OnTrigger enter in both object, which event is called ? Both ?

Thanks

# Answer
> 4 votes
In order to fire `onTrigger`, you need to have colliders in both game objects with at least one of them with a `rigidbody` and with at least one of them with `isTrigger` set to `true`.

When that's the case, the `OnTriggerEnter` is called on all game objects involved if you have the `OnTriggerEnter()` function written in the scripts attached to them.

It doesn't matter which one has the `rigidbody`, or which one has `isTrigger` set to `true`. You can mix and match the settings in any way you want.

You can also have both object with `isTrigger` set to `true`. If you are having issues, you may have misspelled the function call on the bonus object.

---
Tags: unity, collision-detection
---


# Question
Title: Finding all hexagonal grid coordinates inside cover arc
I got a turret that points at the corner of hexagon (point A). It can shoot in cover arc that's shown here:

I need to check if my target lies within this cover arc. From this tutorial: Hexagonal Grids I know how to get a hexgrid coordinate of my target by cliking on it.

How can I get coordinates of all the hexes in cover arc (not only red hexes but all that lie within CA)?

# Answer
I prefer to do hex-cell coordinate math in what Amit calls cubical coordinates on your linked page. For the rest of this answer, (X, Y, Z) will refer to cubical coordinates.

Basically, for any of the 6 sectors you're interested in, one of the positive or negative X, Y, or Z axes will correspond to the radial distance. For example, in Figure 1, as X increases in the northeast sector, the distance gets further away.

The other two coordinates are chosen such that they are less in magnitude than the radius (so you don't go past the left and right borders of the sector). Again, referring to Figure 1, When X is `2`, `(Y, Z)` goes `(0 -2), (-1, -1), (-2, 0)`. Due to the rules of the cubical coordinates, Y and Z must add up to -2, and they cannot be `(-3, 1)` for example because they cannot be larger than X in magnitude.

Putting this together, given a particular sector, you choose one of `X, -X, Y, -Y, Z, -Z` as the radius axis and then iterate along two other axes such that the two axes plus the radius always equals 0 (to satisfy the cubical coordinate constraint) and whose absolute values are less than the radius. In pseudocode:

```
 for(var radius = 0; radius <= 4; radius++) {
     for(var a = 0; a >= -radius; a--) {
         var b = - radius - a;
         /*
        At this point we have 3 coordinates that satisfy the cubical condition: (radius, a, b) and radius + a + b == 0.
        Depending on the sector, we choose all hexes with coordinates (x, y, z) such that:
        Sector 1: (x, y, z) = (r, a, b) :: X is the radius
        Sector 2: (x, y, z) = (-a, -b, -r) :: -Z is the radius
        Sector 3: (x, y, z) = (b, r, a) :: Y is the radius
        Sector 4: (x, y, z) = (-r, -a, -b) :: -X is the radius
        Sector 5: (x, y, z) = (a, b, r) :: Z is the radius
        Sector 6: (x, y, z) = (-b, -r, -a) :: -Y is the radius
          */
     }
 }

```

To check figure out which sector any particular hex cell with coordinate (X, Y, Z) belongs to, you can check that it obeys the following rules.

* Sector 1: Y \<= 0 && Z \<= 0
* Sector 2: X \>= 0 && Y \>= 0
* Sector 3: Z \<= 0 && X \<= 0
* Sector 4: Y \>= 0 && Z \>= 0
* Sector 5: X \<= 0 && Y \<= 0
* Sector 6: Z \>= 0 && X \>= 0

---

# Interactive Demo:

```
var w = document.body.clientWidth, h = 400, r = 5;
 var $new = x => document.createElementNS("http://www.w3.org/2000/svg", x);
 var $attrs = (e, attrs) => { for(var k in attrs) e.setAttribute(k, attrs[k]); return e; };
 $attrs(demo, {width: w, height: h, viewbox: `0 0 ${w} ${h}`});

 // on mouse over, we highlight the current sector
 function onMouseOver(e) {
     var coords = this.id.split('_').slice(1);
     var sector =
  coords[1] <= 0 && coords[2] <= 0 ? 0 :
  coords[0] >= 0 && coords[1] >= 0 ? 1 :
  coords[2] <= 0 && coords[0] <= 0 ? 2 :
  coords[1] >= 0 && coords[2] >= 0 ? 3 :
  coords[0] <= 0 && coords[1] <= 0 ? 4 :
  5;
     highlightSector(sector, 4);
 }

 // -------------------- Initialize All tiles --------------------
 function createTile(x, y, z) {
     var u = x * 40 - y * 40, v = z * 60, g = $attrs($new('g'), {
  id: `a_${x}_${y}_${z}`,
  transform: `translate(${w/2 + u},${h/2 + v})`,
     });
     g.addEventListener('mouseover', onMouseOver);
     var t = $new('text');
     t.innerHTML = [x, y, z];
     g.appendChild(t);
     g.appendChild($attrs($new('polygon'), { points: "0,-40 40,-20 40,20 0,40 -40,20 -40,-20" }));
     demo.appendChild(g);
 }
 for(var z = -r; z <= r; z++)
     for(var x = -r; x <= r; x++)
  if (!(z + x > r || z + x < -r)) createTile(x, -z - x, z);

 function highlight(x, y, z, h) { document.getElementById(`a_${x}_${y}_${z}`).setAttribute('class', h); }

 function highlightSector(sector, maxRadius) {
     var e2 = Array.prototype.slice.call(document.getElementsByClassName('h'));
     for(var i=0; i<e2.length; i++) e2[i].setAttribute('class', '');

     for(var radius = 0; radius <= maxRadius; radius++) {
  for(var a = 0; a >= -radius; a--) {
      var b = - radius - a;
      /*
  At this point we have 3 coordinates: (radius, a, b).
  Depending on the sector, we choose all hexes with coordinates (x, y, z) such that:
  Sector 1: (x, y, z) = (r, a, b)
  Sector 2: (x, y, z) = (-a, -b, -r)
  Sector 3: (x, y, z) = (b, r, a)
  Sector 4: (x, y, z) = (-r, -a, -b)
  Sector 5: (x, y, z) = (a, b, r)
  Sector 6: (x, y, z) = (-b, -r, -a)
       */
      if (sector == 0) highlight(radius, a, b, 'h');
      if (sector == 1) highlight(-a, -b, -radius, 'h');
      if (sector == 2) highlight(b, radius, a, 'h');
      if (sector == 3) highlight(-radius, -a, -b, 'h');
      if (sector == 4) highlight(a, b, radius, 'h');
      if (sector == 5) highlight(-b, -radius, -a, 'h');
  }
     }
 }
```

```
<!doctype html>
<style>
 g { stroke:#368; fill: #99bbcc66; text-anchor:middle;}
 g:hover { stroke:red; stroke-width:2.5; }
 .h { stroke-width:3; stroke:green; }
</style>

<svg id="demo"> </svg>
```
> 6 votes

---
Tags: 2d, maps, coordinates, grid, hexagonal-grid
---


# Question
Title: Why is the depth test not done on geometry before rasterization?
It seems the only time depth is used to discard data is during rasterization, i.e. at the fragment level.

In the geometry stage, I've only see culling and clipping of vertices. Is it not possible to determine whether if a triangle is behind another triangle using just vertex data (depth?) and discard if so? Wouldn't this save all the work later in scan conversion?

# Answer
It doesn't work well to do depth tests at the vertex level.

Triangles are surfaces. All three vertices of a triangle could be occluded by other triangles in the scene and the middle of that triangle *could still be visible*. The only way to determine whether that triangle is completely behind something else is to interpolate position or depth along the triangle's surface and determine if, at every step of that interpolation, the triangle is still occluded.

This is precisely what the per-fragment depth test is already doing.

Thus, while you could do some "clever tricks" on a per-vertex basis to try to test if a triangle is fully occluded by others prior to the per-fragment test, they will never be completely accurate unless you do exactly the thing you're trying to avoid: step along the surface of the triangle as your rasterization resolution and test the triangle *there*.
> 20 votes

# Answer
You can determine if a triangle is behind another triangle. However, that's not the operation you would need to do if you wanted to do culling at the triangle level. You would have to determine if the triangle is behind a forest of triangles: you have to determine if the triangle is behind any one triangle in the scene.

Triangle to triangle culling is expensive. Fragment by fragment culling is much much cheaper. Eventually the number of triangles will start to add up and fragment culling will be far cheaper.

This will also happen sooner than you think because we can't just test individual triangles. We have to test them together. If you have a triangle that's behind a quad (two triangles), it may be that your triangle being tested isn't occluded by either of the triangles that make up the quad on their own. This means now you need complex geometry tests to see if a triangle is covered in this way.

In the end, testing the triangle will be substantially more expensive than just doing the fragment tests.
> 2 votes

# Answer
This may be of interest:

**Position-Only Shading Pipeline**

> the Cull Pipe uses these critical results to compute visibility information for all the triangles whether they are culled or not. On the other hand, **the Replay Pipe consumes the visibility information to skip the culled triangles and shades only the visible triangles** that are finally passed to the rasterization phase

https://patents.justia.com/patent/20160086299

It seems to solve exactly the problem you are asking about.
> 0 votes

---
Tags: geometry, vertex, depth, rasterization
---


# Question
Title: How can I move an object in an "infinity" or "figure 8" trajectory?
When I want to move object around point I do:

```
    point.x *= cosf(timer.timeElapsed);
    point.y *= sinf(timer.timeElapsed);

```

How to make point move on eight or infinity sign trajectory?

# Answer
Some possibilities:

Lemniscate of Bernoulli

Lemniscate of Gerono

Lemniscate of Booth

Watt's curve
> 25 votes

# Answer
As Marton notes, there are several "figure of eight" curves that might fit your needs. Perhaps the simplest is the lemniscate of Gerono, which has the parametrization:

```
x = cos(t);
y = sin(2*t) / 2;

```

and looks like this:

However, the lemniscate of Bernoulli may be visually more pleasing; it has a parametrization very similar to the lemniscate of Gerono, except that both axes are scaled by a factor of `1/(sin(t)^2 + 1) = 2/(3 - cos(2*t))`:

```
scale = 2 / (3 - cos(2*t));
x = scale * cos(t);
y = scale * sin(2*t) / 2;

```

It looks like this:

(Animations made with Maple 13, compressed with GIFsicle.)
> 69 votes

# Answer
I randomly found another one using this formula:

$$x^2 = y^2 + 0.1x^{2.8}$$

As plotted by Wolfram Alpha:
> -1 votes

# Answer
# $$((x+1)^2+y^2)((x-1)^2+y^2)=1$$

# The product of the distances from any point on that curve to (-1, 0) and to (1,0) is constant and equals to 1.
> -3 votes

---
Tags: mathematics, movement, trajectory
---


# Question
Title: Creating and editing a .fnt file based on a PNG source
I am currently making a game, (obviously), with the LIBGDX Java Library. I have already made a font, (It's a PNG file, not a TTF or RTF), that looks something like this:

(It's a mockup, by the way.)

I've tried programs like Shoebox to create my font automagically, but it doesn't recognize my font.

Can someone explain how I can just make my own .FNT config file?

Thanks in advance!

Plug

# Answer
> 2 votes
The simplest way is probably just to redraw it maually, using a simple .fon editor like Fony.

It will probably take less than a hour.

# Answer
> 1 votes
you can use **Hiero** for generating the .FNT file using your .ttf font file. Go through the link and download it.

https://github.com/libgdx/libgdx/wiki/Hiero

---
Tags: java, libgdx, graphics, fonts, spritefont
---


title: How do I enable FSAA in OpenTK?

text:
# Question
Title: How do I enable FSAA in OpenTK?
All I could find about it is this question, but `GraphicsMode` alone doesn't enable anti-aliasing:

```
using System.Drawing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

class Program
{
    static void Main()
    {
        using (var window = new GameWindow(800, 60, new GraphicsMode(32, 24, 0, 8)))
        {
            window.Resize += (sender, e) => { GL.Viewport(window.Size); };
            window.RenderFrame += (sender, e) =>
            {
                GL.Clear(ClearBufferMask.ColorBufferBit);
                GL.Color3(Color.Red);
                GL.Begin(PrimitiveType.Triangles);
                GL.Vertex2(-1, 1);
                GL.Vertex2(-1, 0);
                GL.Vertex2(1, 0);
                GL.End();
                window.SwapBuffers();
            };
            window.Run();
        }
    }
}

```

# Answer
It's in the constructor of `GraphicsMode`:

`new GameWindow(1280, 800,
 new GraphicsMode(new ColorFormat(8, 8, 8, 0),
 24, // Depth bits
 8, // Stencil bits
 4 // FSAA samples
 ),
"Title");`
> 1 votes

---
Tags: opentk, antialiasing
---


# Question
Title: Access violation when using shaders in LWJGL 3
I've successfully used LWJGL 2.9.3 in the past and am now giving LWJGL 3.15 a shot in Kotlin.

I had a quad rendering nicely but now I'm using shaders it seems that openGL isn't initialized and I'm not sure why. I look through others' example code and can't figure out why mine isn't working. I've called glfwInit() and GL.createCapabilities()

```
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffd4af32957, pid=14068, tid=0x00000000000026ec

# Problematic frame:
# C  [lwjgl_opengl.dll+0x12957]

Register to memory mapping:

RAX=0x0000000071bd1d50 is an unknown value
RBX={method} {0x0000000016404640} 'glCreateShader' '(I)I' in 'org/lwjgl/opengl/GL20'
RCX=0x0000000000000000 is an unknown value

```

My best guess is that the problem lies somewhere in one of these two classes:

Main.kt

```
import org.lwjgl.glfw.*
import org.lwjgl.opengl.*
import org.lwjgl.glfw.Callbacks.*
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.opengl.GL11.*
import org.lwjgl.system.MemoryStack.*
import org.lwjgl.system.MemoryUtil.*
import shaders.StaticShader

class Main : Thread(){

private var window: Long = 0
private val width = 800
private val height = 600
private val title = "Swan LWJGL"

private val loader = Loader()
private val renderer = Renderer()
private val shader = StaticShader()

override fun run() {
    init()

    val model = loader.loadToVAO(
            floatArrayOf(
                    -0.5f, 0.5f, 0f,
                    -0.5f, -0.5f, 0f,
                    0.5f, -0.5f, 0f,
                    0.5f, 0.5f, 0f),
            intArrayOf(
                    0,1,3,
                    3,1,2))

    while (!glfwWindowShouldClose(window)) {

        renderer.prepare()
        shader.start()
        renderer.render(model)
        shader.stop()

        glfwSwapBuffers(window)
        glfwPollEvents()

    }

    loader.free()
    shader.free()
    glfwFreeCallbacks(window)
    glfwDestroyWindow(window)
    glfwTerminate()
    glfwSetErrorCallback(null).free()
}

private fun init() {
    GLFWErrorCallback.createPrint(System.err).set()
    if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW")

    glfwDefaultWindowHints()
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE)
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE)

    window = glfwCreateWindow(width, height, title, NULL, NULL)
    if (window == NULL) throw RuntimeException("Failed to create the GLFW window")

    glfwSetKeyCallback(window) { window, key, _, action, _ ->
        if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
            glfwSetWindowShouldClose(window, true)
    }

    stackPush().use { stack ->
        val pWidth = stack.mallocInt(1)
        val pHeight = stack.mallocInt(1)
        glfwGetWindowSize(window, pWidth, pHeight)
        val videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor())
        glfwSetWindowPos(window,
                (videoMode.width() - pWidth.get(0)) / 2,
                (videoMode.height() - pHeight.get(0)) / 2)
    }

    GL.createCapabilities()
    glfwMakeContextCurrent(window)
    glfwSwapInterval(1)
    glfwShowWindow(window)
    glEnable(GL_DEPTH_TEST)
    println(glGetString(GL_VERSION))
}

companion object {
    @JvmStatic fun main(args: Array<String>) {
        Main().start()

    }
}

}

```

StaticShader.kt

```
package shaders

import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL20.*
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

abstract class Shader(vFile: String, fFile: String){

private var vID = loadShader(vFile, GL_VERTEX_SHADER)
private var fID = loadShader(fFile, GL_FRAGMENT_SHADER)
private var id = glCreateProgram()

init{
    glAttachShader(id, vID)
    glAttachShader(id, fID)
    //bindAttributes()
    glLinkProgram(id)
    glValidateProgram(id)
}

fun start(){
    glUseProgram(id)
}

fun stop(){
    glUseProgram(0)
}

fun free(){
    stop()
    glDetachShader(id, vID)
    glDetachShader(id, fID)
    glDeleteShader(vID)
    glDeleteShader(fID)
    glDeleteProgram(id)
}

private fun loadShader(file: String, type: Int): Int{
    val src = StringBuilder()
    try{
        BufferedReader(FileReader(file)).useLines { it.map{
            line -> src.append(line).append("\n")
        }}
    }catch(e: IOException){
        e.printStackTrace()
        error("Error reading file")
    }
    val sID = glCreateShader(type)
    glShaderSource(sID, src)
    glCompileShader(sID)
    if(glGetShaderi(sID, GL_COMPILE_STATUS) == GL_FALSE){
        println(glGetShaderInfoLog(sID, 500))
        error("Error compiling shader")
    }
    return sID
}

open fun bindAttributes(){}

open fun bindAttribute(attrib: Int, name: String){
    glBindAttribLocation(id, attrib, name)
}

private fun error(msg: String){
    System.err.println(msg)
    System.exit(-1)
}

}

```

# Answer
Switch the statements `glfwMakeContextCurrent()` and `GL.createCapabilities()`

`glfwMakeContextCurrent()` creates the context, which needs to happen first. `GL.createCapabilities()` then retrieves function pointers and checks available extensions, but this needs an active context first.
> 2 votes

# Answer
I figured it out. It's throwing an exception because by constructing the StaticShader class when I declare it in my Main class variables, gl functions are being called by StaticShader's constructor before OpenGL has been initialized in the init() function of my Main class. I moved the initialization of StaticShader until after I'd initialized OpenGL and now it works fine.
> 1 votes

---
Tags: lwjgl, kotlin
---


# Question
Title: How can I read an image from a binary file?
I'm trying to put all the assets inside a binary file and then trying to read them from the file itself, without scattering all them around in separate folders to let them exposed. What I'm trying to achieve is something like the way that RPG Maker and Wolf Editor use to join all the images / sounds of the game into a single customized format file (e.g. Data.wolf).

It's a very simple security's method but is enough for what I'm planning.

For now, I have the following code for reading a PNG file inside the binary, that always prints an error's message when it trys to create a new surface from IMG\_LoadPNG\_RW, saying "Error reading the PNG file."

```
tString sResult{};
cFile_Manager::tRead_File oRead(sDir, std::ios::binary);

if(oRead.is_open()) {
    tString sLine{};
    while(getline(oRead, sLine)) sResult += sLine + "\n";
    oRead.close();
}else {
    throw cLog("\n\n[ERROR] Wrong dir passed.\n\nDIR: %s\n\n", sDir);
}

SDL_RWops* aRW{};
aRW = SDL_RWFromConstMem(&sResult, sizeof(sResult));

if(!aRW) // Error message

SDL_Surface* aSurface{};
aSurface = IMG_LoadPNG_RW(aRW);

if(!aSurface) // This is where SDL shows "Error reading the PNG file."

```

EDIT: Omg I made some mistakes, now this is the correctly code. Now it gives a different error: "PNG file corrupted by ASCII conversion"

```
    char* sBuffer{};
    if(oRead.is_open()) {
        oRead >> std::noskipws;
        oRead.seekg(0, oRead.end);
        int iLength = oRead.tellg();
        sBuffer = new char[iLength];
        oRead.seekg(0, oRead.beg);
        oRead.read(sBuffer, iLength);
        oRead.close();
    }else {
        throw cLog("\n\n[ERROR] Wrong dir passed.\n\nDIR: %s\n\n", sDir);
    }

    SDL_RWops* aRW{};
    aRW = SDL_RWFromConstMem(sBuffer, sizeof(sBuffer));

```

# Answer
> 1 votes
I was able to find a solution, which was a result of various information I collected here in Gamedev and StackOverFlow.

To increase the range of the solution, I'm going to pass the link from where I got it: https://stackoverflow.com/questions/4317318/how-do-i-pass-an-stdstring-to-a-function-that-expects-char

It's the first answer in this link

---
Tags: c++, sdl, assets, sdl2, binary
---