# Question
Title: Turn based Android game using google play games services
I want to develop a turn-based,multiplayer android game.Its very similar to chess.Is it possible to make entire game just by using google play games services(GPGS) ? ie, creating a game between 2 players,managing player moves,changing game states in database, all this can be done using GPGS? Also,is google-app-engine anyhow related to this ?

# Answer
Yes, Google Play Game Services can do all this for you. It supports leaderboards, cloud saving of progress, room based multiplayer lobby system, achievements and much more.

Here's documentation for turn-based multiplayer game service

Google app engine is hosting environment for your game, in cloud. However, you can only use Python, Go, Java and PHP to develop for it.
> 1 votes

---
Tags: google-app-engine, google-play-services
---


# Question
Title: How can I read inputs from buttons at the same time?
I am using the tk2d toolkit.

For my project, each player has their own button. I need to be able to get both buttons inputs (at the same time) so that I can figure out which up event first.

I run into the problem in this situation.

* First User presses their button down.
* Second user presses their button down, at the same time the first user is releasing their button.
* Button inputs aren't registered properly

I need to be able to determine who's up event fired first, while still letting both players push their buttons whenever they want.

# Answer
> 3 votes
Use the AND symbol to test if both buttons are down in an if statement. In C++ and C# it would look something like this:

```
if(BUTTON_A_PRESSED == true && BUTTON_B_PRESSED == true) { /* DO SOMETHING */ }

```

Otherwise you could use a nested if statement like so:

```
if(BUTTON_A_PRESSED == true)
{ if(BUTTON_B_PRESSED == true) { /* DO SOMETHING */ }  }

```

Hope this helps.

EDIT:

After reading the edit this may help.

If you want both buttons to be pressed down at the same time, but cause separate events to go off per user you will need to add the button down or button up event separately. If they are separate they will trigger individually, regardless of what the other button is doing. If you run this frame by frame you can add in a `bool` (or an `int` for multiple buttons) to to see who pressed first.

Here I use `int` to easier show the player number that pressed first:

```
int first = 0;

if (BUTTON_A_DOWN == true)
{
   if (first == 0)
   {
      first = 1;
      /* DO SOMETHING */
   }
}

if (BUTTON_B_DOWN == true)
{
   if (first == 0)
   {
      first = 2;
      /* DO SOMETHING */
   }
}

```

You can then use the `int` or `bool` to see who pressed first. You will need to decide how often you want to run this, as if it is every frame it will have seemingly no effect.

However, should you just want both players to react individually, using the `int` or `bool` is not needed as they will just check for the button press/release in order. This happens so fast that it won't be noticed by the players.

# Answer
> 1 votes
It's easy to check if those are both down. Just use IF with && and operator. Here is two examples for Unity, ready to run. Just place these to any script on an object that is in scene.

```
function Update () {
    if (Input.GetKey ("up") && Input.GetKey ("down"))
        print ("Pressing Up and Down");
}

```

However, this activates every frame and it can cause weird stuff, if you only need to react once to that double key press. This is how you can check double key press and react only once to it. Once you release either of keys, it can be activated again.

```
bool keysDown = false;
// Update is called once per frame
void Update()
{
    if (keysDown == false && Input.GetKey("up") && Input.GetKey("down"))
    {
        keysDown = true;
        print("Pressed keys down");
    }
    else if (keysDown == true && ( Input.GetKey("up") == false || Input.GetKey("down") == false))
    {
        keysDown = false;
        print("Released one of the keys");
    }
}

```

---
Tags: unity, unityscript
---


# Question
Title: How can I determine the extreme color values in a texture?
I am looking for a way to determine the most extreme color values for all of the texels in a texture. So for a texture consisting only of black and white texels, the extreme values should be (0,0,0) and (1,1,1) expressed in RGB format. For a color gradient from red to green I should get the values (1,0,0) and (0,1,0).

Now obviously I could do this on the CPU by iterating over all the pixels/texels of the texture and keeping track of the color values found to be most apart from each other, but this is probably relatively slow, so I am looking for a way to do this using the GPU/shaders.

Is this possible using shaders? I am not experienced with GPGPU, so a solution in HLSL/GLSL would be preferred. Or maybe there is a fast algorithm I could use on the CPU?

# Answer
The task is actually highly parallelisable on the GPU.

Here is an algorithm that should work, assuming *e.g.* a 1024×1024 source texture `ST`.

* create a 256×256 render target, `RT1`
* run a fragment shader that reads from `ST` and writes to `RT1` and does the following:
    + for each fragment in the render target
        - get the `(x,y)` fragment coordinates
        - sample 16 pixels from `ST` at `(4x+i, 4y+j)` for `(i,j)` in `[0,3]×[0,3]`
        - write the max value in `RT1`
* create a 64×64 render target, `RT2`
* run the previous shader, reading from `RT1` and writing to `RT2`
* \[…\]
* create a 1×1 render target, `RT5`
* run the previous shader, reading from `RT4` and writing to `RT5`

Each iteration of the process divides the number of pixels by sixteen. In the end, you get the maximum value in your single 1×1 texture in only five steps.

You can do the same for the minimum value, or devise a more complex shader that computes both the min and max. You can also play with how much you divide the resolution each time, depending on how many texture reads your GPU can do.

You can read about min/max textures in this article.

Here are the five steps of the algorithm when used on this 1024×1024 image:
> 9 votes

---
Tags: textures, shaders, algorithm
---


# Question
Title: Android: How to create fluent animations by using bitmaps and ObjectAnimator?
I want a resized bitmap item to move over the screen into a house. This basically works, but the movement is not fluent and is stuttering. Since I always have to draw both the resized background and the house due to some alphas (both are exactly as big as the screen), the animation runs very slow, because **invalidate()** is no fast enough. At every bitmap move, **invalidate()** is being executed.

This is a very simplified example of my view to show what I'm doing.

```
public class GameView extends View implements ValueAnimator.AnimatorUpdateListener
{
    //more code

    @Override
    protected void onDraw(Canvas canvas)
    {
        canvas.drawBitmap(ResizedBitmapMapping.getBackground(), 0f, 0f, null);
        canvas.drawBitmap(item.getBitmap(), item.getXY().getX(), item.getXY().getY(), null);
        canvas.drawBitmap(ResizedBitmapMapping.getHouse(), 0f, 0f, null);
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation)
    {
        invalidate();
    }

    public void setActive()
    {
        item = new Item(ResizedBitmapMapping.getItem());
        XYHolder startXY = new XYHolder(0f, height);
        XYHolder endXY = new XYHolder(width * 2 / 3, height / 4);

        animator = ObjectAnimator.ofObject(car, "xY", new XYEvaluator(), startXY, endXY);
        animator.setDuration(2000);
        animator.addUpdateListener(this);
        animator.setRepeatCount(ObjectAnimator.INFINITE);
        animator.start();
    }

    //more code

}

```

My questions: Is the concept of drawing basically wrong? If yes, how does an efficient drawing concept look like? If the concept is right, is it just a case of optimizing like drawing just "rects" instead of the whole background and house or something?

# Answer
I found a solution which works for my purposes since I don't use many bitmaps on the canvas. It's absolutely fluent when I **invalidate()** just once when all bitmaps (background and so on) have been loaded and then in onAnimationUpdate() I only partially invalidate the canvas by this method:

```
invalidate(int l, int t, int r, int b);

```

That means I only invalidate the rect around the moving bitmap(s). Since they lie close together, I don't get such a big "dirty rect" and it's very fluent. If the bitmaps are scattered around the whole surface, the trick would probably be to invalidate each bitmap after another (not tested yet). That would mean that one complete move of all bitmaps would take as long as every single bitmap has been invalidated. It's some kind of a juggling act because you have to think about what is slower: A very big dirty rect invalidated just once or many invalidates of several dirty rects.

By the way: I wonder how all the games on Android are designed. They are always absolutely fluent. Do they all use OpenGL?
> 2 votes

# Answer
When you want to draw something fast on the Android GUI don't use the View.onDraw() method. It is too slow. Generally everything is done one the main(gui)-Thread, including each onDraw() of each View. And the time of the calls to each .onDraw depend on everything else on the main thread. To be fast you want to draw onto a canvas on a separate thread (with the help of a SurfaceView). I recommend to look at the Drawing and Canvas topics in the Android Developer documentation: http://developer.android.com/guide/topics/graphics/2d-graphics.html.

Edit: Well I can't say much without looking at your new code and I have no own code available, I use this technic on more static canvas. On another stackoverflow forum there is a good answer, with working code (tested by myself before writing here) with a smooth animation of a ball and a moving background. I copy the explanation here: https://stackoverflow.com/questions/4938822/how-can-i-use-the-animation-framework-inside-the-canvas:

> The Android animation class applies to objects such as views and layouts. The canvas is just a surface for drawing which is either part of a View or linked to a bitmap. In **onDraw in a custom view only one frame is drawn at the time until next invalidate is called**, which means that you have to draw your animation frame by frame. Here is an example of bouncing ball which rotates, which you may find useful.

When this is not smooth enough, and this will happen, when start using multiple moving objects (for instance 30), you should start thinking about switching to Open GL.
> 4 votes

---
Tags: android, animation
---


# Question
Title: Does LibGDX abstract OpenGL ES away or can I still use my OpenGL ES knowledge?
I've been learning OpenGL ES, and am now turning my attention to using LibGDX.

My main concern with LibGDX is, if needed, will I be able to apply my OpenGL ES knowledge to something if needed and essentially override bits and pieces of the framework, or does LibGDX essentially hide any implementations of OpenGL?

# Answer
> 1 votes
Although libgdx largely abstracts away the OpenGL component for most of the basic things, you can still use it in your code for the more advanced stuff.

Usually though, if you dig a round for a while you'll probably find that about 99% of the time whatever you want to do with OpenGL has already been implemented somewhere in libgdx.

Source:

Opengl-es-support

---
Tags: opengl, java, android, libgdx
---


# Question
Title: Scaling entity by screen height (simulating depth on orthographic camera)
i want my entities to be at 100% scaling (for example 128x128 pixels) when they are at 40% of the screen height (for example 480 pixels at 100%), so when they are at 41%, they are at 99% scaling (126,72x126,72 pixels).

any idea of how i can achieve this? thanks

# Answer
> 0 votes
This seems like a 2D view in which case it should be feasible to project the entity's rendered size at 100% scaling, then figure out the ratio of that value to the total viewport size and go from there.

---
Tags: mathematics, scale
---


title: Is it okay for UVs to touch border?

text:
# Question
Title: Is it okay for UVs to touch border?
As a matter of habit I always shrink UVs to just below the full texture space, even for single island things like sprites. Can I have my UVs touching the actual border or is this bad practice?

# Answer
UVs touching the border is pretty routine. However a related thing you probably want to know about is repeating vs. clamp texture; the idea is to set the image so that borders are rendered correctly.
> 1 votes

---
Tags: uv-mapping
---


# Question
Title: How can I manage entities(in entity component system) using Lua scripts?
Suppose I have a code like this in C++

```
// Game.cpp
Entity* hero;
Entity* witch;
... // entity initialization

if(/player near witch/) {
    if(hero->get<HealthComponent>()->getHealth() < 100) {
        say("Let me help you");
        witch->get<GraphicsComponent>()->setAnimation("witch.heal");
        hero->get<HealthComponent>()->setHealth(100);
    }
    else {
        say("Go away!");
    }
}

```

Suppose I want to put this code into Lua script, so I make an "interact" function in C++

```
void interact(Entity* first, Entity* second);

```

And call it like this:

```
interact(witch, hero);

```

Then I can call lua script, which gets first and second entity IDs and does something like this:

```
-- Script.lua
function interact(firstId, secondId)
    if(getHealth(secondId) < 100) then
        say("Let me help you")
        setAnimation(firstId, "witch.heal")
        setHealth(secondId, 100)
    else
        say("Go away")
    end
end

```

And then I can define wrapper functions in C++ like this

```
void setAnimation(int firstId, const std::string& animationName) {
    Entity* e = entities[firstId];
    e->get<GraphicsComponent>()->setAnimation(animationName);
}
// etc.

```

and call it from Lua. But this gets quite troublesome as I need to write lots of binding and wrapping(like "setAnimation") functions. Is there any other methods to control entitity behaviour using Lua?

# Answer
Writing binding functions gets tiresome pretty fast, and is error prone. There are two ways I can think of on how to improve this:

**1)** Use some Lua wrapper code that creates the interface functions you need. I did see on your blog that you have used *LuaWrapper*. Not sure how much support that lib have but there are others that use templates to create the binding functions. For my own project, I wrote my own system that also have the name *LuaW*. This is an example of what my code looks like. All objects are managed (created/destroyed) in the C++ code:

**C++ side:**

```
LuaW_Class<CameraComponent>( scriptEngine->m_pkState, "CameraComponent");
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "GetName", &CameraComponent::GetName);
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "GetCamera", &CameraComponent::GetCamera);
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "AddTestRenderer", &CameraComponent::AddTestRenderer);

LuaW_RegisterGlobal<World>(scriptEngine->m_pkState, "World", m_world.get());

```

**Lua side:**

```
local cament = World:MainScene():CreateEntity("blueprints/camfront.blueprint", Vector3:new(0,0,0) )
camcomp = cament:GetComponent("CameraComponent")
camcomp:AddTestRenderer()

```

By using a wrapper lib like that you can stop writing binding functions, unless of course you wish to do something special like returning multiple values.

**2)** The second way is to keep the components and as much stuff as possible in Lua code. So most of your game will be in Lua and only the functions you really need to write in C++ will require a binding function.
> 1 votes

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


# Question
Title: How can I correctly line up differently sized animation frames with a character?
For educational purposes, I'm developing a 2d game without APIs or libraries. Currently I'm stuck with a sprite drawing problem.

To store sprites for drawing (assuming I have the sprites I need all in one sprite sheet), is it better to

1. store just the coordinates for each sprite for each entity, and then draw only the corresponding part of the sprite sheet when the entity should draw itself, or
2. store actual parts of the sprite sheet in each entity and the draw each the cropped sprite?

Another thing I'd like to learn is how to handle sprites with different sizes. See Zelda, for example: Link's walking sprites are all about the same size, regardless of his position or orientation. But when he attacks, the sprites include his sword and depending on his orientation, some sprites are wider and some longer.

Is there a good way to position and align sprites with different sizes relative to a part of the character—their foot, for example? Should I store some sort of offset for each sprite along with the sprites?

# Answer
> 4 votes
I assume you will be using some modern rendering API to draw to the screen, such as OpenGL or D3D. You will certainly want to batch sprites as much as possible and use sprite sheets to reduce the number of textures. A sprite sheet is nothing more than a Texture Atlas (also read this). Once you have a Texture Atlas up and running, it will be up to you how you assign sprite frames/images to them. On common practice is, for example, to use one altas per game character, one for static elements, one for background elements, etc.

To each sprite you can assign a reference to the altas where its frames are and a list of locations inside the altas where the frames are. Instead of atlas locations you can actually store raw texture coordinates (UVs).

OK, so suppose you have a sprite sheet/texture atlas like this one:

You will also need some extra info about the rectangles of each sprite frame (each one of those cats is a sprite frame). You can use anything from a `txt` file with `(x,y,w,h)` sets on it, from a more complex XML file. But the basic thing you need to specify is the rectangles in image space where the frames are.

So your atlas class would look something like:

```
class TextureAtlas {

    LoadTexture(string filename);  // Loads the image itself
    LoadMetadata(string filename); // Loads the metadata describing the atlas nodes/sprite frames

    Region GetRegion(int index);

    Texture  texture; // The actual image. Immutable
    Region[] nodes;   // The nodes/frames. Each is a rectangle inside the 'texture' image
}

```

Once you have something like that you can define a sprite with:

```
class SpriteFrame {

    // The region inside the atlas texture
    // where this frame resides; As texture coords, ready for rendering.
    float u0, v0;
    float u1, v1;

    const TextureAtlas * atlas; // Just a pointer/ref, not the actual object.
                                // This allows you to share a texture with many sprites.
}

class Sprite {

    // And a sprite is just a collection of frames.
    SpriteFrame[] frames;
}

```

Then you would use such setup in much this way:

```
TextureAtlas catAtlas;
catAtlas.LoadTexture("runningcat.png");
catAtlas.LoadMetadata("runningcat.meta");

Sprite catSprite1 = new Sprite(catAtlas);
Sprite catSprite2 = new Sprite(catAtlas);
...

```

The constructor of `Sprite` still need to go thru every sprite frame and get the UVs from the atlas to set them up. Something like:

```
for each SpriteFrame frame in Sprite
{
    Region region = atlas.GetRegion(i);
    frame.u0 = region.x / float(atlas.Width());
    frame.v0 = region.y / float(atlas.Height());
    frame.u1 = (region.x + frame.w) / float(atlas.Width());
    frame.v1 = (region.y + frame.h) / float(atlas.Height());
}

```

And finally, the rendering would be very simple and efficient:

```
func DrawSprite(Sprite s)
{
    // Apply/bind the atlas texture once
    s.atlas.Apply();

    for each SpriteFrame frame
    {
        // Send down the frame texture coords (UVs)
        // and geometry vertexes to the rendering API.
        // The texture is already set and ready to be used.
    }
}

```

---
Tags: 2d, animation, sprites, spritesheet
---


title: Unity Texture Problem

text:
# Question
Title: Unity Texture Problem
http://www.gfycat.com/FlawedLimpingGrizzlybear http://www.gfycat.com/UnawareQuerulousHawk

Every texture and shader has the same problem. It seems like the problem has nothing to do with either.

Tried all the things my friends suggested I should, reimported everything, restarted my machine, nothing seems to work.

# Answer
I created a new project, ported everything over. It solves the problem, so I assume it is a Unity bug.

I have no idea how to recreate it though.
> 0 votes

# Answer
This might be related to using texture atlas techniques combined with mipmapping.

Mipmapping means that you generate scaled down versions of your textures. These are used when looking at textures that are at a far distance or viewed at a sharp angle. The reason for this is that you want to sample a larger area of the texture when looking at it from a distance. For instance, consider using a black-white checkerboard texture. If you look at it from a close distance, you can see the individual tiles. If you look at it from a far distance, the texture will appear uniformly gray, as you cannot distinguish between individual tiles. This is what mipmapping achieves. Without mipmapping, you'll be sampling a single point from your texture, which can cause flickering as you move the camera.

A texture atlas means that multiple textures (eg, different faces of your cube) are stored in the same texture. This is useful to prevent excessive file access operations and texture allocations. Different textures are essentially stored in the same texture, layed out across the texture. Don't worry about the term "texture atlas". Essentially, if all faces of your cube are in the same texture file, you are using an atlas.

When these two techniques are combined a problem can occur for the smaller mipmap levels. As mipmaps are generated by downsizing the original image, it is possible for textures in the texture atlas to bleed into neighbouring textures. For instance, if you have an atlas texture with four different subtextures (eg. a red, green, blue and yellow one), the lowest mipmap level would be the average of all these subtextures.

I believe that this is the effect you're seeing in the image you provided. I'm not very familiar with Unity, but here are some general solutions you could try:

* Limit the amount of mipmaps generated (in your case, level 4 seems to be the last correct mipmap image). Note that this could cause flickering when looking at the texture from a distance, while moving the camera.
* Choose a clever alignment of the subtextures in your texture atlas. Mipmaps are generated by scaling down in powers of two. If you align your textures on a 2x2 grid, a 4x4 grid, a 8x8 grid, or any other power of two grid, you should be able to generate higher level mipmaps without bleeding.
* Add guard spaces inbetween the different textures in your texture atlas. This means that you leave a gaps inbetween the faces of your cube texture. It would be wise to fill these gaps with the same colour as the neighbouring subtextures.
> 1 votes

---
Tags: unity, textures
---


# Question
Title: 2D Collision in JavaFX - Bad accuracy with .intersects()
I have several Shape objects - `Circle`, `Rectangle` and `Polygon`.

I use the built-in `.intersects(Bounds1, Bounds2)` method to detect collision but it's quite inaccurate.

```
Circle c1 = new Circle(20);
Bounds c1Bounds = c1.getBoundsInParent();
Rectangle r1 = new Rectangle(20,20);
Bounds r1Bounds = r1.getBoundsInParent();
... etc for other Shape objects

```

My collision code:

```
if (c1Bounds.intersects(r1Bounds) {
    //collision happened.
}

```

Why is the collision accuracy so bad and how can I improve it? The collision detection is REALLY bad for polygon objects. It is literally at least 50 pixels off.

# Answer
> 2 votes
`getBoundsInParent()` returns the bounding box around the shape — a rectangle.

The built-in `intersects()` check works only for rectangular shapes, not for circles, polygons, etc. For these, you'd need to implement the check yourself.

---
Tags: java, collision-detection, physics
---


# Question
Title: How can I use imprecise accelerometer data for controls?
I want to rotate an object with respect to the phone's position. I use the accelerometer output to detect orientation:

```
float roll = Gdx.input.getRoll();
float pitch = Gdx.input.getPitch();
float azimuth = Gdx.input.getAzimuth();

Vector3 accel=new Vector3(accelX, accelY, accelZ);
bat.transform.setToRotation(0f, -1f, 0f, pitch);

bat.transform.setFromEulerAngles(azimuth, -pitch, -roll);

```

However, the accelerometer data fluctuates so strongly that the object jitters.

How can I deal with this?

# Answer
I don't know if it is because of a poor component that causes the false readings or a extremely precise component that registers the spinning of the earth, as it orbits the sun, as our solar system spirals through the galaxy. Either way, this is a common problem. The solution is to use some type of filter to smooth out the "extra" readings. There are several methods that you can use.

**DeadZone** \- simply track the last "valid" event and compare it to each new accelerometer event . If the difference between the two is greater than an threshold value then count the new reading as a valid event. This is simple to implement, but can make a blocky response since the readings will only move by the threshold value or greater.

**Low Pass Filter** \- This works by only allowing a value to change by a percentage(alpha) of the difference between the previous value and the new value. Simply `output = previousValue + alpha * (newValue - previousValue)` This works well, but might require some tweaking of the alpha to find a value that works well for your needs. A low alpha will give you a consistent value while the device is idle, and a very fluid motion reading, however it will cut down any sharp peaks in movement. A higher alpha will give a more responsive feedback but will not remove all the noise.

**Infinite Impulse Response filter (IIR)** \- It works by combining a percentage(alpha) of the previous value with the opposite percentage of the new value. `ouput = previousValue * alpha + (1.0f - alpha) * newValue`. This can produce similar results as a low pass filter, however the alpha value is just the opposite. In this case, a higher alpha will give you a smoother response and a flatter line, while a lower value will give you a more more responsive result, but also might still have a bit of noise.

**Rolling Average** \- Combine the last X number of sensor events and then divide by X. This creates a smooth response while the device is in motion. The few reading averaged the more noise you will see, while the more values that you average the more "sluggish" the response will appear. If you want to try this I would suggest starting with averaging the last 5 value and then go from there.

**FPS** \- For lack of a better term, let's call this "frames per second." You can simply only accept a sensor event if a given amount of time has passed thus only allowing so many valid sensor event per second. While this is very easy to implement, I would caution that this can produce a very blocky and sluggish response. To get this method to acceptably quiet any idle time noise there is usually too few readings per second. This causes the blockiness and sluggishness.
> 6 votes

---
Tags: android, libgdx, bullet-physics, controllers
---


title: Take a screenshot from camera problem

text:
# Question
Title: Take a screenshot from camera problem
I use script below to take a screenshot from camera. It's working fine. However, when I take a screenshot again (pressing k multiple times), its old image is not clear from the memory and it keep drawing over same image over and over again. If object is moving while taking screenshot multiple times, image I will get all frame combine into one image with every frame in the same image. What should I do to fix this problem?

```
using UnityEngine;
using System.Collections;

public class HiResScreenShots : MonoBehaviour {
    public int resWidth = 2550;
    public int resHeight = 3300;

    private bool takeHiResShot = true;

    public static string ScreenShotName(int width, int height) {
        return string.Format("{0}/screenshots/screen_{1}x{2}_{3}.png",
                             Application.dataPath,
                             width, height,
                             System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
    }

    public void TakeHiResShot() {
        takeHiResShot = true;
    }

    void LateUpdate() {
        takeHiResShot |= Input.GetKeyDown("k");
        if (takeHiResShot) {
            RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
            camera.targetTexture = rt;
            Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.ARGB32, false);
            camera.Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camera.targetTexture = null;
            RenderTexture.active = null; // JC: added to avoid errors
            Destroy(rt);
            byte[] bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName(resWidth, resHeight);
            System.IO.File.WriteAllBytes(filename, bytes);
            Debug.Log(string.Format("Took screenshot to: {0}", filename));
            takeHiResShot = false;
            Debug.Log("Capture!!");
        }
    }
}

```

# Answer
> 0 votes
Seem like it's fixed after I set Camera "Clear Flags" to "Skybox"

---
Tags: unity, screenshot
---


# Question
Title: Calculating the winding and normal when programatically adding triangles to a mesh
I'm writing a program that takes a 2D planar polygon and extrudes it to a 3D mesh with a given height. I identify triangle edges that are borders of the polygon and now I'm trying to automatically compute the two triangles required for the extrusion of the border. However, I'm stuck at how to compute the correct winding and normals

My start situation is this: I have the two coordinates of the edge (marked in white) and the normal of the original triangle (marked in orange)

Using this information I'm trying to compute two triangles which should result in:

The 4 vertices are easy to compute (just the two vertices of the edge and two more at a different height). The normal should be perpendicular to the original normal but to do that I need a second reference point. It doesn't seem to be as simple as using the centroid of the triangle.

The triangle winding confuses me. I need a **counter-clockwise** winding and I guess I could determine which vertices to use based on the normal but how is not immediately apparent to me.

# Answer
> 2 votes
I don't completely understand the problem you're having, but this is a sketch of an extrusion algorithm

Supposing `polygon` is an array of 3D points in counter-clockwise order (I guess they don't have to be convex, or even coplanar), and `direction` is a 3D vector determining the direction in which you want to extrude your polygon, this is what I came up with (in no particular language)

```
function extrude(polygon, direction)
    triangles = []
    -- Top cap
    for p = 0 to count(polygon) - 2 do
        p0 = polygon[0] + direction
        p1 = polygon[p + 1] + direction
        p2 = polygon[p + 2] + direction
        normal = normalize(cross(p1 - p0, p2 - p0))
        triangles.push(new triangle(p0, p1, p2, normal))
    end

    -- Bottom cap
    for p = 0 to count(polygon) - 2 do
        p0 = polygon[0]
        p1 = polygon[p + 2] -- pointing down now...
        p2 = polygon[p + 1]
        normal = normalize(cross(p1 - p0, p2 - p0))
        triangles.push(new triangle(p0, p1, p2, normal))
    end

    -- Sides
    for p = 0 to count(polygon) do
        p0 = polygon[p]
        p1 = polygon[(p + 1) mod count(polygon)]
        p2 = p0 + direction
        p3 = p1 + direction
        normal = normalize(cross(p1 - p0, p2 - p0))
        triangles.push(new triangle(p0, p1, p2, normal))
        triangles.push(new triangle(p0, p2, p3, normal))
    end

    return triangles
end

```

The normals created by this snippet point outwards for each face. You could also average them with the normal of the adjacent face to create a softer look for polygons with lots of faces...

Would something like this work for you?

---
Tags: normals
---


# Question
Title: Does allocating and freeing a huge chunk of memory at startup "clean up memory?"
The book *Game Coding Complete, Fourth Edition*, chapter 5 (*Game Initialization and Shutdown*), section *Checking Memory* contains this interesting code sample:

```
bool CheckMemory(const DWORDLONG physicalRAMNeeded, const DWORDLONG virtualRAMNeeded)
{
    MEMORYSTATUSEX status;
    GlobalMemoryStatusEx(&status);
    if (status.ullTotalPhys < physicalRAMNeeded)
    {
        // you don’t have enough physical memory. Tell the player to go get a
        // real computer and give this one to his mother.
        GCC_ERROR("CheckMemory Failure: Not enough physical memory.");
        return false;
    }
    // Check for enough free memory.
    if (status.ullAvailVirtual < virtualRAMNeeded)
    {
        // you don’t have enough virtual memory available.
        // Tell the player to shut down the copy of Visual Studio running in the
        // background, or whatever seems to be sucking the memory dry.
        GCC_ERROR("CheckMemory Failure: Not enough virtual memory.");
        return false;
    }

    char *buff = GCC_NEW char[virtualRAMNeeded];
    if (buff)
    {
        delete[] buff;
    }
    else
    {
        // even though there is enough memory, it isn't available in one
        // block, which can be critical for games that manage their own memory
        GCC_ERROR("CheckMemory Failure: Not enough contiguous memory.");
        return false;
    }
}

```

This raises some questions.

The first part just asks the OS (Windows) how much physical RAM is available. The curious part is the second one, which allocates a huge chunk of memory and frees it right away:

```
char *buff = GCC_NEW char[virtualRAMNeeded];
if (buff)
{
    delete[] buff;
}

```

The author goes on to explain:

> ... this function allocates and immediately releases a huge block of memory. This has the effect of making Windows clean up any garbage that has accumulated in the memory manager and double-checks that you can allocate a contiguous block as large as you need. If the call succeeds, you've essentially run the equivalent of a Zamboni machine through your system's memory, getting it ready for your game to hit the ice...

But I have my reservations on that.

"Cleaning garbage that has accumulated in the memory manager?" Really? If the game has just started, shouldn't there be no garbage?

"Making sure you can allocate a contiguous block?" In the very specific case where you are going to manage memory yourself, this would them make some sense, but still, if you do allocate a lot of memory right of the bat, you pretty much make it impossible for any other application to run in the system while yours is on.

Also, isn't this likely to force the OS to commit all that memory, and as consequence evict a lot of memory to the swap disk space, slowing your app startup a lot?

Is this really a good practice?

# Answer
> 12 votes
One thing that pre-allocating a large chunk of memory *could* do, if your computer was low on RAM, might be to force the OS to free some extra space by swapping parts of other programs' memory space to the disk.

Since such swapping is generally a very slow operation that pretty much freezes your program while it's happening, there could be some advantage to ensuring that, if it's going to happen anyway, it will happen *before* your game starts rather than in the middle of gameplay.

That said, forcing a swap-to-disk like this is not exactly 100% reliable:

* On many virtual memory implementations, merely allocating memory doesn't actually trigger any swapping; rather, it only happens when you first access each page of the memory you allocated. (This is certainly true on modern versions of Linux, with memory overcommit enabled, as it is by default; I don't know for sure how different versions of Windows handle it.)

Thus, if you really want this code to "clean up memory", you should probably add a `memset()` call or equivalent to actually write data to every part of the array (or at least to the first `physicalRAMNeeded` bytes of it) before releasing it.
* Also, forcing the OS to swap other programs out of the RAM like this doesn't mean that they'll *stay* out of it. Windows is a multitasking OS, and as soon as one of those swapped-out programs wants to run again and to use its swapped-out data, it will get swapped back in, potentially freezing your game again.

Thus, this trick is generally only useful if the RAM is being eaten up by large chunks of data that are not being actively accessed (such as large documents left open in the background in some editing software). Web browsers tend to be particularly problematic in this regard, since, even if you're not actually using a web page opened in some background tab, the page may still have scripts running on it that force it to be kept in RAM.

(There *are* ways for a program to actually tell the OS to lock a part of its memory space into RAM and prevent it from being swapped out, but these typically require elevated privileges. In any case, the code you posted does not appear to be using any such methods.)

Basically, this trick seems only useful in that relatively narrow borderline situation where the user *would* have enough RAM to run your game (and any other software actively running in the background) without swapping, but that RAM is currently filled with inactive and unused open files or other data that can and should be swapped to the disk while your game is running. In such situations, it *may* be effective in making your game seem smoother and more responsive, by replacing occasional small swap operations during gameplay with a single one during startup.

# Answer
> 26 votes
I don't know how old that writeup is, but I'd say it's pretty old. In modern Windows (XP and newer, but specially on 64-bit versions), I would say doing something like that will have little to negative impact on the startup of your game.

First of all, remember that the address space is virtualized for each process. As far as your process is concerned, you have the entire address space to yourself, and you will always get contiguous (virtual) memory, regardless of whether that memory is physically contiguous or not.

In fact, whether or not the memory is contiguous in physical memory is not something you have control over. The OS will choose how to allocate the physical blocks as it sees fit, and nothing you do at the application level can have effect on the benefits (if any) of having contiguous physical memory.

You do need to care about virtual memory fragmentation if you keep on allocating and freeing memory of different sizes for a very long amount of time. This is of course much less relevant with a 64-bit address space. Games don't usually run for months, so you most likely won't have to care about this, unless we're talking about long running game servers.

Even if you do allocate lots of memory of wildly different sizes in a 32-bit machine, modern memory allocations are pretty good, so it is unlikely you will get virtual memory fragmentation issues unless you're actively looking for them

To be honest with you, I don't know what that writer is going on about. Even if the address space was shared, and you did get a huge contiguous block in physical memory, by freeing it, you're saying you don't care about it anymore. There are other programs running on the background doing their own allocations, so even if your huge malloc succeeded, nobody will guarantee the next one will succeed as well.

I think that's a case of "it worked for some reason I don't really understand, so I made something up to explain it".

---
Tags: c++, memory
---


title: Procedural terrain generation

text:
# Question
Title: Procedural terrain generation
Currently I have a procedurally generated planet using multiple octaves of perlin noise. The thing is, that I don't generate heightmap, but rather get the values of perlin function and apply them directly to vertices.

I'd like to add more surface features. Right now terrain is very rough, there are no flat areas, or rivers.

How can I add those features? Normally there would be some sort of heightmap-filtering, for example voronoi + perlin = good-looking terrain with flat surfaces.

Is it possibile to somehow mix fractal algorithms? If so how, which ones and where can I find more info about it?

# Answer
Diverse terrain can be created using various arithmetic adjustments of randomly generated numbers. As I'm sure you realize, adjusting your generated values (for example, multiplying by two) would change the result you have.

If you are familiar with programs such as Photoshop or Paint.net you've probably heard of the concept behind multiplying colors, or burning, adding, etc. These are pretty simple concepts which wouldn't take much googling at all to find code for. If you had a variety of heightmaps, using these effects you could start creating pretty diverse terrain.

So where am I heading with this? Expand your skills with random generation. Change your code so that it merely generates a single canyon throughout a flat terrain (or 'flat' around your planet). Try using diamond square algorithms and mucking around with the variations to create extremely mountainous terrain.

By creating all sorts of effects, you're essentially creating a library of algorithms which you can now mix and mash to get your final product.

'But these are still all the same effect around the entire planet!' Well this is where those image effect concepts come back in. Say for example, I am making a terrain out of two perlin noise maps and a diamond square generation. For a single vertex, I generate the height as usual for each map. This may give me the values p1, p2 and ds1. In your current implementation, you are straight off using p1 as the height.

What I am suggesting, is you use something like (p1 * p2) + (ds1 * (1 - p2)) as the height. Just to clarify, the 'lower' the second perlin noise point is, the more the vertex is based off the first perlin noise map. the 'higher' the second perlin noise point is, the more the vertex is based off the mountains diamond square calculation.

Given the nation of perlin noise (especially when scaled up a lot), this will create effects where some patches are mountainous, and then that dies out to be the hilly nature of perlin noise in other areas.

Of course this is an extremely basic example for the potential behind the idea.

TLDR; mash multiple terrain generations together, not necessarily simply with averages or additions. Multiply some generations by others, then add them to a third and then multiply by a fourth! Think photoshop layer effects
> 5 votes

---
Tags: 3d, algorithm, procedural-generation, procedural
---


# Question
Title: How can I predict player-to-projectile collisions in Box2D?
I'm making a real time shooting game with Box2D as the physics engine. The gameplay is mostly about trajectory, like Angry Birds. I want to make a slow motion effect and move camera to the player when he's killed, but the effect should start when the stone is still in the air, before the collision actually happens.

The magnitude of damage is only calculated at collision, based on impulse. Because it's a real-time game, the player must be able to move their character's physics body without lag.

How can I predict their death? Is it even possible? I could raycast, but what if another object moves to block its path?

# Answer
> 2 votes
Why calculate the trajectory for the sounds/slow down effects?

If you split the act of slowing down the camera and playing effects into sections upon approach to your squishy victim then you can essentially play them on condition of their proximity.

This is a great example that comes to mind. The proximity slow down effects employed in Peggle

The ball gets close to the peg and starts slowing down. This is actually based completely off proximity, no trajectory involved. If it gets close enough to the last peg it starts a drum roll and slows the game-play down, if it does not hit the peg and goes out of range you hear "Awww.. :(" and all returns to normal, but if it collides you will get the full fledged Overture and winning screen.

This is a great technique if you approve of making your player go "Holy cow, I nearly got hit!". If you have a start-up sound/effect for a death cam that will play before impact then simply trigger this when the stone is close enough that even if the player moved at maximum speed in any direction - they have a great change of getting squished.

Say your rock is falling and you want to begin the slow down effect to ~4m away from the player: You start by triggering slow-down, move your camera and start focusing on the player - if the rock is then interrupted by other debris then simply exit the slow down focus and your player continues as normal.

This is essentially how Peggle handle their slow down effect and trigger the end game music and is perfectly viable for using on your camera/rock/squishy pre-empting death-scene scenario.

---
Tags: physics, box2d, game-mechanics, movement-prediction
---


# Question
Title: How can I work on a game that I don't like?
I started making a game with a friend, and I want to see it through. But the deeper we get into the project, the more I dislike the game.

How can I stay motivated and keep getting things done, if I don't really feel invested in the end product?

# Answer
Find something in the project that you are really invested in. Even if the ultimate game isn't that thing, hopefully there's some part of the project that you can connect with.

For example, for me it's often about the new technology that I'm learning. Even if I'm meh about the end product, usually I get pretty jazzed about all the new techniques that I'm learning while I work.
> 1 votes

---
Tags: project-management
---


# Question
Title: At what point of the game should I request users leave a review?
I'm planning on displaying a dialog requesting users review my Android game, but I'm wondering at what point I should display the dialog. I wont show the dialog until the user has completed several levels, but I can't decide where in the game flow to place it.

I have several options.

1. On game launch - my concern with this is that they're looking to play a game at this moment in time, not review the game.
2. On game exit - this seems a fairly classic time to do it, but many users wont quit by pressing back, often they'll just use the home button, or just turn the phone off. Also, if a user is stopping playing then they'll often be doing so because they've got something else to do.
3. On level completion - I will only request the review on successful level completion as I assume a player will be feeling good about the game at that point in time. My concern with this is that it interrupts game flow.

I'd be interested in hearing the thoughts of others on this.

# Answer
Option 3 sounds like a good idea, but! Don't prompt the user in a way that they have to perform an action to get past the reviewing. I find this highly annoying. Instead, create a button somewhere in the score screen which they can click when they feel like it.
> 4 votes

# Answer
I think you've probably answered your own question. There are concerns with both options 1 and 3 as they interrupt the flow of getting into the game and while playing. If I were to ask users to leave a review it would be on exit of the game. I have had apps ask me to review the application on first start-up without even using it in the first place. I found this to be fairly annoying as it should recognize that I haven't used the app. Reviewing during play is another one I've come across in games but the fact that it happened during play would actually affect the review of the game itself because it has just interrupted my enjoyment of an otherwise great game. With option 2, I understand your concern with users not pressing the back button and using home etc, but the fact that users are using the home/power button is indication of the fact that they're not in the mindset to review in the first place and will probably rush a review with a not so accurate evaluation. I know most of time I use the back button and when an app asks me to review, I usually provide honest feedback as I have had a chance to use the app and properly evaluate its features without interruption. Hope that helps!
> 1 votes

# Answer
What I've seen other popular games do is prompt you when you open the app, but only after you've played it once or twice. I'm guessing you could record the number of times the app has started, and then after they've opened it however many times, you can prompt them to review.
> 0 votes

---
Tags: mobile
---


# Question
Title: How to calculate whether a cuboids face edge is infront of or behind another for sorting
I'm building an isometric game, I want to position and sort objects in a particular way. All my entities have 3d bounds which determines their cuboid, looking my example, a different edge is used to decide if a cuboid is in front of another, depending on whether the point b2 is left or right of a2.

I have already calculated all the points a1,a2,b1,b2 which are x,y,z I think I basically need to virtually draw "aedge" and "bedge", and compare some intersection.

If b2 is right of a2 the green cuboid (b) is consider in front of the red cuboid when bline is south east of aline.

If b2 is left of a2 the green cuboid (b) is considered in front of the red cuboid when bline is south west of aline.

Please forgive my ignorance here, I'm sure there's some terminology I should have used here. I'm struggling to put down in words what it is I need.

# Answer
I'm not sure how you have your axes set up, so this will work for any situation where the faces are parallel.

Subtract ax from bx. (ax is any point/vertex on face/edge a, bx is any point/vertex on face/edge b) This gives you a vector. Then do a vector projection onto the normal of the face you are testing (which is a unit vector). I.e.:

```
#pseudocode

v = bx - ax // e.g. a1 - b1
n = (-1, 0, -1).normalize // Change this based on how your axes are set up
vec_proj = v.dot(n) // dot product of the vector and normal

if (vec_proj > 0) {
    // in front
} else {
    // behind or overlapping
}

```
> 1 votes

---
Tags: javascript, isometric
---


# Question
Title: How to change from 60FPS to 30FPS while keeping things smooth?
Here is my current game loop:

```
final int ticksPerSecond = 60;
final int skipTicks = (1000 / ticksPerSecond);
float dt = 1f/ticksPerSecond;

while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){
        updateLogic();
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;

```

On **most** devices I've tested my game on (this is an Android game BTW) it runs quite nice.

As you can see, I'm using a fixed time-step (defined as my ticks per second).

If I reduce my Ticks Per Second to 30, everything runs at the same speed but is nowhere near as smooth. I keep hearing people say that 30fps should be OK for mobile games and everything should run great at 30 fps, but that's just not my experience.

Would be grateful if someone could give me some pointers on how to achieve this.

# Answer
> 4 votes
If you have seen a game running at 60fps, then reverting to 30fps will always be noticeably less smooth - it's a perception thing.

Get someone who has never played your game before to play it at 30fps and they'll probably think it's just fine.

Most games target 60fps these days as games running at 60fps have a much better feel. Most recent (high end?) mobile devices have their framerates throttled to 60fps. Older/low end devices may be forced to run at a lower frame rate, but more and more will be targeting 60fps. If games looked just as good at 30fps as they do at 60fps, then devices would just throttle to 30fps.

The bottom line is - don't worry about it. You'll never get a game looking as smooth at 30fps as it looks at 60fps.

# Answer
> 0 votes
One thing stands out to me that could likely explain the difference in how smooth it looks: I don't see any indication that your `updateLogic()` method is using the actual delta time between frames. If I'm correct in assuming that `dt` is your delta time variable, it should not be constant.

This probably won't be cut and paste usable, but it should be something more like:

```
float skipTime = 1000 / 60.0f;
float lastUpdate = System.currentTimeMillis();
float dt;

while(true){
   dt = System.currentTimeMillis() - lastUpdate;
   if(dt >= skipTime){
      updateLogic(dt);
      lastUpdate = System.currentTimeMillis()
   }
}

void updateLogic(float dt){
   // modify any time-influenced calculations by the delta time, ex:
   player.position += player.velocity * dt
}

```

The difference between that, and what I think is probably going on in your game, is that in this case, if the update happens to occur at 18, 19, or even 100 milliseconds, the update will account for the actual difference in time between frames and the position of a moving object will update by the correct amount. If dt is always 16.666667, but the actual time between frames is not that amount, then the object will not move the correct amount of space for the amount of time that has passed. What should be a constant velocity, or a smoothly changing velocity as it is affected by acceleration, is not so smooth, and not so constant. At 60 FPS this is likely to be less perceptible, but I'd wager the effect is still there, mitigated by the smaller dt constant.

---
Tags: android, opengl-es2, game-loop, vsync
---


title: Texturing a VBO cube (JOGL)

text:
# Question
Title: Texturing a VBO cube (JOGL)
I've been having trouble texturing a cube using vertex buffer objects.

~~EDIT: I updated/replaced my shaders to fit the right version. The program compiles and links, but it shuts down java in drawCubeVBO().~~

~~EDIT2: I simplified the shaders so I could figure out setting uniforms first. The program runs, but the VBO doesn't have any texture on it. Many examples I've seen do basically the same thing I am (I think). So I think the problem now could be something small or obvious that I'm not seeing.~~

EDIT3: Now I've been trying to convert from drawElements to drawArrays. I can't get the cube to render let alone render with textures. When I run this, there are clearly triangles being rendered, but I can't relate their position to the vertex array. For example, some of the triangles have points at 0,0,0 and there are no points 0,0,0 in vertexArray. I think I may be missing some glDrawArrays syntax or I left something from glDrawElements that shouldn't be there.

initVBO is called only once before rendering and drawCubeVBO is called every frame

```
    public void initVBO(GL2 gl, String textureFileName, String textureFileType) {

// cube ///////////////////////////////////////////////////////////////////////
//      v6----- v5
  //   /|      /|
  //  v1------v0|
  //  | |     | |
  //  | |v7---|-|v4
  //  |/      |/
  //  v2------v3

  // vertex coords array for glDrawArrays() =====================================
  // A cube has 6 sides and each side has 2 triangles, therefore, a cube consists
  // of 36 vertices (6 sides * 2 tris * 3 vertices = 36 vertices). And, each
  // vertex is 3 components (x,y,z) of floats, therefore, the size of vertex
  // array is 108 floats (36 * 3 = 108).

  float[] vertexArray = { 1, 1, 1,  -1, 1, 1,  -1,-1, 1,      // v0-v1-v2 (front)
                         -1,-1, 1,   1,-1, 1,   1, 1, 1,      // v2-v3-v0

                          1, 1, 1,   1,-1, 1,   1,-1,-1,      // v0-v3-v4 (right)
                          1,-1,-1,   1, 1,-1,   1, 1, 1,      // v4-v5-v0

                          1, 1, 1,   1, 1,-1,  -1, 1,-1,      // v0-v5-v6 (top)
                         -1, 1,-1,  -1, 1, 1,   1, 1, 1,      // v6-v1-v0

                         -1, 1, 1,  -1, 1,-1,  -1,-1,-1,      // v1-v6-v7 (left)
                         -1,-1,-1,  -1,-1, 1,  -1, 1, 1,      // v7-v2-v1

                         -1,-1,-1,   1,-1,-1,   1,-1, 1,      // v7-v4-v3 (bottom)
                          1,-1, 1,  -1,-1, 1,  -1,-1,-1,      // v3-v2-v7

                          1,-1,-1,  -1,-1,-1,  -1, 1,-1,      // v4-v7-v6 (back)
                         -1, 1,-1,   1, 1,-1,   1,-1,-1 };    // v6-v5-v4

        vertices = Buffers.newDirectFloatBuffer(vertexArray.length);
        vertices.put(vertexArray);
        vertices.flip();

        FloatBuffer textureData = Buffers.newDirectFloatBuffer(12);
        textureData.put(textureLeft);
        textureData.put(textureRight);
        textureData.put(textureBottom);
        textureData.put(textureTop);
        textureData.flip();

        int[] temp = new int[3];
        gl.glGenBuffers(3, temp, 0);

        VBOVertices = temp[0];
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBOVertices);
        gl.glBufferData(GL.GL_ARRAY_BUFFER, vertices.capacity()
                * Buffers.SIZEOF_FLOAT, vertices, GL.GL_STATIC_DRAW);
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);

        vboTextureCoordHandle = temp[2];
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboTextureCoordHandle);
        gl.glBufferData(GL.GL_ARRAY_BUFFER, vboTextureCoordHandle, textureData, GL.GL_STAT

IC_DRAW);
            gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);

            shader = new Shader(gl);
            shader.bind(gl);
            shader.attachVertexShader(gl);
            shader.attachFragmentShader(gl);
            shader.link(gl);
            //shader.unbind(gl);
        }

        public void drawCubeVBO(GL2 gl, String textureFileName, String textureFileType) {

 //shader.bind(gl);

    //initializing textures
    this.textureFileName = textureFileName;
    this.textureFileType = textureFileType;

loadTexture(gl);
    texture.enable(gl);
    gl.glEnable(GL.GL_TEXTURE_2D);

    //setting the uniform
    shader.setUniform(gl, "tex", 0);

    //activating textures
    gl.glActiveTexture(GL2.GL_TEXTURE0 + 0);
    texture.bind(gl);

    //drawing
    gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY);

    /* Setup Position Pointer */
    gl.glBindBuffer    (GL.GL_ARRAY_BUFFER, VBOVertices);
    gl.glVertexPointer (3, GL.GL_FLOAT, 0, 0);

    /* Setup Texture Coordinate Pointer */
    gl.glBindBuffer      (GL.GL_ARRAY_BUFFER, vboTextureCoordHandle);
    gl.glTexCoordPointer (2, GL.GL_FLOAT, 0, 0);

//actual drawing
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBOVertices);
gl.glDrawArrays(GL.GL_TRIANGLES, (int) vertices.get(0), vertices.capacity());

gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);

//shader.unbind(gl);

        }

    public void loadTexture(GL2 gl) {
                // Load texture from image
                try {
                    // Create a OpenGL Texture object from (URL, mipmap, file suffix)
                    // Use URL so that can read from JAR and disk file.
                    texture = TextureIO.newTexture(getClass().getClassLoader()
                            .getResource(textureFileName), // relative to project root
                            false, textureFileType);

                    // Use linear filter for texture if image is larger than the
                    // original texture
                    gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                    // Use linear filter for texture if image is smaller than the
                    // original texture
                    gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

                    // Texture image flips vertically. Shall use TextureCoords class to
                    // retrieve
                    // the top, bottom, left and right coordinates, instead of using
                    // 0.0f and 1.0f.
                    TextureCoords textureCoords = texture.getImageTexCoords();

                    textureTop = textureCoords.top();
                    textureBottom = textureCoords.bottom();
                    textureLeft = textureCoords.left();
                    textureRight = textureCoords.right();

                } catch (GLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }

```

And the shaders:

```
private String vertexShaderString =
        "#version 330 core\n"+

        "layout(location = 0) in vec2 pos;\n"+
        "layout(location = 1) in vec2 tex;\n"+

        "out vec2 texCoords;\n"+

        "void main()\n"+
        "{\n"+
            "texCoords = tex;\n"+
            "gl_Position = vec4(pos, 0.0, 1.0);\n"+
        "}";

private String fragmentShaderString =
        "#version 330 core\n"+

        "uniform sampler2D tex;\n"+

        "in vec2 texCoords;\n"+
        "out vec4 outColor;\n"+

        "void main()\n"+
        "{\n"+
            "outColor = texture(tex, texCoords);\n"+
        "}";

    // ProgramID
    int programID;

    // Vertex Shader ID
    int vertexShaderID;

    // Fragment Shader ID
    int fragmentShaderID;

    public Shader(GL2ES2 gl) {
        programID = gl.glCreateProgram();
    }

    public void attachVertexShader(GL2ES2 gl) {

        // Create GPU shader handles
        // OpenGL ES retuns a index id to be stored for future reference.
        vertexShaderID = gl.glCreateShader(GL2ES2.GL_VERTEX_SHADER);

        // Load and compile the source
        String[] vlines = new String[] { vertexShaderString };
        int[] vlengths = new int[] { vlines[0].length() };
        gl.glShaderSource(vertexShaderID, vlines.length, vlines, vlengths, 0);
        gl.glCompileShader(vertexShaderID);

        //Check compile status for errors
        int[] compiled = new int[1];
        gl.glGetShaderiv(vertexShaderID, GL2ES2.GL_COMPILE_STATUS, compiled,0);
        if(compiled[0]!=0){System.out.println("Horray! vertex shader compiled");}
        else {
            int[] logLength = new int[1];
            gl.glGetShaderiv(vertexShaderID, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);

            byte[] log = new byte[logLength[0]];
            gl.glGetShaderInfoLog(vertexShaderID, logLength[0], (int[])null, 0, log, 0);

            System.err.println("Error compiling the vertex shader: " + new String(log));
            System.exit(1);
        }

        //Attach Shader
        gl.glAttachShader(programID, vertexShaderID);
    }

    public void attachFragmentShader(GL2ES2 gl) {

        // Create GPU shader handles
        // OpenGL ES retuns a index id to be stored for future reference.
        fragmentShaderID = gl.glCreateShader(GL2ES2.GL_FRAGMENT_SHADER);

        // Load and compile the source
        String[] vlines = new String[] { fragmentShaderString };
        int[] vlengths = new int[] { vlines[0].length() };
        gl.glShaderSource(fragmentShaderID, vlines.length, vlines, vlengths, 0);
        gl.glCompileShader(fragmentShaderID);

        //Check compile status for errors
        int[] compiled = new int[1];
        gl.glGetShaderiv(fragmentShaderID, GL2ES2.GL_COMPILE_STATUS, compiled,0);
        if(compiled[0]!=0){System.out.println("Horray! fragment shader compiled");}
        else {
            int[] logLength = new int[1];
            gl.glGetShaderiv(fragmentShaderID, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);

            byte[] log = new byte[logLength[0]];
            gl.glGetShaderInfoLog(fragmentShaderID, logLength[0], (int[])null, 0, log, 0);

            System.err.println("Error compiling the fragment shader: " + new String(log));
            System.exit(1);
        }

        //Attach Shader
        gl.glAttachShader(programID, fragmentShaderID);

    }

public void link(GL2ES2 gl) {

    //link
    gl.glLinkProgram(programID);

    //check for errors
    int[] compiled = new int[1];
    gl.glGetProgramiv(programID, GL2ES2.GL_LINK_STATUS, compiled,0);
    if(compiled[0]!=0){System.out.println("Horray! Shader program linked!");}
    else {
        int[] logLength = new int[1];
        gl.glGetProgramiv(programID, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);

        byte[] log = new byte[logLength[0]];
        gl.glGetProgramInfoLog(programID, logLength[0], (int[])null, 0, log, 0);

        System.err.println("Error linking the program: " + new String(log));

          System.exit(1);
        }

/**
 * Sets the uniforms in this shader
 *
 * @param name    The name of the uniform
 * @param values  The values of the uniforms (Max 4)
 */
public void setUniform(GL2ES2 gl, String name, float... values)
{
    if (values.length > 4)
    {
        System.err.println("Uniforms cannot have more than 4 values");
        System.exit(1);
    }

    // Get the location of the uniform
    int location = gl.glGetUniformLocation(programID, name);

    // Set the uniform values
    switch (values.length)
    {
        case 1:
            gl.glUniform1f(location, values[0]);
            break;
        case 2:
            gl.glUniform2f(location, values[0], values[1]);
            break;
        case 3:
            gl.glUniform3f(location, values[0], values[1], values[2]);
            break;
        case 4:
            gl.glUniform4f(location, values[0], values[1], values[2], values[3]);
            break;
    }
}

```

# Answer
I figured out my "EDIT3" problem: I didn't look closely enough at the parameters of glDrawArrays(). Instead of saying `gl.glDrawArrays(GL.GL_TRIANGLES, (int) vertices.get(0), vertices.capacity());` I should have been saying `gl.glDrawArrays(GL.GL_TRIANGLES, 0, vertices.capacity());` because the middle parameter is the starting point.

After that, the cube rendered with a stretched out texture on it! I'm going to take that as answering my original question because technically, there is a texture on the cube. Also, there are several other posts having that same stretched out texture problem so I'm not going to continue that here. (https://stackoverflow.com/questions/10463384/vbo-with-texture-in-lwjgl?rq=1, https://stackoverflow.com/questions/16778687/vbo-texturing-dont-work-correctly-lwjgl?rq=1, https://stackoverflow.com/questions/19032136/opengl-texture-stretched-and-wrong-vbo-vertices-incorrect)

My original post is kindof a mess with edits. The problem was much bigger than I initially expected. To reiterate: my original goal was to render a textured cube with VBOs. I learned: I needed a shader(s), I had to set my uniforms, I had to use glDrawArrays instead of glDrawElements.

Thanks so much to Sri Harsha Chilakapati for helping me through this issue!
> 0 votes

# Answer
I should have read your post completely. Using `glDrawElements` is not a perfect fit for textured models because there can be shared vertices but those vertices cannot have same texture coordinates all the time. So you have to add all the vertices normally as you do in the case of using `glDrawArrays`. So using `glDrawElements` is useless in this case and it requires extra memory for the ebo.
> 0 votes

---
Tags: java, textures, shaders, vbo, jogl
---


# Question
Title: Game Engine Entity/Component with Services Architecture
I'm currently working on my first game engine and decided to use the entity/component model with services.

**Background:** My GameEngine class is an Entity and has multiple services that are Components, like the RenderService and the PhysicsService. Other Entities in my game have components that communicate with services, like the RenderComponent and the PhysicsComponent.

**Question:** How do I get these components to communicate with their respective services?

**Note:** I have thought about having a call to the respective service create the components, but I would like to hear about other solutions you guys have. I'm open to adding/removing classes and changing my whole architecture. It is my first attempt, so I'm willing to take advice and learn. Time is not the concern.

Let me know if you need more information.

Thank you in advance.

# Answer
I think you might be overengineering, or at least abstracting too much away. While the `GameEngine` can certainly utilize composition in the form of services, I wouldn't treat the `GameEngine` as an `Entity` along with the rest of your game objects. If you are planning to have a 1:1 mapping of component types and services, I would definitely let each service manage the lifetimes of their respective components, by letting your `Entity` constructors or factories request the creation of components.

Personally, I don't like to compartmentalize that much. I use more of a property-centric approach to components, where components are little bits of data such as a position, a mesh, an AI script, etc. The behaviour associated with this data (drawing, simulating, etc.) lives in **systems** that can operate on more than one component type. For example, the rendering system might be interested in both the position and the sprite of an object. I like to store all my components in contiguous arrays and have my systems be free functions. I've already written a couple of articles about this so I'll link them for if you want to know more.

Understanding Entity Component Systems

Implementing Entity Component Systems
> 2 votes

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


title: java capping fps

text:
# Question
Title: java capping fps
hello again I have a basic platformer game and I want to make an fps counter and cap the fps to 30 but I don't know how. I want this because when I start up the game sometimes the character moves realy fast and other times very slow.

# Answer
You should probably use framerate-independent movement, because then you wouldn't have to care about the FPS.

What you are probably doing right now is in every frame you say `position += velocity;`, where `position` is in units of distance (whatever they may be--pixels, meters, etc.), and `velocity` is in units of distance per frame.

However, what you should probably do is have `velocity` instead be in units of distance per time instead of distance per time. Then what you would do is `position += velocity * frameTime;`, where `frameTime` is `1/FPS`, and is in units of time (seconds, to be specific).

Now, no matter what the framerate is, your character will move the same distance in the same amount of time.
> 0 votes

# Answer
I believe what you want to add is a fixed timestep. If you wish to make your game's logic independent of your framerate, you'll want to look into adding a delta - a timestep that calculates the time between update calls.

For a more in-depth explanation, check out DeWitter's article: http://www.koonsolo.com/news/dewitters-gameloop/
> 0 votes

---
Tags: java
---


# Question
Title: What is the purpose of adding non-gameplay elements to a game?
As an example, I'll reference scientists in Jetpack Joyride.

I do understand there are achievements that involve scientists, that you can kill them or you have a nerd repellent, but I am not asking about any of those.

I want to understand whether there is any very important reason to have such an element in a game, since (at least initially) it seems quite insignificant.

More precisely, does the presence of scientists (or any equivalent, apparently insignificant "actor" in a game) has any psychological effect or influence of any kind to the players? Or they are simply there as a small little feature of the game that barely makes any difference to the player's feelings & attitude whilst playing the game?

# Answer
There are a number of reasons for this:

1. **To add to the environment.** By far the most likely reason. Nearly every game has components that are not essential to gameplay. From NPCs going about their daily lives to birds flying around, all of these things add to the immersion for the player and increase the visual appeal of the game. This even goes as far as, why use an animated sprite for your game character? It's not important to the gameplay for the character to look nice is it?
2. **It's for something you don't know about yet.** Maybe later in the game, these non-essential elements are used for something else. Where it wouldn't make sense to have them appear right when you need them.
3. **It was going to be a feature, but didn't get fully implemented.** Perhaps the elements were part of a planned feature, but it wasn't finished.
4. **The developer has a personal reason for adding it.** Maybe it's a joke, or something they really like. The game is their canvas, they can add whatever they like.
> 44 votes

# Answer
Easter Egg effect: Plenty of games have implemented surprises in supposedly innocent and not important elements. Players usually try to find out if there is a 'second bottom' or it is just a decoration. Anticipation of unexpected makes game more interesting and sometimes... Non-gameplay elements turn-out to be vital to your mission.
> 1 votes

# Answer
1. It makes the world seem more real and convincing and less planned.
2. Paying attention to non-essential details shows that the developer put effort in.
3. More details means that there is more depth to observe which help replayability.

Consider the following: You go to a restaurant to order and eat a meal. However, restaurants may include bread on the table before your meal. They may include crayons for the kids. They might have a fish tank or paintings on the wall. The walls might be painted and floors might be carpeted. They might have a musician playing. None of these things are central to the reason you are there or help you achieve the goal of eating food, but they help your overall perception of the place be more complete. Knowing that the restaurant owner didn't do ONLY what they had to do makes you feel good!
> 0 votes

---
Tags: game-design
---


# Question
Title: How to I access "Deny" message from a Lidgren client?
I'm using the Lidgren v3 network for a UDP client/server networking model. On the server end, I'm initializing a NetServer object with the NetIncomingMessage.ConnectionApproval message type enabled.

So the client is able to successfully connect and the first packet it sends is a login packet, containing a username and password supplied by the user. The server is receiving that and doing some black magic to authenticate, and everything works up to that point.

If the login fails, the server calling NetIncomingMessage.SenderConnection.Deny("Invalid Login Credentials"). I want to know how to properly receive this deny message on the client.

I'm getting the message, it shows up with a message type of NetIncomingMessage.StatusChanged. If I call ReadString on that message, I get a corrupted version of the string I passed to the Deny method on the server. The type of corruption varies, I've seen odd characters in there but in every case it's truncated and is way shorter than the string I entered.

Any ideas? The official documentation is sparse on this topic. I could use pointers from anyone who has successfully used the Lidgren library and uses the Accept or Deny methods.

Also, if I don't do any authentication and just Approve() the connection every time, stuff actually works just fine and I'm getting reliable two-way UDP traffic. (And lastly, Stack Exchange said I don't have enough reputation to use the "Lidgren" tag....???)

# Answer
I stumbled upon the same question today, from your `StatusChanged` message type, read the first byte of the message and cast it to `NetConnectionStatus`. After that, check if it is a `Disconnected` status message. If it is, read the string from the message, which is the disconnect reason.

```
case NetIncomingMessageType.StatusChanged:
    switch ((NetConnectionStatus)im.ReadByte())
    {
        //When connected to the server
        case NetConnectionStatus.Connected:
             break;
        //When disconnected from the server
        case NetConnectionStatus.Disconnected:
        {
             string reason = im.ReadString();
             if (string.IsNullOrEmpty(reason))
                  Debug.WriteLine("Disconnected");
             else
                  Debug.WriteLine("Disconnected, Reason: {0}", reason);
        }

```
> 2 votes

# Answer
Sorry for the slow answer; but the first byte of the StatusChanged message is a byte which contains a NetConnectionStatus enum - after that there's the human readable reason string.
> 0 votes

---
Tags: udp
---


title: LibGDX Android version

text:
# Question
Title: LibGDX Android version
I am trying to use the LibGDX UI Project creator to create LibGDX projects, but it doesn't allow me to choose the Andorid version for the project. This is a problem for some android features. For example I want to hide the action bar, so I wanted to set the Theme:

```
Theme.Holo.Light.NoActionBar.Fullscreen

```

...but if I do that I get the error message

> @android:style/Theme.Holo.Light.NoActionBar.Fullscreen requires API level 13 (current min is 5).

My idea is to manually set up the projects so I can choose freely the versions and API levels. But I think I can't choose what I want, because then LibGDX would have problems.

How can I correctly set the android version using UI Project creator?

# Answer
As per your comment, you should probably rephrase your question if all you're trying to do is remove the navigation/title bar..

https://stackoverflow.com/a/2868052/1620568

```
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

```

Or you can do it via your AndroidManifest.xml file:

```
<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
</activity>

```
> 0 votes

# Answer
You are probably developing with the ADT. To change the API you are working with, download the newest one with the Android SDK Manager and change the `project.properties target=android-19`.

That might fix it.
> 1 votes

# Answer
From one of your comments I saw that you meant to disable the navigation bar. Well this will keep it out of the screen until you swipe down from the status bar. It's the same code that Jetpack Joyride uses:

```
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
decorView.setSystemUiVisibility(uiOptions);

```

You must also have this in the activity section of your XML file:

```
android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen"

```
> 0 votes

---
Tags: android, libgdx
---


title: game mod security question

text:
# Question
Title: game mod security question
So I'm in the process of building a game in C++ for the engine and Python for behavior and moddability. One of the planned major features is that when the game client connects to a game server with mods, the server will tell the client where to get the mods. This introduces a security problem for the client as a mod with malicious code could be downloaded. How can I limit python so that mods can not affect the system outside of the game?

# Answer
> 2 votes
I've researched this same issue, but for a different platform. What you're looking for is called a "sandbox."

https://wiki.python.org/moin/SandboxedPython

---
Tags: c++, architecture, python, client-server, security
---


# Question
Title: Currently developing a game with Android SDK, should I switch to a game engine in future projects?
I am an android developer, and I've made several apps on the Google Play Store. I'm currently working on my first game, which is just a simple RPG for android, that I'm coding in Java with the android SDK. I went to an indie game conference recently, and one of the veterans, asked why I didn't use Unity or another game engine to build my game, so it could be easily ported later on. Which got me to wonder if I should use a game engine, since I do want to port this game to other platforms.

So, my question is, should I try to adapt to a game engine to make my future projects, if so, which game engines should I look into?

Thanks!

# Answer
YES. If we put cross-platform aside, I think you should use a game engine just for the basic features that many game engines provide:

* Object/Layer management + Level loading
* A Renderer for either 2D or 3D
* Texture management (texture groups, texture sizing, texture-atlasing)
* Physics
* Animation engine (support opacity, rotation, position, etc.. with different easing curves)
* Particle system (efficiently render many particles acting according to meta data)
* Easy to use editors (level, animations, particle effects)

Now some game engines also offer cross-platform deployments to mobile phones and desktops, some examples are Unity, Cocos2d-x and Unreal Engine. So if you are ok with the licensing terms then it's a no-brainer question whether to use one.

P.S: I can't help you with a recommendation for a specific one because I do my own game engine development.
> 2 votes

# Answer
As you mention that your current game is *simple* I assume you are learning, or at least expanding upon other non-game related knowledge. Game engines are useful tools in industry, the games you make will work more efficiently and turn around time will be faster.

My opinion is that it is far better to create your own engine if not working on a commercial project (time/profit isnt an issue). As you will learn lots of things you would miss over otherwise in terms of how game engines work and how to structure a library and how to program for efficiency. These things are all possible to learn while on other projects but are integral with game engines.

As you have already worked on an engine in your first game. How much have you learned from that process? and how would you change it if you start again.

for commercial work use a published/professional engine, for personal projects work on your own as you will get allot more out of it.

also building an engine specifically for your game, means you wont have excess code/variables taking up space in your program, and can be more efficient and do exactly what you want.
> 1 votes

---
Tags: android, porting
---


title: Resolution independent game world in 3D

text:
# Question
Title: Resolution independent game world in 3D
I'm developing a game similar to Don't Starve - 2D billboards in a 3D world. Now I have encountered a problem with resolutions. I want the player to be able to change resolution, but I don't want to change how much of the world that can be seen on screen. This is how it works in Don't Starve.

So will the resolution just decide the size of the textures? Do I use a set internal resolution and then scale the textures according to the resolution? Do I then need to scale the world coordinates?

I want the field of view to be the same and also so the camera angle(it's looking down with an angle as in most strategy games). I might also mention I'm coding with Monogame.

# Answer
A GPU works in screen-space coordinates which go from -1~1 for both x and y dimensions. The projection matrix (in combination with the view matrix) takes care of how 3D world coordinates are mapped onto two-dimensional screen space coordinates.

If you use the same field of view and aspect ratio for each resolution the player will never see more (or less) than he/she is supposed to. When you've designed your game for an aspect ratio of 16:9 (for example 1920x1080 resolution) some things might look stretched when the user selects a resolution with a different aspect ratio (for example 800x600 is a 4:3 aspect ratio). In this case you will need to add some post processing to un-stretch the image and add black bars on the top and bottom of the screen.

Now I don't know how you draw your 2D billboards. Do you by-pass the viewprojection matrix? If you're using the sprite batch to draw the billboards you will need to add your own math to address this problem as the sprite batch uses the resolution directly to position the sprite. Note you can add a Matrix to SpriteBatch.Begin() to transform all your sprites!

By the way:

See the related questions on the right, such as:

*(Note the links I gave are for XNA, but Monogame is a direct port of it so all concepts there are valid for you as well)*
> 1 votes

---
Tags: xna, 3d, monogame, resolution
---


title: Geometry design and buffers

text:
# Question
Title: Geometry design and buffers
I'm making some tests with rendering stuff and I'm wondering how to design my Geometry class. For the moment, here is how I do:

* Init: Stock array with positions, array with colors, array with normals, … has attributes.
* Just before rendering, if my geometry have changed, I update his vertex buffer and index buffer. To do that, I compute interleaved array here and send it to my vertex buffer.

I've made some tests with particles (10000 on iPad), the heaviest function is "Geometry::computeInterleavedArray.

How can I avoid this part? Is it better to stock geometry's data inside a single array with all data already interleaved?

# Answer
> 2 votes
The most efficient method of updating vertex data would be to do it on the GPU. To do this you can use transform feedback. Transform feedback works by letting you write out changes to your vertices in the vertex shader back to your vertex buffer.

Or if you need to calculate the positions cpu side for some reason, glMapBufferRange may be the next best thing. I'm assuming at the moment you are doing something along the lines of:

```
GLuint myVBO;
glm::vec3 positions[10000];
glm::vec3 colours[10000];
glGenBuffers(1, &myVBO);
//Update
for(...)
    position[i]+=velocity[i];
// Upload
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*10000, &positions[0], GL_DYNAMIC_DRAW);
// Render

```

Instead you can do:

```
// (Not complete code)
GLuint myVBO;
glGenBuffers(1, &myVBO);
glm::vec3 positions[10000];
glm::vec3 colours[10000];
// Set initial positions
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*10000, &positions[0], GL_DYNAMIC_DRAW);
//Update
glm::vec3 * gpuPositions = glMapBufferRange(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3)*10000, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
for(...)
    gpuPositions[i]+=velocity[i];
glUnmapBuffer(GL_ARRAY_BUFFER);
// Render

```

These are OpenGL es 3.0 features. So may not be available on your device. If you need es 2.0, you are not going to get much more speed than uploading with glBufferData() each frame. If you are doing something along the lines of:

```
for(...)
    interleavedArray[i] = positions[i];
    interleavedArray[i+3] = colours[i];

```

Then yes it would be more efficient to store the data already interleaved like:

```
for(...)
    interleavedArray[i+positionOffset] += velocity[i];

```

---
Tags: opengl, geometry, vertex-buffer
---


# Question
Title: glDeleteBuffers causing other objects not to draw
I have few objects in scene and they exist until I turn off the application. Their calls for glDeleteBuffers are in destructor. Since I don't delete anything in the middle of the game everything is fine. But now I created one helper function for drawing lines with following body:

```
void DrawLine(glm::vec3 p1, glm::vec3 p2, glm::vec4 color)
{
    GLuint vao, vbo;

    glm::vec3 data[2] = { p1, p2 };

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(glm::vec3) * 2, data, GL_STATIC_DRAW);

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glEnableVertexAttribArray(0);

    glBindVertexArray(vao);

    SimpleShader.SetAttribute("World", glm::mat4x4());
    SimpleShader.SetAttribute("UseStaticColor", true);
    SimpleShader.SetAttribute("UseLighting", false);
    SimpleShader.SetAttribute("StaticColor", color);
    glDrawArrays(GL_LINES, 0, 2);
    SimpleShader.SetAttribute("UseStaticColor", false);
    SimpleShader.SetAttribute("UseLighting", true);

    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &vao);
}

```

But as soon as glDeleteBuffers is called nothing is drawing anymore. If I comment those two lines everything is fine (except a bunch of unreleased object names of course).

Anyone know why is this happening?

# Answer
> 1 votes
*I am just rehashing what @yuumei said, but since he did not post an awnser:*

You are creating the `vao` object with:

```
 glGenVertexArrays(1, &vao);

```

As such you need to delete it with:

```
glDeleteVertexArrays(1, &vao);

```

Here is the documentation for glGenVertexArrays.

What happens here is that the value in vao is the same value with some other buffer and as such that buffer is being deleted instead. Next time you try to use that buffer, it will not work, since you deleted it.

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


title: Reflection and shadows in OpenGL

text:
# Question
Title: Reflection and shadows in OpenGL
I'd like to implement shadows and reflective surfaces in my OpenGL app. I already have ideas which I will provide below. But I would like to ask someone more experienced than me before I put too much effort into the implementation. (I'm still very new and so I don't know all options I have on modern graphic cards.)

I would like to know if there are any common improvements or common techniques that would improve the quality and/or performance. (Or even if my idea is completely nonsense)

**Shadows**

I would render a cube map at the center of each light source in a separate Framebuffer. When rendering the real scene I can lookup the depth information in the the relevant cube map (for each light source) and compare the depth value with xyz-Position of the Fragment. And check if the Fragment is behind an object. Additionally I could also take surrounding depth values into account to render blurred shadows depending on the distance to the object.

For the special case that the light source is stationary I could render all other stationary objects at the beginning. For each frame I still have to render the dynamic objects and reset to the "stationary scene" afterwards.

**Reflection**

For plane mirrors you could simply mirror the view matrix around the plane and render the scene a second time (with the stencil buffer to clip the rendering process to the mirror surface). Also I should clip the rendering volume with `glClipPlane()`. I found this technique on Google, so it seems to be very common.

But for arbitrary surfaces I had to think about something different. My idea is to render a cube map at the center of every object that has reflection enabled in its material definition. When I am in the real rendering process, I would read out the pixel value in the cube map, depending on the surface normal and the fragment xyz-Position. The problem is that you get an parallax error for near objects because the fragment obviously isn't at the center of the object. I couldn't solve this problem. (Maybe I could render the normals of the mirror object and then use this to make some transformations while rendering the cube map?)

For stationary mirror objects I could do same trick that I described in the *Shadows* section.

Instead of cube maps I could also use a single map and transform the Cartesian coordinates to spherical coordinates (phi, theta, r). So that the resulting texture has the dimension phi * theta (r is the depth value). But I don't know which method is generally faster. Also a single map would generate different texture qualities depending on theta. I'm not sure how bad this will be in the result.

The main problem that I have is that this all sounds very performance intensive. Maybe there are tricks I don't know?

An advice would be helpful. Thanks in advance.

# Answer
> 2 votes
You are not so far off with your observation. The approach you describe in both cases is OK but needs refinement.

**Shadows**

When looking into shadows you need to consider different issues. As you describe you can handle everything dynamically. The process is basically as you describe, except for directional lights and spotlights you would use "normal" 2D frame buffers.

There are a number of optimizations you can do. For example you can ask the question which lights actually need shadows. Often when designing a level you will put many small point lights into places where low "ambient" light is expected, such as glow from illuminated signs and such. Here you can get away with no shadows at all.

The next optimization is, you can precompute static lights on static geometry and "bake" the lightmaps. You would then blend the dynamic lights with the static lights to achieve the final result for static objects. Dynamic objects would then be lit by all lights. But again here you may want to have some lights only contribute to the static scene. You can see this allot in the Unreal Engine.

If you have static lights you may also create "light volumes". This technique precomputes the area the light touches in a 3D texture. This allows static geometry to shadow dynamic objects by looking up into that texture.

The next thing you need to consider is filtering. The filtering will greatly influence the quality and performance of the final result. There are many different filtering algorithms and with different tradeoffs. It is hard to recommend one.

**Reflection**

As to reflection, it depends. It depends if you are trying to do proper reflection or just do first order ambient lighting.

Many implementation get away with "reflection captures" scattered in the scene. You can see this when the glossy tiles on the floor don't perfectly match up with the wall behind. This is one cubemap or spheremap that is used for all objects close by. Here you can either do a single capture once, every couple of frames or every frame. It depends on how dynamic your scene is. If you are going to blur the result anyway, this works great.

When you need perfect reflection it makes sense to explicitly capture reflection at the object. But in this case you would limit the number of objects that actually need it.

It is interesting with how few captures you need to make a scene look good. The question here is, will you let level designers place the captures or do you want to try to place them procedurally. Unfortunately I have not yet found a good algorithm that would do that for me.

---
Tags: opengl, shadows, shadow-mapping, reflection-rendering
---