# Question
Title: Working With D3D11/OpenGL Shader Reflection
I've been working in my off-time to do some system design for a game engine as a fun and challenging project, and i've hit a bit of a wall. I've made an interface which is a renderer that i try to incorporate elements similar to both d3d11 and opengl so that implementations of both are still very functional behind said interface. In the process of working with abstracting shaders, i was wondering if there was a way to actually enumerate the uniforms / cbuffers in a shader using shader reflection, rather than query for them by name. In openGL, the only way to set a variable is if you query for it by name (I think), and in d3d11 you are able use the ID3D11ShaderReflection interface, but are only able to query cbuffers and variables by name. My knowledge is pretty new in opengl, but i was wondering if there was a way to grab or make a list of all the uniforms / cbuffers present in the shader, so that i could query the rest of my engine for the values needed.

What this would do for me is simple: Rather than my engine requiring compiled knowledge beforehand of what variables some specific shader might need, it can instead obtain the names and typenames of all the variables it requires to function correctly. Then i can code a resource container that can hold any number of types and resources, which are associated by variable name in a map or similar, which would allow me to compare the names of the values in the resource container, with what the shader required, and then tell you which uniform /cbuffer value you didn't bind to something. Is this possible, because it sounds incredibly useful.

# Answer
I can only answer from OpenGL point of view. Yes you can do what you are looking for. You can query shader information using `glGetProgrami`, `glGetActiveUniform` and `glGetActiveAttrib`

E.g. the following code queries the available uniforms from a shader:

```
int maxLength;
glGetProgramiv(shaderProgram, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxLength);
char name[...]; // Size should be allocated to be maxLength + 1

int uniformCount;
glGetProgramiv(shaderProgram, GL20.GL_ACTIVE_UNIFORMS, &uniformCount);

for (int i = 0; i < uniformCount; i++) {
    int size;
    int type;
    glGetActiveUniform(shaderProgram, i, maxLength, NULL, &size, &type, name);
}

```

Note that the returned name can depend on the driver implementation. For array uniforms nVidia drivers return `uniformName[0]` whereas AMD drivers return just `uniformName`. I recommend checking for this and removing the trailing `[0]` if present. Also if you are mixing programmable and fixed function pipeline, the returned uniforms can contain built-in uniforms in addition to your custom ones. So another advice is to skip uniform names starting with `gl_`.
> 4 votes

# Answer
Yes, you can do this with d3d11 shader reflection. Here is some code showing how to iterate over a constant buffer, as well as grab all the values within the cbuffer. This doesn't require you to know anything about the shader.

```
ID3D11ShaderReflection* reflection = NULL;
D3D11Reflect(description->buffer, description->length, &reflection);

D3D11_SHADER_DESC desc;
reflection->GetDesc(&desc);

//
//Find all constant buffers
//
for(unsigned int i = 0; i < desc.ConstantBuffers; ++i)
{
    unsigned int register_index = 0;
    ID3D11ShaderReflectionConstantBuffer* buffer = NULL;
    buffer = reflection->GetConstantBufferByIndex(i);

    D3D11_SHADER_BUFFER_DESC bdesc;
    buffer->GetDesc(&bdesc);

    for(unsigned int k = 0; k < desc.BoundResources; ++k)
    {
        D3D11_SHADER_INPUT_BIND_DESC ibdesc;
        reflection->GetResourceBindingDesc(k, &ibdesc);

        if(!strcmp(ibdesc.Name, bdesc.Name))
            register_index = ibdesc.BindPoint;
    }

    //
    //Add constant buffer
    //
    ConstantShaderBuffer* shaderbuffer = new ConstantShaderBuffer(register_index, Engine::String.ConvertToWideStr(bdesc.Name), buffer, &bdesc);
    mShaderBuffers.push_back(shaderbuffer);
}

```

And then grabbing variables within the cbuffer.

```
//
//Populate constant buffer with variables
//
for(unsigned int j = 0; j < desc->Variables; ++j)
{
    ID3D11ShaderReflectionVariable* variable = NULL;
    variable = buffer->GetVariableByIndex(j);

    D3D11_SHADER_VARIABLE_DESC vdesc;
    variable->GetDesc(&vdesc);

    ShaderVariable* shadervariable = new ShaderVariable();
    shadervariable->name = Engine::String.ConvertToWideStr(vdesc.Name);
    shadervariable->length = vdesc.Size;
    shadervariable->offset = vdesc.StartOffset;
    mSize += vdesc.Size;
    mVariables.push_back(shadervariable);
}

```

Note, I am clearly using some of my own classes in this situation to store the information in a format my system prefers.
> 7 votes

# Answer
The OpenGL functions `glGetActiveUniform` and `glGetActiveAttrib` will grab information such as the variable's type and name for an uniform/attrib at a given index

`glGetProgramiv` can get various bits of information related to a shader program, such as the total number of uniforms and attributes.

The first answer for this stack overflow link shows an example of how to load information for all uniforms in a shader https://stackoverflow.com/questions/4783912/how-can-i-find-a-list-of-all-the-uniforms-in-opengl-es-2-0-vertex-shader-pro
> 2 votes

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


title: Port a WP7 game to WP8 with Monogame

text:
# Question
Title: Port a WP7 game to WP8 with Monogame
I have a full working game for WP7, I want to port it to WP8 with Monogame. I have installed Monogame and I have done all tests to see that it is working inside Visual Studio Express 2012 for Windows Phone 8. Now I just don't understand how to rebuild my WP7 version game within a Monogame project to target WP8 devices.

So, if you would have the entire solution of a WP7 game, how would you make it work on WP8 with Monogame?

Thanks!

# Answer
> 1 votes
Well as far as I have it, it will probably be easiest for you to create a new Windows Phone 8 MonoGame project from the template and then just copy all the code in. MonoGame uses the exact same namespaces, it just has a lot of behind the scenes changes that make it reference different libraries. Applying these changes whilst also applying all the other changes necessary for WP7 to WP8 project manually will be a complicated and messy task which will probably require hours of troubleshooting to get it working.

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


title: Calculating vertex normals on the GPU

text:
# Question
Title: Calculating vertex normals on the GPU
I have some height-map sampled on a regular grid stored in an array. Now, I want to use the normals on the sampled vertices for some smoothing algorithm. The way I'm currently doing it is as follows:

1. For each vertex, generate triangles to all it's neighbours. This results in eight neighbours when using the 1-neighbourhood for all vertices except at the borders.

```
 +---+---+
 ¦ \ ¦ / ¦
 +---o---+
 ¦ / ¦ \ ¦
 +---+---+

```
2. For each adjacent triangle, calculate it's normal by taking the cross product between the two distances.
3. As the triangles all have the same size when projected on the xy-plane, I simply average over all eight normals then and store it for this vertex.

However, as my data grows larger, this approach takes too much time and I would prefer doing it on the GPU in a shader code. Is there an easy method, maybe if I could store my height-map as a texture?

# Answer
> 2 votes
You can use the slopes between vertices instead of the triangle normals to average the vertex normal. This could be easily ported to the GPU if you have vertex shader texture fetch support. Gottfried Chen sums it up here with code: http://www.flipcode.com/archives/Calculating\_Vertex\_Normals\_for\_Height\_Maps.shtml

# Answer
> 1 votes
How big is your map? It could be that your grid sampling is blowing out the caches as it gets bigger, causing the sudden slow down. It could be that your loop needs optimizing. Also, how long is too long? Is your map static at run time? You said in passing that this is for smoothing and not rendering, how are you using this?

Eight normals is a little excessive, I think that you'd do fine with just four closest and ignoring the diagonals but suggest trying a before-and-after version to compare results. You could also march down the rows and carry forward results from the previous point to avoid some computation, it's an approximation but all lighting is an approximation.

If your map is static, pre-compute and save the data along with the map. If your map is generated at run time then embed the normal calculation into the generation code where you have all the data handy. If your map changes at run time then only recalculate the affected points.

---
Tags: xna, c#, shaders, normals, heightmap
---


# Question
Title: XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4
Beginner question. Synopsis: my water effects does something that causes the drawing of my sky sphere to throw an exeption when run in full screen. The exception is:

> XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4.

This happens both when I start in full screen directly or switch to full screen from windowed. It does NOT happen, however, if I comment out the drawing of my water.

So, what in my water effect can possibly cause the drawing of my sky sphere to choke???

# Answer
You need to set the `SamplerState[0]` to `SamplerState.PointClamp` before your `DrawIndexedPrimitive` call.
> 3 votes

# Answer
I think I solved the problem. I was confronted with the same problem: I used a SurfaceFormat.Single-Texture to make some displacement in my HeightmapShader and everything works until I change the resolution (switched to Full-screen or back). During this switch my SkyboxDrawer complains about exact the same thing. But my Skybox-texture was in SurfaceFormat.Color, so the exception doesn't make sense at all.

So I start googling and found out, that Sharwn Hargreaves (a programmer of XNA with a great blog on XNA and other stuff) mentioned that there is a bug in XNA4.0 connected to the correct sync of settings of the sampler states with their C# counterparts.

My sampler looks like the following, so I thought all that should be done, was done.

```
texture Texture;
sampler TextureSampler = sampler_state
{
    Texture = <Texture>;
    MinFilter = POINT;
    MagFilter = POINT;
    MipFilter = POINT;
    AddressU  = Wrap;
    AddressV  = Wrap;
};

```

But what really solved the problem was setting the VertexTextureSampler before drawing my **Heightmap**. This made the given exception in my SkyboxDrawer disappear.

```
GraphicsDevice.VertexSamplerStates[0] = SamplerState.PointClamp;

```

For completeness: My SkyboxDrawer uses the BasicShader whereas my HeightmapDrawer uses a custom HeightmapShader. So the only connection between them are the states in the grafics pipeline.

But there is a unsolved "problem". As far as I know a vertex textures sampler in XNA only can use floating point based formats like SurfaceFormat.Single, SurfaceFormat.Vector2, SurfaceFormat.HalfSingle and so on. These formats require POINT sampling. So why the hell am I able to change the GraficsDevice.VertexTextureSampler\[\*\] to something else?! Did I miss something?
> 1 votes

---
Tags: xna
---


title: Making a quad cover the screen

text:
# Question
Title: Making a quad cover the screen
I'm trying to make a shader and I need a fullscreen quad to do so.

I have everything set up and working, but when I render the quad it appears as a small square. This would probably be because I'm passing the cameras world, projection and view matrix into the shader and so the quad appears as a normal object. If I remove this it doesn't appear at all.

How do I go from it rendering as a part of the scene which moves with the camera to being something that completely covers the screen?

edit:

Vertices:

```
new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 0)),
new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 0)),
new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 1)),
new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 1))

```

Indices:

```
ushort[] indices = { 0, 1, 2, 2, 1, 3 };

```

Render:

```
        for (int l = 0; l < loader.GlowShader.CurrentTechnique.Passes.Count; l++)
        {
            //loader.GlowShader.Parameters["World"].SetValue(camera.World);
            //loader.GlowShader.Parameters["View"].SetValue(camera.View);
            //loader.GlowShader.Parameters["Projection"].SetValue(camera.Projection);
            loader.GlowShader.Parameters["glowTexture"].SetValue(renderTargetTexture);

            loader.GlowShader.CurrentTechnique.Passes[l].Apply();
            renderQuad.Render();
        }

```

# Answer
> 3 votes
Your vertex and index buffer look fine. However, your vertex shader for a full-screen quad should simply copy the input vertex position to the output position. There is no need to pass any of the matrices in because the vertex shader shouldn't use any of them. This is not the same vertex shader you would use for ordinary scene elements.

BTW, your UVs are upside down. The UV origin is in the upper left for D3D.

# Answer
> 1 votes
Nathan Reed is right, when using pretransformed vertices you should no apply World, View of Projection matrix, because the coordiantes are already in screen space. If I don't get is wrong you are defining your two triangles counter-clock-wise, which is culled away by default by XNA. You can simply proof this by setting your RasterizerState to RasterizerState.CullNone. If the quad appear, this was your problem. After that you can choose between two options:

1. Change the winding order of the triangle by changing your indices to 0,2,1,1,2,3
2. Change your RasterizerState to RasterizerState.CullClockWise.

I prefer to leave the RasterizeState in its default behavior (CullCounterClockWise) and change your indices.

---
Tags: xna
---


title: Game Logic Update Order

text:
# Question
Title: Game Logic Update Order
Is there a commonly-accepted general approach to the order of processing logic updates?

My current 2D platformer has objects that implement different concerns, including the following:

* Notifiable - can be event-driven and scripted
* Collidable - can interact with solid tiles (eg NPCs)
* Intersectable - exists in 2D space and can intersect with the player (eg doors)

In general the order of events in a game loop is:

1. Get input
2. Act on input and update stuff
3. Render

I'm not sure what order to do things in point #2. I've concluded moving things like moving platforms that the player can stand on *first* is a good idea, but I don't know when to consider scripting. The scripting in my game can give NPCs behaviours (walk between here and there), suspend player input for 'cutscenes', show dialog screens, and move the player to a new level.

# Answer
You seem to have a handle on this already.

> My current 2D platformer has objects that implement different concerns, including the following:
>
> Notifiable - can be event-driven and scripted Collidable - can interact with solid tiles (eg NPCs) Intersectable - exists in 2D space and can intersect with the player (eg doors)
>
> Intersectable - exists in 2D space and can intersect with the player (eg doors)

Separating entities by concern this way will go a long way to figuring out step #2.

The simplest answer to what goes into step #2 is *it depends*. You may have other steps in there that deal with networking, or streaming data, auto-saving, et cetera. But that kind of an answer doesn't help, either.

> I've concluded moving things like moving platforms that the player can stand on first is a good idea, but I don't know when to consider scripting. The scripting in my game can give NPCs behaviours (walk between here and there), suspend player input for 'cutscenes', show dialog screens, and move the player to a new level.

You already have an answer to this question. Your separation-by-concern method can be used to separate individual script actions into their own queues, and be processed at appropriate times.

NPC scripts like walking can be processed at the start of the frame to give their usual "update" cycle something to do. Any entity-changing script can be integrated into the overall cycle in this manner. Where you do it (start of frame, end of frame) is up to you and what works best for your cases.

For the script actions that stop the game, like playing cutscenes or moving the player to a new level, the sensible thing to do is let the frame play out, and process them at the end of the frame. Do any resource clean up/loading and carry on from there.

The end effect is that you construct an API that the script consumes, and the surface of that API is a scheduling mechanism for the the actions that your loop will execute at appropriate times. This allows you to easily decouple script execution and game execution.

Keep it simple and integrated into how your loop is structured. Make the fact that it's coming from a script be an irrelevant part of the process. Don't let it dominate your game cycle.
> 7 votes

---
Tags: game-loop, platformer
---


# Question
Title: Drawing transparent and opaque 3D objects. How do I preventing z-fighting?
I am using a transparent weighted average algorithm to draw my transparent objects.

The transparent object is drawn with the following notable render states (the rest are default XNA values):

```
    CustomBlendState.Additive,
    DepthStencilState.DepthRead,
    RasterizerState.CullNone,
    SamplerState.PointClamp

```

The opaque object is drawn using the following states:

```
    BlendState.Opaque;
    DepthStencilState.Default;
    RasterizerState.CullCounterClockwise;
    SamplerState.PointClamp;

```

In the picture below there is what I believe is a z-fighting issue where the green block and the wooden block meet.

How can I keep the objects in the same location and stop this issue from occurring?

When changing the transparent object's DepthStencilState.DepthRead state to DepthStencilState.None the issue goes away. While this is what led me to believe it was a z-fighting issue, the opaque object will then no longer occlude the transparent object when viewed from another angle.

EDIT:

Applying a depth bias to the situation makes no discernible difference either:

```
    public static RasterizerState SolidNoCullBias = new RasterizerState()
    {
        CullMode = CullMode.None,
        FillMode = FillMode.Solid,
        DepthBias = 1f,
        SlopeScaleDepthBias = 1f,
    };

```

EDIT 2:

Culling the triangles will cause the object to look incorrect as a transparent object should show both the inside and outside faces.

EDIT 3:

Depth Stencil State is as follows with 'LessEqual' compare function (doesn't solve the issue)

# Answer
I have found a method which works and allows me to keep CullMode.None.

This involves the introduction of a small epsilon value which translates the triangle face along the normal. It is only activated for transparent objects.

The following line is added to the HLSL shader:

```
input.Position.xyz -= (input.Normal.xyz * 0.0001);

```

Perhaps this is an acceptable approach?

It can also be applied in screen space without the need for a multiplication

```
Output.Position.z -= 0.00001;

```
> 0 votes

# Answer
Have you tried to set the cull mode for the transparent cube to a state other than `CullNone`? It seems like the problem would go away if the backsides of the transparent cube were not drawn.
> 1 votes

# Answer
Use the "less than or equal to" depth compare function instead of a hacky bias, and render transparent polygons last using painters algorithm (as it looks like you are already doing).
> 0 votes

# Answer
this can be accomplished by a modified RasterizerState, that is set before drawing transparent objects.

```
private readonly RasterizerState _antiDepthFightingState
    = new RasterizerState{DepthBias = -0.000001f}

```

As far as I understand this, it adds a little bit to your (projected) z or depth value, before comparing it with the already existing value in the DepthBuffer. So for the graphics card my transparent objects are hovering over the other objects. But as far as you don't make DepthBias to big, this is not visible. Because of the fact the DepthBias is added to your depth value of a certain pixel, its amount has to be carefully adjusted to your near- and far-plane settings.

Finally your code should look something like this:

```
//set some paramters
...
//set antidepthFightingState
GraphicsDevice.RasterizerState = _antiDepthFightingState;
//draw your transparent stuff
...
//!reset RasterizerState State to default
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise

```
> 0 votes

# Answer
I can't find the source, but I remember someone suggesting that this z-fight could be caused by the vertex coordinates of the adjacent cubes not matching exactly due to floating point inaccuracy. For example if you render the left cube in `left = x * cube_width; right = left + cube_width;`, the position of `right` for cube `x` can differ from the position of `left` for cube `x + 1`. If you instead replace the second calculation with `right = (x + 1) * cube_width;` (assuming `x` is integer), the values would exactly match. When you render the exact same polygon twice, the z-fight should disappear.
> 0 votes

---
Tags: xna, 3d-meshes, transparency
---


# Question
Title: It is possible to use Pokemon images in a game?
Is it possible to use Pokemon images, names, elements in a game I would like to make? Are they still copyrighted, patented, would I get sued?

(Maybe their rights have expired by now, is what I am thinking?)

# Answer
> 10 votes
Copyright expiry depends where you live. The simple answer is that they are copyright, and you can get sued. (More likely you'll get a cease-and-desist shutting down development of your game and threatening legal action.)

If you really want a pokemon-style game, create your own unique game world and characters and use those.

# Answer
> 1 votes
Copyright protecion lasts for the life of author and 70 years based on the the longest living author if jointly created or if work of corporate authorship, works for hire, or anonymous and pseudonymous works, the shorter of 95 years from publication, or 120 years from creation.

# Answer
> 0 votes
You can not do because of the Straight of author. The only way is to contact the legal department of Game Freak and ask permission to use their works (sound, images, fonts and etc...)

---
Tags: legal, copyright, nintendo, intellectual-property
---


# Question
Title: How to make custom shaped holes in terrain
So I'm trying to create a game where you fit certain shaped objects into the hole that fits them (similar to the young children's game with different shaped blocks) in Unity 3D.

I've encountered a problem, how do I make the holes in the terrain? Or what type of object should I use for making holes in?

So far I've tried to make a 3d model in unity by using other cubes and planes, it just doesn't feel right. I guess I need to create a model in another software and import to unity, I don't know any other software I can use. Tips would help.

# Answer
There’s a plugin for this on the Asset Store: Terrain Hole System

Description: “This Unity extension lets you make holes in your terrain that characters and other objects can go through.”

More information can be found on the forum thread.
> 1 votes

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


# Question
Title: Performance of XNA 4,0 static vertex buffer / VertexPositionNormalTexture in F#
Good afternoon,

I have been toying with the VertexBuffer in XNA just to see what it is capable of. I have done some very minor 3D work in the past, so the concepts are not completely foreign to me; however, my knowledge and experience leave a lot to be desired.

I have run a few tests in release mode with a static vertex buffer, using VertexPositionNormalTexture, and performance has been bugging me. My initial tests involved a rotating view of 40,000 (give or take) randomly generated cubes, with vertices for edges obscured by adjacent opaque cubes not added to the buffer. The view worked fine, but performance was notably choppy, expecially when the corner of the randomized area rotated into view.

My first idea to optimize was to combine adjacent, parallel faces into single, continuous faces, and adjust the Vector2 texture coordinates to appropriately draw the repeating texture; however, when I tested a single rotating cube (36 total vertices) with each side showing 100x100 tiled repetitions of the texture, I experienced pretty much the exact same stuttering problem.

So I have to ask, what might I be doing wrong? Should I render my own pre-tiled RenderTarget2D textures to use with the static vertex buffer, so the GPU does not have to "tile" it so many times? Or does the GPU do that already on its own?

My vertex buffer is generated only once and sent to the GPU only once. My texture is loaded only once, and the same texture/effect is used for the entire vertex buffer.

I do not understand why a GTX 275 would have such a hard time drawing 12 textured triangles.

What am I missing?

From my custom Chunk class:

```
let construct() =
    _vertices <- _blocks.Values |> Seq.collect Block.vertices |> Seq.toArray

    let vertexCount = _vertices.Length
    if vertexCount > 0 then
        _buffer <- new VertexBuffer(device, VertexPositionNormalTexture.VertexDeclaration, vertexCount, BufferUsage.None)
        _buffer.SetData(_vertices)
        device.SetVertexBuffer(_buffer)

    _requiresConstruction <- false

member public m.DrawToDevice(device : GraphicsDevice) =
    if _requiresConstruction then construct()

    let vertexCount = _vertices.Length

    if vertexCount > 0 then
        let triangleCount = vertexCount / 3
        device.DrawPrimitives(PrimitiveType.TriangleList, 0, triangleCount)

```

From the Game-derived class:

```
override game.Draw gameTime =
    let skyColor = Color.CornflowerBlue

    game.GraphicsDevice.Clear(skyColor)
    let fogColor = skyColor.ToVector3()

    let effect = new BasicEffect(device)
    let cameraPosition = Vector3(0.0f, 0.0f, 125.0f)

    effect.World <- Matrix.CreateTranslation(chunk.ChunkPosition);
    effect.View <-
        Matrix.CreateRotationY(MathHelper.ToRadians(rotation)) *
        Matrix.CreateRotationX(MathHelper.ToRadians(rotation)) *
        Matrix.CreateLookAt(cameraPosition, chunk.ChunkPosition, Vector3.Up);

    let viewDistance = 250.0f
    effect.Projection <- Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, viewDistance);
    effect.FogEnabled <- true
    effect.FogColor <- fogColor
    effect.FogStart <- viewDistance / 3.0f
    effect.FogEnd <- viewDistance

    effect.TextureEnabled <- true
    effect.Texture <- sprite
    effect.EnableDefaultLighting()

    for pass in effect.CurrentTechnique.Passes do
        pass.Apply()
        chunk.DrawToDevice(device)

    base.Draw(gameTime)

```

sprite is a 20x20 Texture2D loaded from content

UPDATE: I tried the massive, single cube again, two ways:

* With a single, non-tiled, pre-stretched texture
* With a single, non-tiled, texture, stretched using Vector2 texture positions.

Both of them exhibit the exact same stuttering behavior I had before. Something must be wrong here. 36 vertices. Non-tiled 20x20 texture. Static vertex buffer. How on earth could this be stuttering on a machine that runs modern 3D games without issue?

Does XNA simply not play well with F#?

UPDATE: RESOLVED

The problem seems to have been recreating effect each frame.

I moved all effect code except for the following into m.LoadContent:

```
// Set the World matrix which defines the position of the cube
effect.World <- Matrix.CreateTranslation(chunk.ChunkPosition);

// Set the View matrix which defines the camera and what it's looking at
effect.View <-
    Matrix.CreateRotationY(MathHelper.ToRadians(rotation)) *
    Matrix.CreateRotationX(MathHelper.ToRadians(rotation)) *
    Matrix.CreateLookAt(cameraPosition, chunk.ChunkPosition, Vector3.Up);

effect.FogColor <- fogColor

```

CPU use dropped from 13% while corners rotating into/out of view, to 0-4%. No more stuttering.

Thanks anyway, though I would still certainly appreciate any tips.

# Answer
> 1 votes
The problem seems to have been recreating effect each frame.

I moved all effect code except for the following into m.LoadContent:

// Set the World matrix which defines the position of the cube effect.World \<- Matrix.CreateTranslation(chunk.ChunkPosition);

// Set the View matrix which defines the camera and what it's looking at effect.View \<- Matrix.CreateRotationY(MathHelper.ToRadians(rotation)) * Matrix.CreateRotationX(MathHelper.ToRadians(rotation)) * Matrix.CreateLookAt(cameraPosition, chunk.ChunkPosition, Vector3.Up);

effect.FogColor \<- fogColor CPU use dropped from 13% while corners rotating into/out of view, to 0-4%. No more stuttering.

(answered after mandatory waiting period)

---
Tags: graphics, 3d, xna
---


title: Drawing Transparency in XNA 4.0

text:
# Question
Title: Drawing Transparency in XNA 4.0
Using C# (VS2010) with XNA 4.0, I have a terrain layer (RenderTarget2D) in a 2D side-scroller. My visual system tracks updates to redraw individual tiles, but I am having trouble finding a way to clear out the rectangle where the tile will be drawn, which I must do because A) there may no longer be a tile or B) the tile may itself contain transparency.

How can I draw a rectangle of transparency onto an existing RenderTarget2D? I essentially want to clear just that rectangular portion of it.

My Google searches have not yielded anything relevant.

# Answer
Gustavo Maciel provided a link about BlendState, but it did not contain any information about the function of each BlendState option or how to use them. I have had quite a bit of time to play around with XNA now, and I have found the answer to this question through trial and error.

BlendState.Opaque will cause each color channel to overwrite the current render target, rather than alpha blending it in. For the example in my question, I could have created a small texture cleared with new Color(0, 0, 0, 0), and then drawn it onto my terrain layer after beginning the sprite batch as follows:

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque);

```

This could have been done even more efficiently through a .fx file, in a pixel shader, sourcing from a 2D texture with point sampling. Each pixel in the source texture would represent a single tile, and empty pixels would represent "no tile". Tiling this way is considerably easier and more efficient, as only 1 draw call is required to build the entire terrain layer, versus one for each tile if you rebuild every frame. It also prevents you from having to deal with preserving the terrain layer's state if you only update when tiles are actually changed.
> 2 votes

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


title: How to move on a mesh?

text:
# Question
Title: How to move on a mesh?
I am working on my collision system right now and I wondered how you can actually walk on a mesh. For example I'm thinking about a dynamically created little village and I want to be able to move the player across roofs etc.

I read about two different approaches to that problem.

1. Simulate the next step and test if the step can be performed. If it's all right, perform that step or abort otherwise
2. Perform the step and let the collision system handle a collision in the next frame.

Now, with regards to speed and accuracy, which one is better suited for my problem. As a sidenote: the player should also be able to climb stairs and I also want to prevent the player from moving on very steep parts of the model.

# Answer
Usually to see if the character is on the ground you raycast downwards from the characters origin and get the distance. That distance should be the model height if it's on the ground. Then if you don't want a character to fall off a ledge all you need to do is take the velocity vector you're about to apply and calculate the new position of the character (by adding vel\*dt to the origin) and then just use that point to raycast downwards to get the new distance. If the distance is bigger or smaller then some threshold then set the velocity to 0.
> 1 votes

---
Tags: 3d, movement, mesh
---


# Question
Title: How do I draw these tiles without them overlapping?
I want to make a map that is tiled, and I want to start the map with all grass.

I use this tile:

When I display this tile and place another next to it I get the following result:

How do I get it to be "flat?"

# Answer
> 1 votes
It looks like you're not properly calculating the offset in the height from one tile to the next. The offset needs to be set so that two tiles next to each other form a rectangle, like this:

Just adjust the height offset until there is no stair-stepping like you can see along the edges in your image. For this particular tile it's 25 pixels.

# Answer
> 0 votes
It looks like the edges of the green tile are shadowed so that it looks more like a box than a flat diamond. If you can edit the tile just make the entire diamond the same color or at the very minimum make the shaded area the same color as the top.

---
Tags: graphics, tiles
---


# Question
Title: Should I create generic bitmap/sound/et cetera wrappers for Allegro?
Basically, I have been writing a game in C++ using Allegro. I mostly just use the library to draw bitmaps, draw text, and play audio.

My main concern as the game continues to grow code-wise, is that with all the places I use `al_draw_bitmap`, `al_play_sample`, etc it becomes harder and harder to ever switch libraries if I so desire. Aka all the places in code I would have to change the function calls and data types (ALLEGRO\_BITMAP, ALLEGRO\_SAMPLE, ALLEGRO\_COLOR, etc).

I was wondering if it is a good idea to make a class (or classes) with generic mappings so that my code calls my own DrawImage(), PlaySound(), etc and then maybe typecast the data types (ALLEGRO\_BITMAP, etc)?

This way its much less to change in the long run. I understand there would still be work involved and obviously I could only switch to another C++ library.

I'm not sure if there is a reason why this would be a bad idea, or if its actually a good idea, whats the best way to go about it.

# Answer
> 3 votes
Finding a balance between hardening code against the future and completing your current project is often challenging. You don't want to waste time over-engineering solutions to problems you don't actually have, but you also don't want to create a massive amount of technical debt for yourself.

Some practical considerations:

* Other APIs almost certainly will have different semantics and interfaces for their corresponding layers of functionality (graphics, sound, et cetera). Unless you have experience with those other APIs, attempting to build yourself wrapper abstractions now will probably just result in abstractions tailored to the single implementation you are currently using (Allegro) and which will need almost as much refactoring themselves as if you just refactored the direct Allegro calls into calls against the new API.
* Particularly, since you describe the abstraction process as simply one of "typecasting data types," it implies strongly that you don't have the requisite background in other APIs to make forward-thinking decisions about the design of your abstraction.
* This means writing the abstraction probably will create a net increase in your workload over time, although you will learn some things from the experience.

Switching to another API may involve some changes in code around that which calls into the API as well; you won't have a trivial time of it. Additionally, switching APIs "just because" isn't necessarily a great idea because it doesn't necessarily bring you closer to the goal of finishing a project. Unless there's added value to be had in switching to a new API for something, if you've got one that works and satisfies the requirements of your project, switching to something else isn't really a smart decisions *except* as a learning exercise.

Hiding implementation dependencies from the rest of your code is a good idea. It helps keep seems isolated and maintainable. To that end, I'd suggest that you build your own interfaces on top of the 3rd party libraries you are using and have the rest of your game call into those interfaces (for example, have your game logic call into your own rendering functions, which themselves call in to the Allegro functions directly). Do not expose Allegro types or enumerations directly outside that layer.

Do this to hide implementation detail, not necessarily to ease future ports. It will teach you things about implementation hiding and its benefits and related techniques, and it will give you a basis to work from in the future should you ever need to change to a different API, but you won't directly solving the "porting" problem since since you don't actually have an immediate need to solve it.

*Don't* go back and do this as one giant change-all-the-things refactoring operation. That's also taking time away from your goal (finish the game) just to reorganize code that already works and is presumably shippable. Rather, make these changes slowly over time, perhaps only starting with new bits of functionality you need to add.

# Answer
> 0 votes
As previously answered, Allegro is already cross-platform enough.

If you are writing your own game engine, and you want to work in the exposed API first, so you can see if It is convenient enough to use, and you don't want to work at low level yet, then you can use Allegro behind the scenes for now until you decide to finally replace that with your own code.

Now, do you really need that? As Allegro is already cross-platform, if It already runs in all your target platforms then why the need for code hiding it.

In the past I did something similar to the engine thing but with SDL. The idea was to write my own low level code for some core functionality at some time during development, but in the end time passed, the game continued, and SDL is still there. Replace it would mean to test the platform specific code in each targeted platform. Note that is still the idea, but It is always postponed for latter.

In resume:

Are you writing a game? Only wrap Allegro when you want to group repetitive tasks. Use classes calling Allegro functions where it have sense. Do not wrap simple things like ALLEGRO\_COLOR except you want to add something extra that you know you need it to happen always when you use ALLEGRO\_COLOR.

Are you writing a reusable engine? As I said in the first paragraph, maybe It may be justified to start wrapping the Allegro API. Maybe you want to add a switch to the build configuration where you let other people decide if they want to depend on Allegro or another libraries that your engine can use.

Are you writing an engine then a game that use it? Rethink things. What are the resources at your disposition (time/manpower)? Maybe you should be writing a game only.

---
Tags: c++, image, sound, allegro
---


title: How to achieve animated glow

text:
# Question
Title: How to achieve animated glow
I am trying to achieve something I've seen numerous times, but I don't know where to start from. I've come across numerous old effects, which I can't recreate. The said effects are the glow animations seen here: world of warcraft armor sets or for instance here Diablo glowing wings. In my desperation I even tried to contact blizzard, but with no success.

My common logic tells me these effects are not implemented with particles as that would be too expensive, especially on the hardware WoW ran on. On top of that, these looks strangely static, in a way even 2-D. I suspect something to do with images. I'm only a hobbyist graphics programmer(on top of that, not a good one) and I can't wrap my head around it. I would really appreciate any help.

# Answer
> 11 votes
Since you dismiss the particles I assume that you mean the self-illumination map.

The basic is that you start with a texture that has the glow in it.

But of course the shader has no way of knowing that the glowing part should not be made darker by the shader. So you need to mask off the glowing bits like this:

So now in the shader you factor in the glow mask and porportionally exclude everying in the mask from the shading, your result should look something like this (left side with glow mask, right without):

It basically boils down to

```
gl_FragColor = (1 - maskcol.r) * shaded_col + maskcol.r * raw_col;

```

which looks like this if you need some visual help:

You can make this pulsate by introducing an additional factor which you can pass to the shader.

```
illumfac = scalefac * maskcol.r;
gl_FragColor = (1 - illumfac) * shaded_col + illumfac * raw_col;

```

If you want something more irregular than just a uniform pulsating you can put a scrolling texture as your scaling factor for the self-illumination map.

But like I said this is only part of what the videos you posted show, but you didn't specify what exactly you wanted and like I said additive blending and particles can also be seen in parts of the examples.

---
Tags: shaders, graphic-effects
---


title: Android Dynamic 2D Map

text:
# Question
Title: Android Dynamic 2D Map
My problem is, I want to create a 2D tiled map. Yes, I know it's been asked a lot. I've seen answers that propose the use of tiled however it only allows (or so it seems to me) to generate static maps that do not change once generated. And I need a large empty uniform space of empty tiles, upon which players may place various buildings (some spanning more than one tile and logically being the same one).

How to approach this in Android? Do I make some kind of TableLayout, use arbitrarly large amount of rows and imageviews (with my emptyTile), than somehow work event-based changing of image ids from there? I'd think that only a portion of that map should be visible at a time, but I don't see how scrolling around could be the part of that structure.

# Answer
> 3 votes
Have you considered using libgdx? It's a Java game development framework (you really want to use a framework if you want to develop Android games) that allows your code to run on desktop, Android, iOS, and HTML5. It's commonly used to focus on the Android part, and you can see that on the Tiled support page, libgdx is listed (under Java).

Tile-based platformers are a very common approach, and it's very easy in libgdx. In fact, this tutorial, which is listed on the libgdx tutorial list, shows you how to implement a tile-based platformer.

To relate to your question specifically: no, the map does not have to be static. Tiled just provides you with an easy map creation method. The file that Tiled provides can be accessed through libgdx (see the documentation here). Once loaded, that file can be treated like any other `TiledMap` object. Again, you really don't want to do this through the default Android libraries.

Just so you know, AndEngine, another Java game development framework for Android, can also use Tiled (according to that page). I have no experience with that framework, however, and you'll have to do your own research to decide which one you want to use.

---
Tags: 2d, android, tiles, maps
---


# Question
Title: I want to make a moddable game. How does this affect my programming language choice?
I have been getting started making some small games in Java, and I am considering learning C# for a bigger project. I would very much like to make a moddable game, but someone told me that I need to stick with Java if I want the game to be moddable, though I don't understand why.

So, what programming language characteristics make a language more suited to moddable games?

# Answer
It depends on how you want to design your mod system. I'll explore two of them.

# SDK

Most likely you will require that your modders use the same language as you do, and load up mods via reflection (or similar, depending on your language of choice). This will obviously limit you to languages which can do late binding - and there are a good many that can do this (even C can do late binding with some clever `LoadLibrary` trickery). You could even do some meta-modding, where a mod could host other mods (e.g. scripted mods).

The first problem with this approach is hiding internal state. Taking C# for example a modder could simply use reflection to access private members, C can also do this (although more effort is required).

The second problem is hosting. People don't really like foreign code running on their system with no sandbox in place. As a worst-case scenario you could write a mod that sets up a seedbox; if this was installed at an ISP it could do some serious harm to their reputation.

# Scripting

Modders would use a language such as Lua to create mods. You would either require a language that could invoke native code (to interface with Lua); or you would have to write your own scripting language in your language of choice.

The first problem here is that most scripting languages are interpreted, which may not be acceptable for real-time systems (although, see LuaJIT); such as games.

Ironically the second problem still exists here; taking Lua as an example I was extremely disappointed that is has 'shelling-out' functions included in the core/default library - making it entirely useless as a sandboxed environment (without a large amount of effort, luck and maintenance), *it's hard to portray how angry I am about this, but I really hope they were drinking some strong cocktails when they included these anti-features*. You could obviously easily avoid this if you rolled your own language (see: UnrealScript).

Finally the cost of interacting with a scripting engine may be prohibitive - again taking Lua as an example, combined with C#: C# has substantial overhead when invoking native functions (via P/Invoke) and Lua is quite a 'chatty' API. This could lead to problems if the way you design the 'script SDK' requires a lot of chatting between your primary language and your scripting language (note that C doesn't really have this problem). Again you could dodge this by writing your own scripting language (and in the case of C# compiling it to MSIL) and executing it in the quickest way under your \[virtual\] environment.

Because the script is essentially running on a completely different system to your primary code you can control the access to internal state entirely (unless they do some fancy stuff with the previously-mentioned shell functions).

# Conclusion

I did veer a bit off-topic, however, what you can basically garner from that wall of text is that you *should* be able to make a moddable game in any language (I would venture to say that you *can*) - but in some languages may lead to more work. Am I a bit anal about security? Yes, you should be too when it comes to user-code.
> 18 votes

# Answer
I'd say the language is not much of a deciding factor here, it's really just how flexible and data-driven you make your game that defines it.

Every game runs on a set of data (e.g. everything from levels, meshes, configurations, items). The difference between a normal game and a moddable game is that the later provides tools that allow the user to modify existing data (or add his own data). Whatever language you choose, just try making your game as data-driven as possible and avoid hardcoding any game content. Virtually any language you'd probably choose can read data from disk, which is most of what you need.

It's also half way there if you just create the tools for your own personal use (for instance, your own level editor) and later perfect them and share them with your users. The Super Meat Boy level editor was pretty much that, an improved verision of the tool used during the development of the game.

And depending on the type of game, you might want to allow users to script some of the game behavior. In which you case you should look into incorporating a scripting language into your game since early (either your own, or an existing one like Lua or Python which are popular choices). This also falls under the category of data-driven design. If you decide to use an existing scripting language, it might be worth checking if the programming language of your choice has bindings for that scripting language (usually in the form of 3rd party libraries).
> 15 votes

# Answer
The language you choose doesn't really determine how moddable a game is, the way you use the language matters more.

If most of your game is data driven (that is game data is defined in a file which is read from your code) the game can be very modifiable. This can be done in pretty much any language. Using a scripting language also makes it easier to mod a game.

However that does not automatically mean not using those things makes it impossible to mod a game. Minecraft for example is not a very moddable game at all, however there are pretty good decompilers available for Java and a very large community for Minecraft, so a lot of tools were made to make Minecraft moddable (various modloaders, Bukkit). With those tools it is possible to mod Minecraft (however they are, probably, technically illegal in some countries).

Best advice I can give you, is to use the tools you want modders to use; If you define a NPC from a file it can be modded, if you special case it in code it probably can't be.
> 5 votes

# Answer
Java is perfectly suitable for writing a moddable game.

Having said that, the best way to make a game moddable is usually to adopt a *dynamic language* that can be embedded within the broader application and used for scripting. You typically want a dynamic language because the point is to be able to interact with the code at runtime, without going through a whole compile/build/test cycle.

Some dynamic language choices to consider:

* **Groovy** \- an excellent dynamic Java-like language that can be embedded within larger Java programs.
* **Clojure** \- a powerful, dynamic Lisp for the JVM. Might be hard for some modders to get their head around, but is an exceptionally powerful language and can be embedded very easily. Haven't seen it used yet for game modding but no reason why not.
* **Lua** \- a very popular game scripting language. I beleive there are versions for the JVM that you can use from within Java (although I haven't tried these myself)
* **JavaScript** \- available on the JVM via Rhino. A pretty solid choice for game scripting as lots of people know some JavaScript, plus the prototype object model fits game mods very well.
> 1 votes

# Answer
There is a way easier way to do this in java though it's a bit sloppy. All you gotta do is take the dot java files in a folder and then put this batch file with the folder, name it Run:

javac /src/.java Java /src/

Note: You can add as many classes you want. Note: In the last line make sure NOT to put any extensions aka .java,.exe,.bat,ect.

That will basically just recompile the code every time the game is run, so if the game source is change it will compile it and then run the newly compiled game... Sadly you can't add other people's mods into the game.
> -2 votes

---
Tags: modding
---


title: Sprite erasing text in Pygame

text:
# Question
Title: Sprite erasing text in Pygame
I'm making a Pong clone in which the user can press the 'p' button to pause/unpause the game. When the user presses the 'p' button the word 'PAUSE' is drawn to the screen and when he presses again the word is erased. My problem is this:

As you can see, the ball sprite is erasing the text. Any clue on why this is happening? Here is the code for the main stuff.

# Answer
In your code flow, you are drawing the "Pause" text immediately when the player presses `p`. Later on in the same frame, you draw the other sprites. Pygame `blit` operations always draw on top of what has already been drawn.

If you want the pause text to appear above everything else in the game environment, you'll have to move the code that blits it to a point after everything else is blitted. Also, you'll want to draw it every frame.

Some code snippets might look like the following:

```
# Declare a boolean to track pause state.
paused = False

# Some other game code...
# ...
# ...

    elif event.type == KEYDOWN:
        if event.key == K_p:
            if not paused:
                pygame.mixer.music.pause()
            else:
                pygame.mixer.music.unpause()
            paused = not paused

# Some more game code...
# Blit the rest of the game world to the background.

if paused:
    # Draw the pause text on top of everything else.
    screen.blit(self.pause_text.image, self.pause_text.rect)
    # Some other pause code...

pygame.display.flip()

```

I noticed that you tried to throw the game into a second loop while it's paused to limit what's executed. Personally, I don't recommend this pattern, but if you'd like to stick with it I think that you'd just need to add a `pygame.display.flip()` to that loop and pull the blitting of the pause text out of the conditional for unpausing:

```
while pause:
    if event.type == KEYDOWN and event.key == K_p:
        pygame.mixer.music.unpause()
        pygame.time.delay(150)
        pause = False

    screen.blit(self.background, self.pause_text.rect, self.pause_text.rect)
    pygame.display.flip()

```

It doesn't make any sense to re-blit the pause text when the player unpauses the game.
> 2 votes

# Answer
I have no experience with pygame specifically, but the problem is not unique to one language, engine or framework. Most likely it has to do with the order in which you draw things, or with the depth if you set that explicitly.

In most cases, the default behaviour without setting a draw depth is that things are layered in the order they are drawn, meaning the last object that is drawn will be on top of anything else that was drawn in that area. In this case, you probably draw the word at some point after the middle line, but before the ball sprite, which would be why the ball is on top. The solution would be to move the drawing of "PAUSE" to the last possible position in the code, to ensure that it is drawn on top of everything else. Another possibility would be to explicitly set a draw depth, telling each object that is drawn at which depth it is, but I don't know pygame well enough to give you an example.

If you already are setting draw depth explicitly, it's almost certainly a small error with the depth parameter either in the word or the ball sprite.
> 0 votes

---
Tags: python, pygame, text
---


# Question
Title: How do I find the 2D direction to a 3D location?
I'm writing a 3D space flightsim, and I'm trying to display a 2D arrow on screen that points to the player's selected target. To clarify, the arrow needs to point in the direction that the player has to turn to reach the target.

I've tried several approaches but I can't seem to make this work for all cases. My current attempt involves constructing a plane from the player's local X/Y, projecting the target position onto it (to make the calculation 2D) then calculating the angle between the player's up and the vector to the projected target position.

I can't help but think I'm over-thinking this and there must be a better, simpler way. Anyone have any suggestions?

**UPDATE:**

Based on Sam's answer, I've tried the following code:

```
//Find the direction to the target, and normalize it
kglt::Vec3 target_dir = (target_pos - ship_pos);
target_dir.normalize();

kglt::Vec3 v1, v2;
v1 = ship_up.cross(ship_dir);
v2 = ship_up.cross(target_dir);
v1.normalize();
v2.normalize();

//Get the angle of rotation for the arrow
float angle = kmRadiansToDegrees(atan2(ship_up.dot(v1.cross(v2)), v1.dot(v2)));

```

But the returned angle is always around 180.0 (although normally -179.xx). Is there any obvious error somewhere? I'll continue debugging and update if I figure it out!

**UPDATE2**

Nevermind, the bug isn't in this section of code. My bad!

# Answer
> 0 votes
Whilte trying Sam's idea, (which almost worked but I couldn't quite get the behaviour right), I found a bug in the functions that returned the ship's forward and up vectors. Once I'd fixed that, my original idea of projecting onto a plane worked fine. Here's the solution:

```
kglt::Vec3 projected;
kmPlane plane;

//Create a plane from the player's position, and forward vector
kmPlaneFromPointAndNormal(&plane, &ship_pos, &ship_dir);

//Project the target's position onto the plane
kmVec3ProjectOnToPlane(&projected, &target_pos, &plane);

//Calculate the direction to the projected point
kglt::Vec3 target_dir = (projected - ship_pos);

//Use atan2 magic, combined with the forward vector to calculate the correct angle for the arrow
float angle = kmRadiansToDegrees(atan2(-ship_dir.dot(ship_up.cross(target_dir)), ship_up.dot(target_dir)));

```

Thanks everyone!

# Answer
> 5 votes
I suggest the following method:

* Build a vector pointing to the ship’s left, from its up vector and current direction.
* Build a similar “left” vector using the target location, as if the ship was already pointing in the correct direction.
* These two vectors lie in a 2D plane orthogonal to `ship_up`. You just want the angle between them.

Using GLSL syntax, assuming `ship_up` is already normalised (otherwise, add a `normalize()` call around it in the last line):

```
vec3 v1 = normalize(cross(ship_up, ship_dir));
vec3 v2 = normalize(cross(ship_up, target_pos - ship_pos));
float angle_radians = atan2(dot(ship_up, cross(v1, v2)), dot(v1, v2));

```

# Answer
> 0 votes
I'd simply transform the game/world coordinates of the target into screen coordinates. You might end up with a position outside the visible screen (like negative coordinates), but you'll still get directions for this. If the resulting coordinates are on screen, just check whether the target is in front of or behind the player and you're done.

# Answer
> 0 votes
1) Project both player position P and target position T using the usual projection matrix.

2) Make

```
V = normalize(T - P),

```

which is the direction in the screen of the vector that connects player and target.

3) To display the arrow you could use a sprite aligned with the screen X axis = (1,0). You just have to rotate it accordingly with the slope of V. To get the angle, just apply the usual slope formula:

```
 tgTheta = (y2−y1) / (x2−x1)

```

---
Tags: opengl, mathematics, vector, direction
---


title: GGX specular BRDF is way over 1!

text:
# Question
Title: GGX specular BRDF is way over 1!
Now, the classic Torrance derivation for roughened surfaces which Cook took into vectorized form yields the familiar parametrization of a specular BRDF where we have the NDF which decides how much perturbation is around the average normal direction of the macrosurface. For example, in the isotropic GGX version, an alpha value is used to modulate just how rough the surface is or just how much specular reflection a partical halfdirection yields from the microsurface normal.

Then there's the geometry term which is, numerically, a protective term from the classic denominator of `dot(n,v) * dot(n,l)` which can tend to zero and the whole term to infinity. It also has a more physically intuitive side rendered irrelevant by the sheer horror of division by zero.

And there's the Fresnel term, the least threatening of all of them.

Basically, it's DGF / (4(n.v)(n.l)). And if any of these terms fail, it goes to hell. Hence, all of these terms have normalizing terms which force them in the \[0,1\] range. Unfortunately, the one I was studying from Epic does not converge give in to the normalization and some values at grazing angles get frustratingly high.

The BRDF is the ratio between the outgoing radiance and the incoming irradiance. Anything beyond 1 is weird to me. But 477.43 is... Well... I've double-checked everything, the math is a direct match. And yet...

Any ideas?

# Answer
> 7 votes
The BRDF is a reflectance *density*, not a reflectance. Values beyond 1.0 are perfectly sensible as long as they occur only in a small region of the parameter space. The whole thing has to *integrate* to a value in \[0, 1\] to avoid adding energy, but that doesn't imply it has to *be* in \[0, 1\] everywhere.

It's similar to a probability density. If you look at a standard pdf like the normal distribution and plug in a small value for sigma, you'll see the distribution gets narrow with a high peak that goes much higher than 1.0, even though probabilities can't be higher than 1.0. It can do that because it's not a probability, but a probability *density*, i.e. probability per unit length. When there is a lot of probability crammed into a small distance you get a high density.

The BRDF has units of reflectance per unit solid angle, so whenever there is a lot of reflectance in a narrow solid angle (e.g. with a shiny, high-gloss surface), you will get values greater than 1.0.

FWIW, I've calculated the integrated directional-hemispherical reflectance for GGX and various other common BRDFs and found they indeed do not add energy. (They sometimes absorb it even when they're not supposed to, but that's another story...)

---
Tags: physics, mathematics, graphics, pbr
---


# Question
Title: Change emission level of a set of vertices within a mesh
ok so here is the problem I need to solve.

I have a known set of vertices that I need to "animate" the emission level of. Currently I have a vertex definition setup and RGB color data for each vertex. and I can animate that. but obviously that doesn't effect the lighting.

what would be ideal I think is if I could take the basic effect class and apply it to just a few vertices at a time but so far I cant find a way to use it on anything less than a mesh.

Update

Thanks to Evan I think the way to go is to get each of these indices and create a mesh that will overlay the existing model. This would make it easier to control transparency as well as the emission.

The question I have is lets say these indices do not make up a full triangle? Maybe after I find all of the vertices I also find that they don't divide out to 3.

I guess what I need now is what would a good way to pull this mesh apart be?

# Answer
If you want alternative lighting calculations or shading effects (beyond color shift) you can do it in a few ways.

The first way would be to create a separate object that uses the vertices you want to be rendered, and either render the original object without these vertices, or simply overdraw the same vertices with the new effect. The overdraw is likely to be more efficient than the time it would take to sort out vertex buffer and index buffer organization. You may also need to remove z-testing for the effects pass.

The second way would be to modulate specific vertices color, and render them a very specific color that is not present in your game in any other fashion (such as a vibrant pink). After that, you could perform glow effects or whichever as a post processing step, that only acts on anything rendered using this particular color. The color of course is only being used as an obvious identifier. This method would likely be best if you are rendering many different objects in this way. Edit, also for this particular effect, you will have to avoid texture sampling in this situation one way or another, otherwise it will be blended with the modulated vertex color, producing inconsistent color variations.

The last way I could think would be to actually implement branching code in whichever shader is applied to objects that could have this effect. I highly advise against this, as branching code is problematic and generally much slower on GPU's, and you REALLY dont want a default shader to have branching code in it. You could perform a shader swap though whenever this effect is enabled, and test the performance characteristics of it. This would also require additional data overhead, as each vertex would need a flag indicating whether it is currently part of the desired effect, or rendered normally. This is the worst of the three by far, but it is an option.
> 0 votes

---
Tags: xna, lighting, vertex, silverlight
---


# Question
Title: Encapsulating Box2D C++ two virtually the same functions
I have two functions that are virtually the same with a few small differences in code, one to create a static body and one to create a dynamic body, however if I call both of them it results in a segmentation fault, but I'm not quite sure why as far as I know I'm not trying to redefine any objects (other than bbox which is a box2d * body).

I've tried debugging it it appears the issue is caused by b2FixtureDef but I again Don't know exactly what it is, From looking at the memory somewhere there is an allocation issue as 0xfeeefeee shows up in a dump of the registers.

as long as I only use one its fine but when I use two or more it crashes. if someone could point me in the right direction ( the code is valid 0 errors and 0 warnings so I'm not looking for handouts )

```
void entity::setAsPlatform(float hx, float hy, b2World world)
{
   b2BodyDef platformDef;
   platformDef.position.Set(bbox_pos.x,bbox_pos.y);
   b2Body * platform = world.CreateBody(&platformDef);
   b2PolygonShape platformShape;
   platformShape.SetAsBox(hx, hy);
   b2FixtureDef platformFixture;
   platformFixture.shape = &platformShape;
   platform->CreateFixture(&platformFixture);
   bbox = platform;
}

void entity::setAsPlayer(float hx, float hy, b2World world)
{
   b2BodyDef platformDef;
   platformDef.position.Set(bbox_pos.x,bbox_pos.y);
   platformDef.type = b2_dynamicBody;
   b2Body * platform = world.CreateBody(&platformDef);
   b2PolygonShape platformShape;
   platformShape.SetAsBox(hx, hy);
   b2FixtureDef platformFixture;
   platformFixture.shape = &platformShape;
   platform->CreateFixture(&platformFixture);
   bbox = platform;
 }

```

and in main.cpp

```
entity platform("Platform", 20, 500);
platform.setAsPlatform(2.0f, 50.0f, world);

entity player("Player", 0, 20);
player.setAsPlayer(1.0f,1.0f,world);

```

# Answer
> 1 votes
Your main problem is that you keep copying and destroying values that you don't mean to destroy.

Let's take for example `world`

When you call `platform.setAsPlatform(2.0f, 50.0f, world);` you make a copy of `world` because `setAsPlatform` takes a `b2World` by value.

You probably meant to write

```
void entity::setAsPlayer(float hx, float hy, b2World &world)

```

This would take `world` per reference and not make a copy which is destroyed at the end of the function. So you added your objects to a copy of your world that you then destroyed, so when the object then tries to look up anything in the world that it's in it'll access already freed up memory as the `0xfeeefeee` indicates.

---
Tags: c++, box2d
---


title: View Matrix from Camera in Unity Script

text:
# Question
Title: View Matrix from Camera in Unity Script
I am looking to get a Camera component's "view" matrix in a script. I see that I can get the projection matrix using Camera.projectionMatrix, but I don't see a Camera.viewMatrix property...

I want these matrices in a script for a 3D graphics refresher tutorial that will visualize a camera's view and projection transforms in the form of game objects (representing vertices) that can be moved around the scene.

# Answer
> 1 votes
It looks like Camera.worldToCameraMatrix *is* the transform that is commonly referred to as the "View" matrix. After transforming some vectors using this and the projection matrix, I am getting the exactly results that I was expecting. Awesome. :)

---
Tags: unity, matrix, view
---


# Question
Title: Should static tiles and dynamic tiles share the same parent class?
I want to make an abstract `Tile` class for all of the tiles in a platformer game - walls, platforms, floor traps, everything. This parent class has basic things every tile will have, such as width and height, position, and boundbox, as well as getters for all of these things. I want to make these attributes constants, because those things typically shouldn't be changing - a wall shouldn't have its width and height changed, for instance. However, in some special cases, those attributes may indeed change - a special platform may change its height when the player jumps on it, or another special platform may disappear after 1 second after the player jumps on it, for instance.

This presents a problem, because for the static tiles, non-constant attributes in the `Tile` class is bad practice, but for dynamic tiles, constant attributes will prevent them from being dynamic. Is the best method, then, to create two different parent classes, which are the same, aside from one with constant attributes and one with non-constant? Is there a special name for dynamic tiles (I've heard "entity" thrown around, but I really don't know)?

# Answer
> 5 votes
I suggest *avoiding inheritance* altogether. Inheritance hierarchies quickly become unwieldy, especially when you start layering on multiple differences:

* dynamic vs. static tiles
* destructible vs. invulnerable tiles
* normal tiles vs. trigger tiles
* invisible vs. visible tiles
* colliding vs. non-colliding tiles
* lethal vs. non-lethal tiles
* etc.

See where I'm going? If you start trying to model all these differences with inheritance, your class heirarchy will quickly become a nightmare.

Instead, model all these things as either properties or sub-components of a tile. You may want to look into:

* Prototype based object models
* Component-entity systems

For example, in a component-entity system approach, you might have a "MovingTile" component that indicates a tile is dynamic, and encapsulates the pluggable logic for moving the tile around in a predefined pattern.

# Answer
> 1 votes
Quick Answer: Depends heavily on your usage pattern.

You are, in fact, describing an entity in your question. Tiles are *generally* following a geometrically regular tessellation (Quads, Hexagons, Pentagons+Hexagons, Octagons+Quads, etc), and thus can gain the benefits of deterministic procedural layout.

If you have true tiles creating the majority of the world, definitely take advantage of the spatial structure and create a specialized system apart from the entities. On the other hand if your "tiles" are irregularly positioned or shaped, then it doesn't make sense to call them tiles at all.

In either situation, you probably should not differentiate between static and dynamic entities at all without a good reason! Your systems should decide how to organize and process the workload, not your data.

**Example**: Even if an entity is not "static" you might gain a benefit from letting it be considered static while it's inactive. (This time limit can be estimated from how long it takes to update your acceleration structure).

To reiterate, data represents *what* to do, the system knows *how* to do it.

*PS: It's only bad "practice" if your skills don't improve by it.*

---
Tags: tiles
---


# Question
Title: Maya Command Line - change texture applied to a model before rendering
I've written some batch scripts which automate maya through the Render application. The batch scripts are working over a series of different scenes and render all of them out.

For some of the models, I would like render the animations in the scene multiple times with different textures applied. Right now, my only solution is create another scene, apply the new texture and include the copied scene in the batch scripts.

Is there another, better way to do this? Ideally, some command line arg that said use texture X for this render would be lovely.

# Answer
> 1 votes
The documentation is pretty clear on how to do it.

An example of how to change a node called `file1` would be

```
"C:\Program Files (x86)\Autodesk\Maya2012\bin\Render.exe" -r file  -preRender "setAttr file1.fileTextureName -type \"string\" \"C:\\temp\\texture1.png\";" -im outfile1 C:\temp\scene.ma
"C:\Program Files (x86)\Autodesk\Maya2012\bin\Render.exe" -r file  -preRender "setAttr file1.fileTextureName -type \"string\" \"C:\\temp\\texture2.png\";" -im outfile2 C:\temp\scene.ma

```

This renders `C:\temp\scene.ma` to `outfile1` with `file1.fileTextureName` set to `C:\temp\texture1.png` and to `outfile2` with `C:\temp\texture2.png`

---
Tags: rendering, maya
---


# Question
Title: XNA Calculate two points of triangle with given Z
I want to calculate the two points of a 3D triangle that have a specified Z coordinate. I guess the way to do this would be to somehow create a plane which is perfectly flat with my given Z coordinate and then calculate where the triangle intersects with it (or is this wrong).

If you know how to do this in any way please help. I have searched for but have not really found anything that seems to work.

# Answer
Here is a method that I hope is intuitive enough, assuming `z0` is the Z value of your intersection plane:

* start with an empty list of points `L`
* if `(A.z - z0) * (B.z - z0) <= 0`, it means AB intersects the plane:
    + compute `u = (B.z - z0) / (B.z - A.z)`
    + add point `B + u * (A - B)` to list `L`
* if `(A.z - z0) * (C.z - z0) <= 0`:
    + compute `u = (C.z - z0) / (C.z - A.z)`, add point `C + u * (A - C)` to list `L`
* if `(B.z - z0) * (C.z - z0) <= 0`:
    + compute `u = (C.z - z0) / (C.z - B.z)`, add point `C + u * (B - C)` to list `L`

At the end, if `L` contains two points, that's your segment; otherwise, either the triangle does not intersect or it's a degenerate case. Make sure you check for possible divisions by zero.
> 1 votes

# Answer
You could just du a ray / plane intersection with two rays, after deciding how the triangle intersects with the plane (To intersect at all 1 point has to be on side A and two points on side B of the plane)

This is my standard 'way-over-the-top' ressource for intersections you can look at different implementations and pick the one best suiting your need.

I little less complex is this side, explaining what to do and providing a trianlge-ray algorithm in c (and a lot more under 'algorithms')
> 0 votes

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


# Question
Title: Will Google Play Game Services allow turn-based gameplay?
Will the Google Play Game Services multiplayer allow (turn-by-turn) gameplay like DrawSomething?

# Answer
> 1 votes
You are not talking about asynchronous gameplay (which is explained here).

You are talking about turn-based gameplay. But I think you can relinquish the idea of using Google Game Services, because of the missing realtime gameplay (= you don't need to establish a connection between the clients).

I would recommend using a database, which contains everything relating to the game like the gamestate, the players, who did the last turn and things like this.

# Answer
> 0 votes
If you can do synchronous gameplay (i.e. playing together in realtime) you can always do asynchronous gameplay as well. The only deciding factor is whether you're able to establish the required connection at any time.

---
Tags: android, networking, google-play
---


title: How to implement a shotgun in a game?

text:
# Question
Title: How to implement a shotgun in a game?
Pistols and machine guns are easy - you can just have bullets flying in a certain direction, so I already implemented that. A shotgun, on the other hand, does damage to anything in a certain area that looks like a cone. How should I implement that? I have a couple suggestions here, but I could use some advice:

* Split a bullet in multiple little bullets, that do less damage by themselves, but fly in a similar direction (a closer enemy is more likely to be hit)
* Not use bullets - just have a particle effect of a shotgun shot and calculate how much damage enemies get based on position/orientation etc.
* Have a big invisible bullet (a cube for example) that damages things, as well as a particle effect that will make it look like it's actually a shotgun shot.

Thanks in advance!

# Answer
> 21 votes
Most games implement shotguns as a weapon which fires multiple projectiles at once, but each one with a certain randomization of the angle they leave the actor. In most modern first-person-shooters almost all weapons have at least some spread for every shot they fire to make them less accurate on long range, so the same implementation can be used for shotguns.

**Simple implementation:** When you want a 10° spread and the player looks into direction 0° vertical and 50° horizontal, the projectiles would leave them in an angle between -5° and +5° vertical and between 45° and 55° horizontal.

**Better implementation:** Spread the projectiles not in a rectangular but in a circular area around the crosshair of the player.

The perceived reduced efficiency on long range results from the spreading of the projectiles which means that distant and small targets won't be hit by all of them. When you would like to further emphasize this to make your shotgun a pure short-range weapon, you can also reduce the damage of each projectile for every game-logic frame it travels.

In top-down or side-scrolling shooters it is less common to have spread on all weapons because the playing-area is too small for this to make sense, but when you want a weapon like a shotgun this is a different matter and the same technique can be used, just that you don't need to care about the 3rd dimension. Alternatively you could just fire the projectiles in fixed angles Like -6°, -4°, -2°, 0°, 2°, 4°, 6°. In a 2d context it won't look as artificial as in a 3d context and the challenge-gamer will like it, because it reduces chance.

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


# Question
Title: Should an actor know its position (or map should know it)
In a tile-based game (in this case MMO), should an actor (e.g., player) know its position, or should only the map know its position?

If an actor is placed on a grid map, it is placed on a specific position (x, y) and assigned to a cell in the map. Now, should I *also* store the actor's position inside the actor's data structure? It would allow to check the actor's position easily (just check it's data) but at the same time, I duplicate the same information in two places which is bad and could introduce a whole spectrum of bugs (e.g., if those two pieces of data are inconsistent)

# Answer
In order to achieve better performance when testing for collisions, checking for surroundings and nearby agents, you have to keep track of an agent's location on the map (so you don't get to check each cell to see who's in it, you just pick an agent and check the other cells surrounding him up to a given range).

Unless you have a pre-processed list of agents to work with and their location, it will be handy to keep the location at agent-level too. You don't want to lessen the advantage you've got in the previous paragraph by going through the grid to see where your agent you want to check the surroundings for might be positioned.

You don't necessarily have to store *raw* positions in both places. The map could simply use pointers to agents, which store their own location. This way there's just one position, and the map references it.

```
class Cell
{
      private Agent[] agentsInside; // Keeps track of all the agents in this
                                    // cell. If one moves away, it gets
                                    // deleted, and the new cell starts keeping
                                    // track of it.
}

```

Since you're on a 2D grid dealing with moving agents that can collide, you might be curious to also read more on the topic. With the fixed-size cell approach, Bin Partitioning could be a good place to start.
> 5 votes

# Answer
Yup, store in on both. There's a couple of answer about this already ...

Its really convenient to have an actor know its own location.

Its also convenient to have each tile knows which actor is on to affect specific status, traps, events, etc, instead of always going threw the npcs list. you wont have performance issue by storing 1 pointer in your class ...

its also easy to create a moveActor() method as the only way to handle movement, and have this method update both values.
> 0 votes

---
Tags: architecture, maps, tilemap
---


title: Using Bluetooth in a Unity3D Game

text:
# Question
Title: Using Bluetooth in a Unity3D Game
Apart from using a plug in or other third party device, is there anyway Unity can support bluetooth communication between two devices?

All of the links I have found seem to relate to third party options which I want to try and avoid.

# Answer
> 2 votes
The reason you're only finding third party options is because Unity doesn't have any built in support for Bluetooth.

> is there anyway Unity can support bluetooth communication between two devices?

Yes, you'll need to use a third party library to add the support, or you can write your own (not recommended).

Which library to use is up to you, find one that meets the requirements for your platform and works with the hardware you want it to.

---
Tags: unity, bluetooth
---


# Question
Title: Trying to figure out SDL pixel manipulation?
Hello so I've found code that plots a pixel in an SDL Screen Surface :

```
void putpixels(int x, int y, int color)
{
  unsigned int *ptr = (unsigned int*)Screen->pixels;

  int lineoffset = y * (Screen->pitch / 4 );
  ptr[lineoffset + x ] = color;

}

```

But I have no idea what its actually doing here this is my thoughts.

You make an unsigned integer to hold the unsigned int version of pixels then you make another integer to hold the line offset and it equals to multiply by pitch which is then divided by 4 ...

Now why am I dividing it by 4 and what is the pitch and why do I multiply it??

Why must I change the lineoffset and add it to the x value then equal it to colors?

I'm soo confused.. ;/

I found this function here -\> http://sol.gfxile.net/gp/ch02.html

# Answer
> 4 votes
From your link:

> Next, we're calculating the line offset. We're dividing the pitch by 4; the pitch value is in bytes, but we're moving four bytes at a time.

It should be:

```
void putpixels(int x, int y, int color)
{
  unsigned int *ptr = (unsigned int*)Screen->pixels;

  int lineoffset = y * (Screen->pitch / sizeof( unsigned int ) );
  ptr[lineoffset + x ] = color;

}

```

Always read full article before post questions.

# Answer
> 4 votes
These are all good answers but nobody explained the reason why you need to access the pixels in the way you do. The pixel data is a one dimensional array. For a 10x10 screen, the following is how you can visualize the data being set up.

```
// This is how it is actually setup
unsigned int data[100];

// This is how people envision it being setup
unsigned int data[10][10] // aka data[x][y]

```

Since it's a one dimensional array, and you have x,y coordinates you need to translate them to their actual position inside that array.

```
// This gets the y offset
int lineoffset = y * (Screen->pitch / 4 );

// Now that we know the Y offset, you can add the x position
// to access your specific pixel. Here you're assigning the
// value of a color.
ptr[lineoffset + x ] = color;

```

If you plot a few pixels on the screen and cout their x, y and then how it's being manipulated you'll see what it's doing and it will be pretty clear. If this WAS a multidimensional array, you could think of the first line as the Y for loop and the second as the X for loop:

```
for (int x = 0; x < 10; x++) { // = int lineoffset = y * (Screen->pitch / 4 );
    for (int y = 0; y < 10; y++) { // ptr[lineoffset + x ]
        data[x][y] = color; //  = color;
    }
}

```

Hope this helps :)

# Answer
> 1 votes
This site contains an Introduction to SDL Video. You'll find the information there to properly set pixels.

I also highly recommend you download the official documentation from the SDL website: http://www.libsdl.org/docs.php.

The code on the site you linked to is quite hack-ish, and not very clear.

For one thing, it's hard-coded only to work with specific resolutions at 32 bits-per-pixel color depth. The versions of `getpixel()` and `putpixel()` that are in the first link are safer (but don't forget to `SDL_LockSurface` the screen first, and `SDL_UnlockSurface` it afterwards).

You don't need to understand every detail of how these functions work in order to use SDL effectively. Basically they're providing you an interface to work directly with the pixels, without needing to worry about the low-level stuff, like memory alignment and bytes-per-pixel, etc.

But maybe you should play a little with `SDL_FillRect()` and `SDL_BlitSurface()` to get used to SDL first :)

But, here's some background info that *may* help interpreting the code:

You probably know that an `SDL_Surface` holds image data. It can also provide access to the screen. Raw access to pixels can be obtained using `SDL_Surface`'s `pixels` member, after locking the surface. You can treat `pixels` as an array of bytes.

One would assume the size of the pixels data array is just the `Width * Height * BytesPerPixel`, but it's not. It's `Pitch * Height`. The pitch is the length of one scanline. Why would the length of one line not be `Width * BytesPerPixel`?

For one thing, scanlines are aligned to a 4-byte boundary for efficiency reasons. Secondly, if you request an irregular resolution for a hardware surface, SDL will give you a different resolution, with the width set to one you requested, but using the pitch of the real video surface.

So you **must** use `pitch` when dealing with the raw pixel data.

# Answer
> 0 votes
`unsigned int *ptr = (unsigned int*)Screen->pixels;` As each pixel have 4 bytes (1 byte for each component RGBA) and also unsigned ints have 4 bytes, it is storing the image data in a unsigned int pointer. So each unsigned int is a pixel of the image.

`int lineoffset = y * (Screen->pitch / 4 );` This gets in what line does the pixel lies on. I'm not very sure what pitch is, but probably related to the size of a line. so That `pitch / 4 = linesize` this gives that `y * linesize = firstPixelofTheLine`

then it just access the pixel you want with `ptr[lineoffset + x ]` as it uses the pointer as an array and sets it to color.

Btw, if you don't understand these pixels and surfaces operations. It would be better to you to stick with something more easier, like SFML, XNA or even Gamemaker or unity.

---
Tags: sdl, pixel
---


# Question
Title: Importing an object from Blender into a scene, rotation on X axis?
This is my situation:

I save the scene with blender no export with any processing steps.

Blender has x right y up -z into the scene for the view coordinates (OpenGL) I have x right y up -z into the scene for the view coordinates (OpenGl) Bleneder has x/y plane and z up as world coordinates I have x/y plane and z up as world coordinates

I load the mesh with assimp directly from the blend file with absolutely no post processing. The object is rotated abount π/2 on the x-axis. Why?

# Answer
> 1 votes
Blender does not have "x right y up -z into the scene", as you can see in your example image, the blue arrow in Blender represents the Z axis. It's pointing up.

You need to either rotate the object in Blender before exporting, or rotate the object as part of your import process.

Blender uses a Z up, Y into the scene coordinates system. You need to change it to match the Y up, Z into the scene coordinates system of OpenGL.

---
Tags: coordinates, assimp, mesh, importing
---


# Question
Title: How can I import a Google Sketchup model with textures?
I'm using Unity 4 and trying to import a SketchUp Model into Unity and other Engines - but I can't get it to import correctly. Can anyone help me out?

# Answer
> 5 votes
A quick Google search reveals this question over on the Unity forums, the steps provided there are as follows:

> **Sketchup Standard version or Pro Version - v8 or higher:**
>
> * 1 Create/open the model with Google Sketchup
> * 2 Align the faces of the model (In the Monochrome mode--\> the bright side should be up/front)
> * 3 Export in .dae format (Default settings!)
>
> **Blender - v3.55 or higher:**
>
> * 4 Open the .dae file with Blender (If you want to see the textures - switch to texture rendering mode)
> * 5 Export to .fbx (Default settings)
>
> **Unity - v3 or higher:**
>
> * 6 Create a new folder for your models (within the Assests tab) - Recommended
> * 7 Create a Folder called "Textures" within the new folder
> * 8 Drag/Import your model textures into the textures folder
> * 9 Drag/Import your .fbx model in the new folder (same layer as the "Textures" folder)
>
> If you have done everything right, you should see a materials folder (near the textures folder) If you drag your object into the scene it should be fully textured If something is invisble - you have aligned the faces wrong (go back to step 2)
>
> PS: If you have Google Sketchup pro - you can skip the blender part

The basic idea being that you'll need to export through an intermediate format to get the textures working. Another step by step tutorial is available here, which includes images to make things easier.

---
Tags: unity, textures, models
---


# Question
Title: Why would one bind several textures to the same OpenGL texture unit?
This OpenGL documentation article says `you can bind 4` *(=several)* `textures to texture units 0, 1,` etc. This OpenGL documentation article too.
I found in this Stack Overflow answer an example of why it could be useful to use several texture units (each bound to a different texture).
However I do not understand in which case one would need to bind several textures to the same texture unit, and how one could use them then.

# Answer
> 3 votes
Binding multiple textures to the same texture unit doesn't mean using them at the same time, you can only have one texture image active at time for each unit ( and in your second link, it clearly states that his is where the spec clearly states **that you can only sample 1 of those textures.**), so why would anyone bind multiple textures?

The answer lies when you really want to render multiple objects with different shaders and/or textures, a simple scenario would be you have basic diffuse shader that will use use with to multiple objects, the shader needs the diffuse map to be bound at texture unit0.

1. Activate your shader.
2. for each object bind the needed texture using glBindTexture with TextureUnit0 still active.
3. Render your actual object.

Please note that might not be the best way for rendering multiple shaders and multiple objects, but it's a valid simple scenario when you need to bind more than one image to the same texture unit, also note that binding different textures with different dimensions to the same unit will result in the higher dimension taking the priority to be sampled (3D \> 2D \> 1D).

---
Tags: opengl, textures
---


# Question
Title: Implementing realistic sun reflection on a sea
I'm drawing a 3d rendered island which has a day / night cycle and a sun that rises and sets over water.

The sea is rendered with a fragment shader derived from this Blinn-Phong tutorial.

http://www.lighthouse3d.com/tutorials/glsl-tutorial/directional-lights-ii/

The sun's position is a represented by a point at its centre which moves over time to simulate a day / night cycle. When the point is over the horizon, the sea shader uses Blinn-phong and a normal map to produce a reflection.

I don't like the way it renders at the moment for a couple of reasons. The most serious issue is light reflection is calculated from a single point at the centre of the sun's disc so that the light flicks on or off in a totally abrupt fashion as the centre of the sun crosses the horizon. See the pictures for what I mean.

The second issue also evident in the picture is the light is a pin prick in the centre of the sun and the reflection on the sea is too focussed. It should spread from the whole disc not just a point in the centre. The Sun's disc btw is just a billboard.

What I want to happen is for the the light levels gradually increase as the sun rises and correspondingly decrease as it sets. I also want the light on the sea to spread from the whole disc rather than a pin point in the middle. This can't be a compute intensive change because the code is destined to run on mobile GPUs on android but it should still be pleasing.

I could potentially move the light point to the top of the sun to make the light appear more early and set later. However that might interfere with the light calculations in an adverse way (now the centre of the light is the top of the sun). Maybe I could start with the light point at the top and slowly move it to the centre as the sun rises (and back again as the sun sets) to counteract this problem. I could also calculate an intensity when the sun is low in the sky based on how much of the sun is showing and gradually increase the intensity to make the light stronger.

I could potentially have a cluster of light sources covering the centre, top, left, bottom and right but this increases complexity a lot and could still look weird.

Does anyone have comments on the feasibility of these ideas or have others ways I could achieve this?

# Answer
Animating the intensity and position of the light as the sun sets, so that it's roughly centered in the portion of the sun above the horizon and has an intensity proportional to the area of the sun above the horizon, sounds like an idea worth trying to me.

Another thing I'd recommend trying is making the specular power on the water lower based on distance. A problem with your image is the specular highlight forms a thin line that points at the center of the sun, where it should be roughly as wide as the sun itself. Lowering the spec power in the farther-away areas should help this. You'll have to experiment with the exact equation.
> 2 votes

# Answer
You could alternatively have the light for the sun set back like so..

apologies for my terrible drawing
> -2 votes

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