# Question
Title: Trying to access another class that is outside my Unity script but casting is failing
I am trying to reference a class that is outside my unity script using GetComponent.

```
private FlyThroughCamera camera;

void Start ()
{
    camera = GetComponent(typeof(FlyThroughCamera)) as FlyThroughCamera;
    camera.DoSomething();
}

```

Although the class exists the cast is failing and returning null.

The other class is defined as:

```
public class FlyThroughCamera : MonoBehaviour

```

Where have I gone wrong?

EDIT:

# Answer
I would caution against shadowing the `MonoBehaviour.camera` field.

I recommend the generic form of `GetComponent()`.

```
private FlyThroughCamera flyCamera;

void Start ()
{
     flyCamera = GetComponent<FlyThroughCamera>();
     flyCamera .DoSomething();
}

```
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: Exponential Variance Shadow Mapping - implementation
I use a variance shadow mapping with a "standard" light bleeding fix in my graphics engine which is based on deferred rendering.. I have a single shadow map for a directional light beacause a test scene is relatively small. Saving depth looks like this:

```
float moment1 = gl_FragCoord.z;
float moment2 = moment1 * moment1;
outColor = vec2(moment1, moment2);

```

Then I perform a separable gaussian blur on that texture.

Shadow test:

```
float Chebyshev(vec2 moments, float mean, float minVariance)
{
    float shadow = 1.0f;
    if(mean <= moments.x)
    {
        shadow = 1.0f;
        return shadow;
    }
    else
    {
        float variance = moments.y - (moments.x * moments.x);
        variance = max(variance, minVariance);
        float d = mean - moments.x;
        shadow = variance / (variance + (d * d));
        float amount = 0.3f;
        shadow =  clamp((shadow - amount) / (1.0f - amount), 0.0f, 1.0f); // standard light bleeding fix
        return shadow;
    }
}

vec4 shadowCoord = shadowMatrix * vec4(viewSpacePosition, 1.0f);
vec2 moments = texture(ShadowMap, shadowCoord.xy).xy;
float minVariance = 0.000001f;
float shadow = Chebyshev(moments, shadowCoord.z, minVariance);

```

I found a interesting technique - Exponential Variance Shadow Mapping which should provides better light bleeding fix. Here is saving depth for that technique:

```
float positiveExponent = 40.0f;
float negativeExponent = 5.0f
float depth = gl_FragCoord.z;
vec2 exponents = vec2(positiveExponent, negativeExponent);
depth = 2.0f * depth - 1.0f;
float pos = exp(exponents.x * depth);
float neg = -exp(-exponents.y * depth);
vec2 warpDepth = (pos, neg);
outColor = vec4(warpDepth, warpDepth * warpDepth);

```

How to implement a shadow test for that technique ? Here is my attempt:

```
float positiveExponent = 40.0f;
float negativeExponent = 5.0f;
vec2 exponents = vec2(positiveExponent, negativeExponent);

vec2 warpDepth(float depth)
{
    depth = 2.0f * depth - 1.0f;
    float pos = exp(exponents.x * depth);
    float neg = -exp(-exponents.y * depth);
    vec2 wDepth = vec2(pos, neg);
    return wDepth;
}

float Chebyshev(vec2 moments, float mean, float minVariance)
{
    float shadow = 1.0f;
    if(mean <= moments.x)
    {
        shadow = 1.0f;
        return shadow;
    }
    else
    {
        float variance = moments.y - (moments.x * moments.x);
        variance = max(variance, minVariance);
        float d = mean - moments.x;
        shadow = variance / (variance + (d * d));
        return shadow;
    }
}

vec4 shadowCoord = shadowMatrix * vec4(viewSpacePosition, 1.0f);
vec4 moments = texture(ShadowMap, shadowCoord.xy).xyzw;
vec2 posMoments = vec2(moments.x, moments.z);
vec2 negMoments = vec2(moments.y, moments.w);
vec2 wDepth = warpDepth(shadowCoord.z);
//float minVariance = 0.000001f;
//Edit
vec2 depthScale = 0.0001f * exponents * wDepth;
vec2 minVariance = depthScale * depthScale;
float posResult = Chebyshev(posMoments, wDepth.x, minVariance.x);
float negResult = Chebyshev(negMoments, wDepth.y, minVariance.y);
shadow = min(posResult, negResult);

```

Unfortunately it doesn't remove light bleeding. Did I do something wrong ? Maybe I should calculate two different minVariance based on the positive and negative exponents ?

**Edit1:** Calculating minVariance this way:

```
vec2 depthScale = 0.0001f * exponents * wDepth;
vec2 minVariance = depthScale * depthScale;
float posResult = Chebyshev(posMoments, wDepth.x, minVariance.x);
float negResult = Chebyshev(negMoments, wDepth.y, minVariance.y);

```

gives better results but light bleeding is still quite visible.

**Edit2:** Light bleeding: EVSM with minVariance which is calculated as above gives better result than VSM without standard light bleeding fix, but to get the best result I also use standard light bleeding fix with EVSM. A light bleeding fix is performed in Chebyshev function but maybe I should add it after following calculation: shadow = min(posResult, negResult) ?

EVSM causes small artifacts on the illuminated side of the objects so I add some glPolygonOffset when saving EVSM depth.

# Answer
> 5 votes
Variance shadow mapping, plainly put, just suffers from these light bleeding issues.

I personally prefer to implement ESM (check out page 257 of ShaderX6) as the memory pressure is half of the VSM map and the artifacts are much less abrasive to me: (The very beginning of the shadow is a bit too bright.)

With this said, here is a (rather old) PDF full of great techniques to get you thinking. (or just to show you the algorithm if you don't have ShaderX6) http://developer.download.nvidia.com/presentations/2008/GDC/GDC08\_SoftShadowMapping.pdf

In my current engine, I have a hybrid which is basically ESM, but uses the 2-moment (or higher) shadow map to compute the variance and reduce the ESM artifacts at the places where the occluder is too close to the receiver.

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


title: Implementing fog of war on HTML5 canvas

text:
# Question
Title: Implementing fog of war on HTML5 canvas
I have been wrestling with creating fog of war for a while now. I actually did create it, but I consider the implementation too resource-heavy to be usefull.

For initial information: I use createjs / easeljs framework / library for the project and the fog of war is now implemented so, that there is a layer with the "fogged" image and data of the map on bottom and on top of that is the non-fogged / clear layer of the map. In the clear layer I only show certain parts by filtering the layer with shapes and the rest is invisible. So only the areas that are visible are shown.

Also note that even the fogged parts are partially visible, e.g. the whole terrain of the map is always visible beneath the fog of war.

This creates 2 different layers with the same information of the map, instead of creating a separate fog of war layer, that would only contain the fog and be filtered to show the non-fogged parts.

I have been unable to make this work so far.

So basically I can now use filters to show certain parts of a layer, but not to make parts of it have an alpha value. E.g. If I have a fog-layer (that contains the fog) and want to show it except certain circular parts (which would reveal the map below, with alpha = 0), how is that achieved? Now I can only show certain parts of a layer with filtering, instead of hiding them / making the have alpha or reverse the filtering.

# Answer
The problem was solved by using another canvas and compositeOperation = "destination-out".
> 0 votes

---
Tags: javascript, html5, html-canvas, fog-of-war
---


# Question
Title: Normal map causing certain faces to get shaded
I added a normal map to a MR arch & design material in Max 2012. I have a specular in the reflection color slot and a diffuse in the diffuse slot. As i increase the intensity of the normal map i certain faces get darker and they get really "obvious". Last time i was fiddling with this the exact same thing happened which made me quit normal maps and all. Some UV's are overlapping and the normal map is made with the Nvidia photoshop plugin. My scene just has a daylight system with a MR sun and MR sky.

Does anyone have an idea what is causing this?

As you can see the face gets shadowed as a whole. The face next to it has the same problem on the opposite corner you see the same effect but much less hard.

# Answer
The face normal has been flipped on the UV layout. Selecting the face with the issue and mirroring it should solve it.
> 2 votes

---
Tags: 3d, textures, 3dsmax, normal-mapping
---


# Question
Title: How would you draw a tile map with perspective?
I want the maps in the game I'm working (in Java) to be draw with perspective just to sugar coat it, but I'm not sure how that can be done. If anyone has an article about the math behind it or something similar, that would be greatly appreciated.

Something looking similar to the plain shown on this image found on Google Images:

(not my image, I take no credit)

**EDIT:** The game is indented to be in 2D, I can draw the map into BufferedImage and then warp it somehow to make it perspective. Just a thought. The real question is, how would the image of the map be warped to to have the angled effect? (Please note, I am trying to avoid using 3D by warping the plain to simulate an angled view)

# Answer
> 3 votes
I wrote some code to explain how this could be done in software:

```
    evaluatePixel()
    {
        const float2 ofst    = float2(0.0, 0.0);
        const float2 imgSize = float2(2050.0, 1700.0); // image size
        const float M = 2.2;
        const float MDZ = 1.0 + 2.0 / (M - 1.0);
        const float H = 1.0 + MDZ;

        float2 c2D = float2(2.0, - 2.0) * (outCoord() / imgSize) + float2(- 1.0, 1.0);

        float dz = 1.0 + (1.0 + c2D.y) / (M - c2D.y);

        float2 c3D = float2(c2D.x, c2D.y + 1.0) * float2(dz, dz);
        c3D.x /= 1.7 * MDZ;
        c3D.y = c3D.y / H - 0.5;

        if(outCoord().x < imgSize.x && outCoord().y < imgSize.y){
            dst = sampleLinear(src, (c3D + float2(0.5, 0.5)) * imgSize + ofst);
        } else{
            dst.rgb = float3(0.0, 0.0, 0.0);
            dst.a = 0.0;
        }

    }

```

This is what it looks like:

And this is what it looked like before the effect:

The image was taken from this page:

http://www.lughertexture.com/tiles-new-hires-textures/modern-and-vintage-tiles-textures/stone-tiles-light-762

Older answer: Look at what they did in this game: http://www.newgrounds.com/portal/view/631599

The trees' leaves are layered in different distances.

If you wish to save time, you should probably use your existing map as a texture for a 2-d plain and position your camera in the desired angle. You could take a screenshot in-game and play around in Blender to figure out the desired angle.

Since you wish to explore this for deductive purposes and for interest, I will point out how it's done.

Imagine the screen (display) plain. You have a matrix (2d array) of pixels on the display. All those pixels originate from tiles in the tile map which is a 2d-array of blocks of pixels. We could generalize this to seeing the tile map as a 2d-array of pixels.

Now, we simply need a function that takes `x, y` in the display and pulls out the correct `x', y'` from the pixel array that is the tile map. That is a form of rendering.

The function obviously depends on the placement (height, offset) and angle of the camera.

Imagine the display is a window and the tile map is beyond that window and you only have one eye and you are tracing a line between that eye and the tiles. Where the line hits the display, that is where the color from the tile map goes. I believe this is called ray-tracing.

In simple terms, to get you started, lets say the tile map is laying flat and your eye is a camera that is 1000 units from the monitor and 500 units above the plain. We will also say that the pixels closest to us are in `y = 0` and that the center line on the screen is in `x = 0`.

Now we have a line and we could use math to figure out where is headed on the tile map. In your case, a simple plain, the mat is also simple. If the eye is looking through the center of the monitor, any pixel above that will not hit the plain if the camera is pointing straight forward. Pixels bellow that point we can calculate like this:

We are assuming each pixel is the size of one unit and that we are `d = 1000` (distance) units away from the monitor right now and 500 units above the tile-map plain. If we are looking at a pixel that is 100 units bellow the center, the ratio is `100 / 1000 = 0.1`. To reach the tile-map plain it will need to go down another `500 - 100 = 400` units so it will required another `400 / 0.1 = 4000` steps on the `y` axis. We could adjust the constants to suit the game design and resolution. The same is being done with the x offset. If you wish to give the camera an angle, it is entirely possible with a tiny bit of additional complication.

To do the rendering fast though, you would probably need to rely on an existing library.

# Answer
> 4 votes
If you are looking to use any 3D objects (lets say a chessboard with 3d pieces), you could make a series of quads, then manipulate the camera's position and target to get the angle/perspective that you want.

# Answer
> 0 votes
Diablo2 did this just with 2D, look at some screenshots and you see the foreground(bottom) tiles are bigger then the background(top) tile. I asked a question about this in the past the answer was basically that it is just too much hassle and hacking to get things right. It makes much more sense if we convert the 2D tile to a 3D scene.

You need to look for bill-boarding. Basically you need to make each tile a "3D" flat plane/billboard. Render them together and just setup a perspective camera. This way you have the benefit of both 2D and 3D worlds. This does however require you to dig a bit into 3D graphics and shading like (HLSL).

---
Tags: java, tilemap, perspective
---


# Question
Title: How can I calculate a terrain's normals?
Im trying to implement basic lighting in Opengl 3+ (a sun) with this tutorial :

http://www.mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=11

Im building a basic terrain and its working well. Now im trying to add normals, and I think its not working well :

Terrain in wireframe

As you can see I dont think my normals are good.

This is how I get them :

```
for(x = 0; x < this.m_size.width - 1 ; x++)
    {
        for(y = 0; y < this.m_size.height - 1 ; y++)
        {
            immutable uint indice1 = y * this.m_size.width + x;
            immutable uint indice2 = y * this.m_size.width + (x + 1);
            immutable uint indice3 = (y + 1) * this.m_size.width + x;
            immutable uint indice4 = (y + 1) * this.m_size.width + x;
            immutable uint indice5 = y * this.m_size.width + (x + 1);
            immutable uint indice6 = (y + 1) * this.m_size.width + (x + 1);

            Vector3 v1 = vertexes[indice3] - vertexes[indice1];
            Vector3 v2 = vertexes[indice2] - vertexes[indice1];
            Vector3 normal = v1.cross(v2);
            normal.normalize();

            normals[indice1] = normal;

            indices ~= [indice1,
                        indice2,
                        indice3,
                        indice4,
                        indice5,
                        indice6];
        }
    }

```

I use this basic shader : http://ogldev.atspace.co.uk/www/tutorial18/tutorial18.html or in the link I posted at the top.

Thanks.

# Answer
By looking at your picture your problem seems that you need to smooth(average) your normals. That is when a vertex is shared by multiple triangles and yet has one normal you have two options to deal with this problem:

* Smooth edges: You calculate the normal of each vertex for each adjacent triangle and then average them.
* Hard edges: You duplicate each vertex, especially at the edges where the normal greatly varies between triangles. It practically has 3 different normals (though it's not actually) but then you have the effect of hard edges.

I provided the full code for smooth normals here. And more detailed explanation for this issue here.
> 5 votes

---
Tags: opengl, lighting, terrain, normals
---


# Question
Title: GLSL blur shader algorithm results in a lumpy blur?
I'm writing a Gaussian blur shader and it's coming along pretty well. However, when I run it on a circle, the result is lumpy.

I'm using a simple nested for loop to create the blur. Here's the code in it's current form:

```
int samples = 10;
int sampledist = 1;
float rt_h = 720; // render target height
float rt_w = 1280; // render target height

vec4 effect(vec4 col, Image tex, vec2 texcoord, vec2 screencoord)
{
   vec3 final = vec3(1.0, 0.0, 0.0);
   final = Texel(tex, texcoord.xy).rgb;
   for (int i=-samples; i<samples; i++)
   {
      for (int j=-samples; j<samples; j++)
      {
         final += Texel(tex, texcoord.xy + vec2(i*sampledist, j*sampledist)/vec2(rt_w, rt_h)).rgb * .01;
      }
    }
    return vec4(final, 1.0);
}

```

*(Note: I'm using a variation of the regular GLSL language for Love2D, so the above code isn't completely valid GLSL shader code)*

What is wrong with my algorithm?

# Answer
> 6 votes
There are two problems here:

1. You're including the center texel twice in the filter. You first initialize `final` as

```
final = Texel(tex, texcoord.xy).rgb;

```

but the same texel also gets sampled in the loop when i and j are both zero. That accounts for why you can still see the image of the unblurred circle mixed in with the blur.
2. You're not doing a Gaussian blur. Since you give every sample the same weight, .01, you're just doing a box blur. This accounts for why the blur is "lumpy" as you put it - the results look different when blurring the part of the circle that's aligned with the box, versus the part of the circle that's at a 45-degree angle to the box. To do a Gaussian blur you would need to calculate the weights using a Gaussian distribution, like

```
weight = exp(-(i*i + j*j) / (2.0 * sigma*sigma))

```

where sigma is the standard deviation (usually set to 1/3 to 1/4 of the filter radius in pixels). In practice this is usually precomputed and the values are hardcoded into the shader, since evaluating that formula in real-time is rather expensive. You have to normalize the total weight to 1.0, as well.

For completeness, I'll also note that you're doing the blur in the non-separable 2D fashion, looping over both x and y inside the pixel shader. That works, but it's quite slow, especially for larger filters. For separable filters (which box and Gaussian both are, but most other shapes are not) you can get a huge speedup by doing the filter in two passes: a 1D filter on each row, then take the result of that and run another 1D filter on each column.

---
Tags: glsl, fragment-shader
---


# Question
Title: Client-side prediction and interpolation
Although my game uses a peer-to-peer model, I've still taken the approach of assigning each player to be a partial authority. What I mean by this is that each player acts as the "server" for a number of objects, and all the other players are "clients" for those objects.

It also uses a fixed update interval and variable render interval. I'm considering a 50Hz update frequency, so the rendered time lags behind the current time by 20ms in order to guarantee two states to interpolate between.

When a client recieves authoritative state information from the server, it comes with the timestamp of when it was sent. Because all the players use a synchronized clock, the client can correctly place the state along its "update timeline", the state history of which is stored for up to 100ms back.

However, in order to hide latency, each client also predicts the behaviour of all objects in the vicinity, regardless of whether or not they are the authority.

The difficulty I'm having is figuring out how to correct errors on the client side and stay synchronized with the server state, when server information for a specific object will be coming far less often than updates happen. What is a good way to smoothly correct current information with information from the past after several prediction steps have been done on estimated information?

# Answer
You don't need to correct the errors on the client right away. If you interpolate the current client info with the incoming server info, the client info will converge to the server info in the next few frames. Since you are expecting the server info arrival to be less granular than the client update, when some info arrive at the client it will have enough time to converge to the expected state. I think you will have to experiment a little bit with the interpolation parameters to find a good guess for the number of steps until convergence.
> 1 votes

---
Tags: networking, client-server, peer-to-peer, latency
---


# Question
Title: How can I notify my AI systems that a target has died?
I am currently building a game focusing on AI for my university and this is my first time writing such a complex AI system.

Naturally, I ran into a little logic problem: In the game, the AI uses a hierarchical finite state machine and certain states have a pointer to a character as target for their logic (e.g. attack state has a target character to attack). Additionally, multiple characters might target this one character at the same time.

Now if that character dies, how should I go about telling the AI that the target is no longer valid? I can't just delete the character object, since that would result in invalid pointers and access violations, of course.

I thought about using an event system, where the characters are notified about the death, but how would I know, when all characters removed their reference, changed their state etc. and I could finally delete the object?

Would I have to resort to using smart pointers here? Or is there another good solution?

# Answer
> 4 votes
Instead of having the FSM pointing to the character instance straight on, you could have it pointing to **a unique ID** representing that character. The characters would be registered in a singleton manager class.

When the character dies, you simply mark it as deceased (in the singleton manager). Later on, when (and if) the FSM reaches a state in which it should interact with that character, a simple query to the manager will be enough for the FSM to identify that it has died and the character can be ignored (or that more appropriate actions shall be taken).

Also, if you have multiple NPCs targeting the same character, you might have to handle the update of the character's deceased state in a thread safe fashion.

# Answer
> 2 votes
You could use the observer pattern.

The observer-pattern in a nutshell:

* There are Observers (like your AI enemies) and Observables (the objects they target)
* Each Observer can `register` itself to one or more Observables
* Each Observable keeps a list of those Observers who registred on it
* When an important event happens in an Observable (like its death or its deletion through the destructor), it notifies each of the Observers in its list by calling a `notify`-method on them.
* When an Observer is either no longer interested in an Observable or ceases to exist itself, it `unregister`s itself from all Observables it observes so they don't try to notify an object which no longer exists or doesn't care anymore.

# Answer
> -1 votes
Ii think there is a point missed here, the state machine should not assume the character is alive. Characters should probably have a bit (bool) stating if they are alive. The dead could be placed in a pool(once they die) and should not be freed from the heap and could instead be recycled. The FSM needs to check if the character is alive and still meets this and other properties required for the desired action. if not, it needs to do a look-up for another character that does meet these properties.

You can also use a counter to see how many pointers point to that character if you wish to avoid smart pointers.

There is no need to "spare" memory by freeing every dead if performance is important.

---
Tags: c++, ai, fsm
---


# Question
Title: How can I programatically generate sprite instances in Unity?
I want to create a block-based puzzle game that generates blocks as they are required, however I cannot seem to find any good information on how to do something like this using Unity's new sprite system.

Ideally the following would occur:

* Generate a random number to determine the type of block
* Create a sprite object of correct block type
* Display block on screen

I currently have the following:

```
using UnityEngine;
using System.Collections;

public class Block : MonoBehaviour {

    public SpriteRenderer blockSprite;
    int row;
    int column;

    // Use this for initialization
    void Start ()
    {
        row = 0;
        column = 0;
    }

    // Update is called once per frame
    void Update ()
    {
        // gravity check
    }

    public void GenerateNewBlock()
    {
        int randNumber = Random.Range(0, System.Enum.GetNames(typeof(BlockType)).Length);
        Sprite sprite = new Sprite();

        blockSprite = gameObject.GetComponent<SpriteRenderer>();

        switch (randNumber)
        {
        case 0:
            sprite = Sprite.Create(AssetsLoader.Instance.BlockSprites[BlockType.Water], new Rect (0, 0, 100, 100), new Vector2(0, 0), 100.0f);
            break;
        case 1:
            sprite = Sprite.Create(AssetsLoader.Instance.BlockSprites[BlockType.Fire], new Rect (0, 0, 100, 100), new Vector2(0, 0), 100.0f);
            break;
        }
    }
}

public enum BlockType
{
    Water,
    Fire
}

```

And an assets loader Singleton class to load in the textures once into memory

```
using UnityEngine;
using System.Collections.Generic;

public class AssetsLoader : MonoBehaviour
{
    // instance variable to prevent multiple instances of this class
    private static AssetsLoader instance;

    // variables we want to retain state
    public Dictionary<BlockType, Texture2D> BlockSprites;

    // empty private constructor
    private AssetsLoader() {}

    // Property that holds the instance
    public static AssetsLoader Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new AssetsLoader();
            }

            return instance;
        }
    }

    // Use this for initialization
    void Start ()
    {
        BlockSprites = new Dictionary<BlockType, Sprite>();

        Sprite newSprite;

        newSprite = Resources.Load("Sprites/water block") as Texture2D;
        BlockSprites.Add(BlockType.Water, newSprite);

        newSprite = Resources.Load("Sprites/fire block") as Texture2D;
        BlockSprites.Add(BlockType.Fire, newSprite);
    }
}

```

Can someone please help me understand what needs to be done to create block objects in my scene. Ideally I would only use `Sprite` objects but I think I might need to load the assets in as `Texture`s in order to get them to display.

# Answer
> 5 votes
I would use prefabs for a situation like this, you could use then to fill your dictionary like so:

```
public class AssetsLoader : MonoBehaviour
{
    public GameObject[] blockPrefabs;
    public Dictionary<String, Texture2D> blockTypes;

// ...

   void Start ()
   {
       blockTypes = new Dictionary<String, Sprite>();

       foreach(GameObject prefab in blockPrefabs) {
           blockTypes[prefab.name] = prefab;
       }
   }
}

```

This will expose the `blockPrefabs` array so you can drop any number of prefabs into it using the Inspector. Use meaningful names and they can function as keys for the dictionary.

You can then spawn them in your scene using `Instantiate`.

**Edit:** Another approach that would allow for enum based reference would be:

```
public enum BlockType
{
    Water = 0,
    Fire = 1
}

public class AssetsLoader : MonoBehaviour
{
    [SerializeField]
    private GameObject[] blockPrefabs;

    // ...

    public GameObject BlockSprites(BlockType blockType) {
        return blockPrefabs[(int)blockType];
    }
}

```

Here there would be a requirement to keep the contents of the array `blockPrefabs` and the values of the enum `BlockType` in sync.

---
Tags: 2d, unity, sprites
---


# Question
Title: How can I create a cross-fade between two quads?
I have two quads, and I would like to have each one of them on the screen for 5 seconds, then fade to the next one. How could this be done?

My code:

```
package net.makerimages.Unacrawl.stateSys;

import net.makerimages.Unacrawl.graphics.TextureManager;

import static org.lwjgl.opengl.GL11.*;
/**
 * Created by Makerimages on 12.01.14.
 */
public class LogoState extends GameState
{
@Override
public void render() {
    TextureManager.bigLogo.bind();

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex2f(0, 0);
    glTexCoord2f(1, 0);
    glVertex2f(0 + TextureManager.bigLogo.getTextureWidth(), 0);
    glTexCoord2f(1, 1);
    glVertex2f(0 + TextureManager.bigLogo.getTextureWidth(), 0 + TextureManager.bigLogo.getTextureHeight());
    glTexCoord2f(0, 1);
    glVertex2f(0, 0 + TextureManager.bigLogo.getTextureHeight());
    glEnd();

    TextureManager.makerLogo.bind();

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex2f(0, 0);
    glTexCoord2f(1, 0);
    glVertex2f(0 + TextureManager.makerLogo.getTextureWidth(), 0);
    glTexCoord2f(1, 1);
    glVertex2f(0 + TextureManager.makerLogo.getTextureWidth(), 0 + TextureManager.makerLogo.getTextureHeight());
    glTexCoord2f(0, 1);
    glVertex2f(0, 0 + TextureManager.makerLogo.getTextureHeight());
    glEnd();
}
}

```

# Answer
> 1 votes
You need to set the alpha of the texture to have it fade. You also need a method of timing in order for it to be able to fade (use delta, or the amount of milliseconds since the last update happend, http://lwjgl.org/wiki/index.php?title=LWJGL\_Basics\_4\_%28Timing%29).

I re-wrote the class with it implemented:

```
package net.makerimages.Unacrawl.stateSys;

import net.makerimages.Unacrawl.graphics.TextureManager;

import static org.lwjgl.opengl.GL11.*;
/**
 * Created by Makerimages on 12.01.14.
  */
public class LogoState extends GameState
{
    @Override
    public void render(int delta) {
    int time = 0;
    time += delta;

    //Enable transparency, glDisable(GL_BLEND) will disable it, which is recommened if you're not going to be using it. You also should draw all transparent objects after all opaque objects.
    glEnable(GL_BLEND);
    glBlendFun(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    if (time < 5000) // The first 5 seconds
    {
        float alpha = 1 - ((1 / 5000) * time); //Gets a number between 0.0 and 1.0 depending on how close it is to 5000 and inverts it from 1 to 0, to 0 to 1(0 being completely white).
        glColor4f(1, 1, 1, alpha); //Set the color to white (default) and adjust the alpha.

        TextureManager.bigLogo.bind();

        glBegin(GL_QUADS);
        glTexCoord2f(0, 0);
        glVertex2f(0, 0);
        glTexCoord2f(1, 0);
        glVertex2f(0 + TextureManager.bigLogo.getTextureWidth(), 0);
        glTexCoord2f(1, 1);
        glVertex2f(0 + TextureManager.bigLogo.getTextureWidth(), 0 + TextureManager.bigLogo.getTextureHeight());
        glTexCoord2f(0, 1);
        glVertex2f(0, 0 + TextureManager.bigLogo.getTextureHeight());
        glEnd();
    }
    else if (time < 10000 && time > 5000) //Between the 5 second mark to the 10 second mark
    {
        float alpha = 1 - ((1 / 5000) * (time - 5000)); //Same as last time but it subtracts 5000 from the time (since 5 seconds have passed) so the algorithm works the same.
        glColor4f(1, 1, 1, alpha); //Set the color to white (default) and adjust the alpha.

        TextureManager.makerLogo.bind();

        glBegin(GL_QUADS);
        glTexCoord2f(0, 0);
        glVertex2f(0, 0);
        glTexCoord2f(1, 0);
        glVertex2f(0 + TextureManager.makerLogo.getTextureWidth(), 0);
        glTexCoord2f(1, 1);
        glVertex2f(0 + TextureManager.makerLogo.getTextureWidth(), 0 + TextureManager.makerLogo.getTextureHeight());
        glTexCoord2f(0, 1);
        glVertex2f(0, 0 + TextureManager.makerLogo.getTextureHeight());
        glEnd();
  }
  else // It's past 10 seconds at this point.
    doSomething();
}
}

```

---
Tags: java, lwjgl
---


# Question
Title: How can I move an object towards another along a straight line
How can I move an object (like a cube) towards another object?

Let's say that we have a red cube in the center of a floor, and a blue cube in another location, there aren't objects between this two, so the movement is along a line.

How can I move the blue cube towards the red one?

# Answer
A basic solution to this problem, given the two positions of the objects (`A` and `B`):

* Compute the normalized direction vector from `A` to `B`: `v = normalize(B - A)`.
* Every game logic update, add that vector `v` (scaled by the desired object speed) to the position of `A`: `A += v * speed`.
* Stop doing this when `A` is within some desired tolerance of `B`.

A simple implementation of this might involve storing "movement destination" point with each object, representing where it is trying to get each frame. Apply the above logic every frame in the object's update method (pseudocode):

```
if (target is assigned && !position.isWithinToleranceOf(target)) {
  v = normalize(target - position)
  position += speed * elapsedTime * v;
}

```

A more involved solution would involve abstracting out the movement destination and handling into a more generic "orders" object which can be associated with an in-game entity, allowing you to build "movement order" objects and "attack order objects," all of which could be assigned to various in-game objects.
> 4 votes

# Answer
I'm assuming you're using 2d vectors to accomplish this. If you are, it's very simple: Just give your moving object a velocity vector that points from its position towards the other object's position. It's easier to give it unit length, that way you can modify speed later on. Example:

```
this.velocity = other.position - this.position;
this.velocity *= 1/this.velocity.norm;

```
> 0 votes

---
Tags: java, movement, jmonkeyengine
---


# Question
Title: How can I determine the card possibilities for a game of Scopa?
In the game of Scopa, at the player's turn, there could be anywhere from 0 to 39 cards on the table (although 10+ is an extreme). I'm trying to figure out the best way to figure out possibilities for the player to pick up cards off the table. Also, in Scopa, you can only pickup cards off the table if there's 1+ cards on the table that add to equal the value of the card in your hand.

Currently, I've got something close to:

```
for (Card card : cardsOnTable) {
    for (Card card2 : cardsOnTable) {
        if (card2 != card) {
           if (card.getValue() + card2.getValue() == cardInHandValue) {
              //Add to list of possibilities.
           }
        }
    }
}

```

But that only works out while checking the table for possibilities of two cards. The problem is that there could be possibilities of 3, 4, etc. cards, and that detecting how many cards it needs to check (how many nested loops) doesn't seem possible. What method could I go about using to check for card possibilities?

# Answer
I'd suggest you change your approach. Instead of attempting to validate every possible set, let the player choose a bunch of cards to attempt to pick up, and then validate their chosen set.

Otherwise, you're looking at evaluating more than 2×10^46 combinations of cards
> 1 votes

# Answer
I agree with Jordaan's approach for the human player of your game...validate only when they've made a selection. If you're trying to make a selection for a computer player (or make a hint for the human player), you're going to have to generate some alternatives.
Since the goal is to find a set of cards from the table that have an equal value than the cards in the players hand, I suggest first sorting the table cards from high to low.
Scan the list to see if a single card equals the hand total (you can stop the loop once the table card is less than the hand total).
Next, look at the pairs by evaluating tableCard\[0\]+tableCard\[1\] through tableCard\[0\]+tableCard\[n-1\] Again, you can stop when the total is less than the hand's total! Move to tableCard\[1\] with tableCard\[2\] through tableCard\[n-1\], etc. to finish the pairs.
After all pairs, go to triples (the first group of triples would go from tableCard\[0\]+tableCard\[1\]+tableCard\[2\] through tableCard\[0\]+tableCard\[1\]+tableCard\[n-1\], the second group of triples would go from tableCard\[1\]+tableCard\[2\]+tableCard\[3\] through tableCard\[1\]+tableCard\[2\]+tableCard\[n-1\], etc.

Work a couple (relatively) small cases out by hand and you'll see the pattern for the loops.

You can stop as soon as you find a match. If you want to evaluate several legal moves, you could generate some alternatives and use a heuristic to pick the best move. For example, it may be in the "smart computer" player's best interest to take as many cards off of the table as possible.

I would generate the alternatives in a thread and set a time limit to come up with an answer. You could use several threads in parallel to generate different possibilities

Good Luck amb
> 0 votes

# Answer
In fact the maximum number of cards on a scopa table is 13. And by So you could list all possibilities rapidely. Here's a sketch:

```
class ScopaSum{
  int total;
  list<Card> cards;
  public void addCard(Card card){
    total+card.value;
    cards.add(card);
  }
}

public List<List<Cards>> getAllPossibilities(Card playedCard){
  List<ScopaSum> sums = new List<>();
  for(Card card : cardsOnTable){
    if(card.value > playedCard.value)
      continue;
    List<ScopaSum> allNewSums = new List<>();
    for(ScopaSum sum : sums){
      if(sum.value+card.value <= playedCard.value){
        ScopaSum newSum = new ScopaSum(sum);
        newSum.add(card);
        allNewSums.add(newSum);
      }
    }
    ScopaSum newSum = new ScopaSum();
    newSum.add(card);
    allNewSums.add(newSum);
    sums.addAll(allNewSums);
  }

List<List<Cards>> allPossibleTake = new List<>();
for (ScopaSum sum : sums){
  if(sum == playedCard.value){
    allPossibleTake.add(sum.cards);
  }
}
return allPossibleTake;
}

```

Then you can certainly enhance a bit this code for a complete hand (3 cards) and add a weight to gold cards to pick up more interesting cards. And note that if the table contains a card with the same value, the player can only take a such card. (I've skipped this part on the algorithm)
> 0 votes

---
Tags: card-game
---


title: Spherical harmonics lighting evaluation

text:
# Question
Title: Spherical harmonics lighting evaluation
The following is taken from my current understanding of spherical harmonics. There may be errors involved which solve my question if they're resolved, so please notify me if I misunderstood something.

Evaluating reflected diffuse indirect illumination at a surface point is done by computing the integral (simplified rendering equation) in the last line of

(stolen from here).

An important property of functions in SH representation is that the integral in the last line boils down to a dot product between the vectors containing the SH coefficients for projected functions L(x,omega\_i) and max(N\_x dot omega\_i,0).

For example, for each surface point in our target image that we wish to compute indirect illumination on, L(x,omega\_i) is available in a precomputed vector of a 4 elements (for 2 bands SH approximation) containing spherical harmonics coefficients. It's not really important where it came from, just that it's available at this point.

From my understanding, to actually evaluate the lighting at a surface point \[x\] is to project the function max(N\_x dot omega\_i,0) into spherical harmonics, and dot it with the coefficient vector of the incoming radiance (and then, multiply it by the stuff in front of the integral, surface albedo / pi). The first 4 coefficients (2 bands) for max(N\_x dot omega\_i,0) projected into SH basis are known, they are:

c\_0 = 0.88622692545...

c\_1 = -1.02332670795 * n\_y

c\_2 = 1.02332670795 * n\_z

c\_3 = -1.02332670795 * n\_x

So the irradiance at that surface point with normal n would just be

E = dot(L\_sh,n\_sh)

where L\_sh is the coefficient vector for the incoming radiance, and n\_sh the coefficient vector for the cosine lobe that we just calculated. Specifically, L\_sh is the same max(...) function projected into SH basis \[with the normal from which the light originated\], just scaled a little by the color its transporting.

The above actually looks fine and seems to produce somewhat correct lighting (hard to judge without ground truth reference). What's confusing me now, is that I've come across several sources (for example here, page 17), which, in the final step, when evaluating the lighting, don't actually use the coefficients from above to project max(N\_x dot omega\_i,0) into SH basis, but instead calculate n\_sh as

n\_sh0 = 0.282094792f

n\_sh1 = -0.488602512f * -n\_y

n\_sh2 = 0.488602512f * -n\_z

n\_sh3 = -0.488602512f * -n\_x

These four coefficients are actually just the spherical harmonics basis function coefficients parametrized in cartesian coordinates (here they are for spherical coordinates).

What's up with that? Why aren't they projecting the max(...) function into SH basis instead? Am I misunderstanding something? Unfortunately, the usual sources (gritty details and stupid SH tricks) don't seem to go into details of this either.

# Answer
It could simply be a normalization difference. The c\_0 and n\_sh0 you posted differ by a factor of pi, and the coefficients in the other three values differ by a factor of 2/3 pi. That makes me think it's a matter of whether 1/pi is included in the Lambert BRDF or not. Aside from that and a sign change (which could also be down to a different convention about the way something is defined), the two sets of equations are identical.
> 1 votes

---
Tags: spherical-harmonics
---


title: Simple 2d tile based lighting in xna

text:
# Question
Title: Simple 2d tile based lighting in xna
I am currently trying to implement simple lighting into my game. My world is represented in a 2d array of numbers, each number being a certain tile. I am changing the color parameter in the spritebatch.Draw method to dim the tiles, and that is working quite well for me(I don't know how to use shaders).Each tile can have a light level from 0 to 5, and depending on its level it will be brighter/darker. The problem I have is that I used this code to simulate lighting:

```
public void Update()
    {
        foreach (NonCollisionTiles tile in nonCollisionTiles)
        {
            foreach (NonCollisionTiles otherTile in nonCollisionTiles)
            {
                if (otherTile.Rectangle.X  == tile.Rectangle.X && (otherTile.Rectangle.Y / size == tile.Rectangle.Y - 1 || otherTile.Rectangle.Y / size == tile.Rectangle.Y + 1))
                {
                    if (tile.Light < otherTile.Light)
                    {
                        tile.Light = otherTile.Light - 1;
                    }
                }
                else if (otherTile.Rectangle.X / size == tile.Rectangle.Y && (otherTile.Rectangle.X / size == tile.Rectangle.X - 1 || otherTile.Rectangle.Y / size == tile.Rectangle.X + 1))
                {
                    if (tile.Light < otherTile.Light)
                    {
                        tile.Light = otherTile.Light - 1;
                    }
                }
            }
        }
    }

```

But I'm not sure if it works or not and it lowers my FPS to 1. I have no idea as to how I can implement my lighting system. Essentially, I want it to look like a torch in Minecraft, but in 2d. Here is the code for my tiles:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace Tile_Map
{
class Tiles
{
    protected Texture2D texture;
    protected int light = 1;
    public int Light
    {
        get { return light; }
        set
        {
            light = value;
        }
    }
    protected Color color;
    private Rectangle rectangle;
    public Rectangle Rectangle
    {
        get { return rectangle; }
        protected set { rectangle = value; }
    }
    private static ContentManager content;
    public static ContentManager Content
    {
        protected get { return content; }
        set { content = value; }
    }

    public void Update()
    {
        color = new Color(light*51,light*51,light*51);
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, rectangle, null, color, 0, Vector2.Zero,SpriteEffects.None,0f);
    }
 }

class CollisionTiles : Tiles
{
    public CollisionTiles(int i, Rectangle newRectangle)
    {
        texture = Content.Load<Texture2D>(@"Images\Tile" + i);
        this.Rectangle = newRectangle;
    }
}
class NonCollisionTiles : Tiles
{
    public NonCollisionTiles(int i, Rectangle newRectangle)
    {
        texture = Content.Load<Texture2D>(@"Images\Tile" + i);
        this.Rectangle = newRectangle;
    }
}
}

```

This is what I am trying to do:

Any help is appreciated!

# Answer
> 1 votes
The code is currently looping over all the tiles twice. On a 10x10 map, it calls the code inside the loops 10,000 times. That's already a very large number, and that's just on a small map. Most of these calls will be useless, as it is also checking tiles that are far away from each other.

**Store things appropriately**

Your tiles will always be next to the same neighbours, so why not store them that way? By using a multidimensional array, you can use tile locations on the array to your advantage.

A tile located at nonCollisionTiles\[5,5\], will always have the same neigbours. So if a light is placed there, it is easy to see that nonCollisionTiles\[5,4\] needs to be updated.

With this information you can write a recursive function like this:

```
private void updateLights(int X, int Y, int lightLevel)
{
    neighbourUpdate(X, Y - 1, lightLevel - 1);
    neighbourUpdate(X, Y + 1, lightLevel - 1);
    neighbourUpdate(X - 1, Y, lightLevel - 1);
    neighbourUpdate(X + 1, Y, lightLevel - 1);
}
private void neighbourUpdate(int A, int B, int lightLevel)
{
    if (lightLevel > nonCollisionTiles[A, B].light)
    {
        nonCollisionTiles[A, B].light = lightLevel;
        updateLights(A, B, lightLevel);
    }
}

```

This function takes as input the X- and Y-location on the array and the light level. It then updates the neighbours (if their lightLevel is lower) and calls another UpdateLights for the location and lightLevel of the updated neighbour.

This is much faster then the double loop, all by using the storing method to our advantage.

# Answer
> 0 votes
Are you making sure you are only checking the visible tiles, and not the tiles for the entire map? This can greatly benefit your FPS. It looks to me as if your two foreach loops are checking every tile on the map up against every other tile. That will be *VERY* expensive in CPU cycles.

If your lights are in fixed positions, then I suggest you create a light-map: a doublearray of int to store the lighting. Then you can perform a check once, before the game begins to set the light-values from 0 to 5 of every tile.

When you draw the textures, you can lookup into the light-map to find how bright the texture should be.

If you have moving lights as well, then you could create another light-map which you update every time one of the moving lights actually move to another tile.

Then your draw routine would be:

```
foreach visible tile from the map
  get the texture
  find the corresponding tile in the the stationary light-map
    and the moving lights light-map
  use the highest lighting value from these to draw the texture

```

---
Tags: xna, c#, tilemap, lighting
---


# Question
Title: How to handle interactions between a sprite (player) and another sprite?
What's the proper way, a proper way, or any proper way at all, to handle interactions between a sprite (usually a player) and another sprite (can be any other object)? (in a tile based world)

i.e. getting into a vehicle, talking with other character, reading signs, etc.

My first instinct is to have some kind of "feeler" or interaction rectangle that's always in front of the player in the direction the player is facing. Then if that rectangle overlaps some kind of intractable object (driver door on vehicle, other character, sign, etc) I would be able to initiate an interaction.

Is this a naive implementation?

**EDIT**

This is for a 2D engine, written in C# for Xbox Live Arcade and Windows.

# Answer
One way of doing this (I am updating my answer for a 2D program):

You can have a key assigned to use objects. Let's say this key is 'E'

When user presses key 'E' Check the position of your character and the direction it looks at. Add them up, if there is an object at that position You call the Use function of the object

Inheritance or interface can help you here. The top level GeneralObject interface has the use function unimplemented, and your vehicle class can have a use function that puts the user in it, the door class which implements opens the door when use function is used, or character class which starts talking when its use function is called. If you press 'E' when a non-interactable object is in front of player, than nothing happens because that object's class's use function is empty.

This way, you don't have to say:

```
If ( objectToInteract is door)
   do this....
If ( objectToInteract is character)
   do this...

```

Instead, you say

```
objects.at(pickedobjectindex).use()

```

And the object will do what it should do, if it should somehow react.
> 3 votes

---
Tags: collision-detection, sprites
---


# Question
Title: I can't seem to figure out what's causing this bug with the "layout" keyword in GLSL
I have a GL shader file whose first few lines currently look like this:

```
#version 120
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 vertexUV;

```

When I try to compile this shader when running the program, it returns this error:

```
0:2(1): error: syntax error, unexpected NEW_IDENTIFIER

```

From what I know, this means that the word `layout` is giving it trouble. What am I doing wrong? Do I need to provide more information?

# Answer
> 3 votes
I believe that the problem is that you are trying to use the `layout` keyword, but the version is set at 120. Try changing the first line to `#version 330`. There is an alternative way of setting attribute locations, which can be found in this answer.

---
Tags: opengl
---


# Question
Title: Effective Methods to utilize 3d Scanners to produce game development resources
Once upon a time I was quite passionate about game development. About four years ago at the height of my game development aspirations, I was involved in a number of activities. I worked with a team of students at my college to build a game using XNA. I wrote a basic cross platform 3d engine using OpenGL/GLUT, and I wrote a simple tank game for Android using OpenGL ES 2.0.

For better or worse, since that time I've been swept up in the winds of corporate profit, and for the past few years I've been mostly preoccupied with building corporate applications and websites and I've done very well by it.

Even so, I've been trying to build games on the side, and one of the major limiting factors has always been the acquisition of quality resources (models, textures, sprites, audio) to support the game itself.

**Basically what I am trying to say is that given an individual whose greatest strength is the programming, and is mediocre at best at developing graphical and media assets, what do you think some techniques I could use in conjunction with a 3d scanner to help me produce realistic or at least decent 3d models and/or 2d renders of scanned objects?**

The catalyst for this thread is that I recently came across a kickstarter for a relatively affordable high quality scanner called 'Robocular'. Aside from being excited about the project as a huge nerd, I am quite frankly intrigued by the possibilities introduced by having the ability to cheaply manipulate a medium and subsequently scan it as a model. Although a device like this seems most suited to scanning terrain assets, I can't help but wonder whether it may be feasible to utilize multiple scanner runs to produce model animations, or perhaps scan individual body parts and cobble them together, applying animations later by manipulating the pieces in Blender. Or perhaps simply using a physical object as the initial base for the model manipulation.

Either way it seems way to potentially save a huge amount of time compared to how long it would have taken me to produce a model myself. I know there are a lot of free or affordable resource packs online, but one problem I've always had with them is that they don't necessarily combine with each other well. I.E. That cheap pack of humanoid models just doesn't quite work with the vehicle pack I purchased, or the free weapon pack I found, etc. It's often the case that the art style or level of detail from one pack to another just doesn't match up... But like I said I haven't been very active in the game dev scene for a while, so I'm not sure if a 3d scanner is necessarily going to provide as much of a shortcut as simply purchasing model packs...

It's just that the concept is so cool and open ended that it's difficult not to be excited about it.

Basically I was hoping to spark a discussion on the practical applications of such a tool. Given the high precision of the scanner and the fact that it supports color, it seems like you could do a lot with it.

Some of the initial ideas I had are:

* Play Doh or clay + Paint
* Wooden models + Paint
* Soap models + Paint
* Construction Paper or paper mache' + glue/tape
* Purchasing toys as base models, then augmenting the toy with clay or play doh to produce something unique
* Casting objects in wax, then carving details in the wax shape

I'm confident that some of these techniques could be significantly faster than using the actual 3d modeling tools, at least to start off. Anyone have some killer ideas on how to utilize a 3d scanner to create assets?

# Answer
> 3 votes
Well, your idea sounds great, but unfortuanately am afraid it's only great in theory , the reasons am saying this are:

* First of all you need actual real life models of each asset in order to produce their 3D counterparts
* I highly doubt that this is actually cheaper and easier than modelling and drawing or even buying (or getting for free ) your assets, you also need to buy the 3D scanner and maybe other things.
* So unless your game only have limited assets it will be much cheaper to buy or use (or even make) ready made models (example from TurboSquid).

The above are only the initial costs and we didn't even start developing the game, on the technical side you have other obstacles:

* When your models are 3D scanned, they are not particularly ready for in game use. 3D scanners will output very complex meshes with millions of polygions with alot of redundant polygons, you need to use fairly complex algorithms in order to decimate and simplify the meshes.
* When you are done with scanning and simplification, you to generate UV coordinates for texturing, which is usually part of the asset creation process.
* 3D scanned meshed still need to be Rigged and Skinned for actual in game animation. I don't see other way to do this.

**In conclusion I would say that using 3D scanned models is just another way to create 3D models with no apparent advantages. You will end up with mostly the same process just with different initial path.**

---
Tags: 3d, models, tools
---


# Question
Title: Can you export lighting models directly from 3D application to a real time renderer?
is it possible for example to insert lighting in a 3D Model software like 3DSMAX and export an animated model like md5,..etc. and export the lighting too ?

# Answer
> 0 votes
If I understand your question correctly, and you need to export the lighting model and not the light info (position, color etc). No, unless that particular lighting model shader was written in GLSL/Cg/HLSL.

3Ds max and other modelling tools use different totally different rendering algorithms, for instance Maya (and probably other programs) use \[http://en.wikipedia.org/wiki/Reyes\_rendering\]\[1\] (with ray tracing) and uses Renderman as its shading language.

While real time rendering engines use different kind of rendering algorithms based on forward rasterization that makes implementing most lighting models and global illumination a totally different thing.

So unless you re-implement what the 3D applications renderer do in your application, or your application just generate your GLSL/Cg/HLSL code for you, and even with that you still have a fairly complex task to integrate it with your real time renderer. it's not possible out of the box.

On the other hand exporting the light info is fairly trivial and you only need to read the exported file in your application and read the light info like {Position, Diffuse, Diffuse Color, Direction, Specular etc)

---
Tags: 3d, animation, lighting, 3d-meshes
---


# Question
Title: Smooth interpolation with variable time steps
My game engine just went through a small overhaul that changed its fixed time step loops into variable time steps ones. Though everything has already been adapted steadily to the new environment, there is still one algorithm that relied heavily on steady ticks: my camera's behavior.

It was pretty much like this (pseudo-code):

```
    class Camera {
        const float factor = /* value between 0 and 1 */;

        void update() {
            Vector2 distance = player.getPosition() - this.getPosition();
            this.move(distance * factor);
        }
    }

```

What is generally done for this sort of "pursuing" behavior? This is more than simple speeds and accelerations.

I *could* go with the following, but it still leaves a feeling of choppiness when in contrast with the rest of the game.

```
    class Camera {
        const float factor = /* value between 0 and 1 */;
        const float fixedStep = 1.0f / 40.0f; // supposing that it worked under 40FPS before

        float timeAcc = 0.0f;

        void update (float timeElapsed) {
            timeAcc += timeElapsed;

            while (timeAcc >= fixedStep) {
                timeAcc -= fixedStep;

                Vector2 distance = player.getPosition() - this.getPosition();
                this.move(distance * factor);
            }
        }
    }

```

It is C#-like pseudo-code, but don't be fooled: I'm actually using C++ and SFML, so I don't have many (or any) already-implemented methods at my reach.

# Answer
> 4 votes
You will unfortunately never get a behaviour that is 100% consistent across framerates, but it’s worth trying to approximate. Here is my suggested solution and the explanation of the maths behind it.

Consider what happens to `distance` after your update: it becomes `distance * (1 - factor)` since the camera moved by `distance * factor`. If the player wasn’t moving, here is how it would evolve with time at 40 fps:

```
t = 0.0       distance
t = 0.025     distance * (1 - factor)
t = 0.050     distance * (1 - factor) ^ 2
t = 0.075     distance * (1 - factor) ^ 3
 ...
t = 1.000     distance * (1 - factor) ^ 40
 ...
t = X         distance * (1 - factor) ^ (40 * X)

```

That last line gives us a simple formula for framerate-independent updates:

```
class Camera {
    const float factor = /* value between 0 and 1 */;
    const float fixedStep = 1.0f / 40.0f; // supposing that it worked under 40FPS before

    void update (float timeElapsed) {
        Vector2 distance = player.getPosition() - this.getPosition();
        float f = 1.0f - ::pow(1.0f - factor, timeElapsed / fixedStep);
        this.move(distance * f);
    }
}

```

Note that if `timeElapsed` is exactly `fixedStep`, this is equivalent to what you had before. That’s a good test to detect whether an algorithm is wrong (it can’t tell you whether it’s correct, though).

# Answer
> 2 votes
As Sean says you are really just using the accumulator to enforce a fixed time step, this is likely to look *very* jumpy in comparison with the rest of your game.

This would be one approach that applies movement on each update:

```
class Camera {
    const float factor = /* low values for "tight" movement */;

    void update (float timeElapsed) {
        Vector2 distance = player.getPosition() - this.getPosition();
        float ratioToMove = clamp(timeElapsed / factor, 0.0f, 1.0f);
        this.move(distance * ratioToMove);
    }
}

```

# Answer
> 1 votes
> changed its fixed time step loops into variable time steps ones

That was probably a bad idea.

Either way, your problem is that you're not actually using time deltas. With a variable frame rate you just replace your old `fixedStep` with a `variableStep` that is the distance moved.

Time accumulators are typically used to convert the variable frame rates of running applications into fixed time steps.

You typically *always* want to pass some kind of `time_delta` into all your `update()` methods no matter what, though: even if you have a fixed timestep, you may want to change that rate someday, and all your math should work in term of time deltas and be ready to accept whatever value.

---
Tags: mathematics, camera, interpolation, timestep
---


# Question
Title: How can I drag a polygon based on a mouse-moved event?
I have drawn a polygon in Java using `java.awt.Polygon`. I want to move that polygon with the mouse (by dragging it). I know that I have to use `mouseDragged` method in `addMouseMotionListener`. That way I can know coordinates of the path in along which the mouse is dragging the polygon.

But the problem is that I do not know what to do with the coordinates I get from the mouse to move the polygon. This is a part of the code:

```
public void mouseListeners(DrawEverything det) {
    det.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {

            if( isMouseInMe(evt.getX(), evt.getY())){//this "if" checks if the cursor is in the shape when we drag it

                int xTmep , yTemp ;
                xTmep = (int) (evt.getX() - xMousePressed) ;//xMousePressed--> the x position of the mouse when pressed on the shape
                yTemp = (int) (evt.getY() - yMousePressed) ;

                for(int i = 0 ; i < nPoints ; ++i){
                    xPoints[i]  +=    xTmep;//array of x-positions of the points of polygon
                    yPoints[i]  +=   yTemp;
                }
            }
        }
    });

```

This part is the main part that I am having trouble with:

```
for(int i = 0 ; i < nPoints ; ++i){
    xPoints[i] += xTmep;
    yPoints[i] += yTemp;
}

```

# Answer
A simple method to drag objects based on mouse interaction requires the following:

* The ability to detect and respond to mouse down, mouse motion ("moved") and mouse up events.
* The ability to detect if a specific point is "within" the shape you want to drag in some capacity.
* Optionally (depending on your APIs) place to store state about whether or not the drag is in progress and what the original click location of the drag was.

The process, in pseudocode, is as follows:

When you get a mouse-down event, record the drag origin position as the point the user clicked, figure out which shape the mouse hit, and store that shape.

```
void OnMouseDown (int mouseX, int mouseY) {
  m_previousPosition = new Point(mouseX, mouseY);

  foreach (var polygon in the scene) {
    if (polygon.containsPoint(m_dragOrigin)) {
      m_dragTarget = polygon;
      break;
    }
  }
}

```

The above method is simplistic, but illustrative. It simply tests every polygon in the scene to see if the clicked point (now stored in `m_previousPosition`) is within it, and if so, makes that polygon the "drag target," the object being moved. It stops after the first one is found. A complex scene may need a better method of doing the picking, for efficiency, but this should get you started.

Now every time you get a mouse-moved event, check if you are dragging something (if you have a non-null drag target). If you are, compute the *delta* between the mouse's current position and the previous position. That gives you the amount you need to move the drag target this frame, so move the object accordingly, and set the "previous" position to the current position so that the next mouse move event will perform the same basic logic:

```
void OnMouseMoved (int mouseX, int mouseY) {
  if (m_dragTarget != null) {
    m_dragTarget.X += mouseX - m_previousPosition.X;
    m_dragTarget.Y += mouseY - m_previousPosition.Y;

    m_previousPosition = new Point(mouseX, mouseY);
  }
}

```

Finally, when you get a mouse-up, terminate the drag by clearing the drag target:

```
void OnMouseUp (int mouseX, int mouseY) {
  m_dragTarget = null;
}

```

Note that some APIs provide deltas directly to their mouse-move APIs, so you may be able to use those metrics instead, which can simplify your logic.

It's also useful in practice to store a copy of the original position of the drag shape; for example if you want to easily support cancellation of the drag, or show a "shadow" as the user drags the object, leaving the original untouched until the drag completes, or to avoid floating-point error accumulation in some cases. You may want to consider augmenting the above bare-bones approach accordingly.

In that case you can actually do away with the per-frame delta computation and store the original drag origin point once (not updating it in the move handler), and instead compute the total delta from the original origin to the current point during the move handler and use that as the translation value for the ghosted drag shape.
> 2 votes

---
Tags: java, input
---


# Question
Title: FlashPunk + Flashdevelop - How to use sponsor provided preloader
I have developed a flash game using FlashPunk (on FlashDevelop). And now that I am trying to add a sponsor preloader and splashscreen to my game, I realize the flashpunk forums are down, and have been for over a week now :( Speak of bad timing.

I imagine some of you here do use FlashPunk. How have you managed to add such sponsor stuff to your game? I haven't had to deal with swf and fla at all until now.

The sponsor's preloader is an actual loading bar, at the end of which it also plays an animated splash screen.

Any help would be much appreciated.

Thanks!

# Answer
> 1 votes
I've had the exact same problem when i tried to add sponsorship SWF's to my game projects (I'm using FlashDevelop & flixel/as3). After a long search i found a way of adding the SWF, through converting it into some byteArray or something and adding to the stage. It worked (checked with Kongregate loader), but the clip just kept on looping and i found no way of accessing which frame its playing or how to stop it.

I'v integrated animations from swfs (which are created in flash, but are converted symbols), so i guess the easiest way to do this is to give the FLA file to someone who has FLASH IDE, convert the whole animation into a symbol(movieclip) and Embed the symbol & instantiate it as movieclip and add to the stage and finally check its **currentFrame**.

```
[Embed(source = "../lib/Sponsor.swf", symbol = "SponsorAnim")]
private var Sponsor:Class;
private var SponsorAnim:MovieClip = new Sponsor();

```

Hope my experience might help you.

---
Tags: flash, actionscript, flashdevelop
---


title: Can I trigger input/controls via code?

text:
# Question
Title: Can I trigger input/controls via code?
I have the 3rd person controller in my game, which moves with the *WASD* keys. But since I am developing for a mobile release, I want touch controls.

I have already the touch control-script in a new script-file, but attached to the same 3rd person controller-prefab.

When I swipe right for instance, I want Unity to trigger the D-key etc.

How can I do that?

```
...
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
{
    if (delta.x > 0)
        //trigger D?
    else if (delta.x < 0)
        //trigger A?
}
...

```

# Answer
First make a function that triggers the real action:

```
void moveLeft() { .. }

```

Then determine when to call it based on the platform:

Desktop: `if(A key down) { moveLeft(); }`
Mobile: `if(swiping left) { moveLeft(); }`

Another solution is to do the opposite:

Create some kind of interface/class that reads input:

```
// (this is a general solution not specific to Unity)
interface ICharacterController
{
  bool shouldMoveLeft();
  bool shouldJump();
}

```

Then, in your character class, have a method like `setController(ICharacterController c)`. In your character's logic code, call the aforementioned methods to determine what action to take.

Finally, implement the given interface and assign it separate for desktop and mobile.

Looking quickly at the Unity docs, it seems like using `sendMessage()` might be a good alternative to keeping references, if you want to reduce dependencies between your classes.
> 4 votes

# Answer
Your best choice, whilst keeping code simple, is to use Platform Specific Compilation. This will allow you to have one component that houses player input for multiple platforms.

For example:

```
public class PlayerController : MonoBehaviour {
    void Update () {

    #if UNITY_STANDALONE
        if (Input.GetKey(KeyCode.A))
            moveLeft();
        // Etc.
    #endif

    #if UNITY_IPHONE
        // Touch logic for iPhone here
    #endif

    #if UNITY_ANDROID
        // Touch logic for Android here
    #endif
    }
}

```

The compiler will then cherry pick which block to use based on your build target and will discard any non applicable clauses.
> 2 votes

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


# Question
Title: What is the purpose of indices in 3D rendering?
Suppose you were creating a 3D cube in OpenGL. You implement the necessary vertex data for the object (cube). What would be the point of using indices?

```
 void CreateCube()
        {
            const Vertex VERTICES[8] =
            {
                { { -.5f, -.5f,  .5f, 1 }, { 0, 0, 1, 1 } },
                { { -.5f,  .5f,  .5f, 1 }, { 1, 0, 0, 1 } },
                { {  .5f,  .5f,  .5f, 1 }, { 0, 1, 0, 1 } },
                { {  .5f, -.5f,  .5f, 1 }, { 1, 1, 0, 1 } },
                { { -.5f, -.5f, -.5f, 1 }, { 1, 1, 1, 1 } },
                { { -.5f,  .5f, -.5f, 1 }, { 1, 0, 0, 1 } },
                { {  .5f,  .5f, -.5f, 1 }, { 1, 0, 1, 1 } },
                { {  .5f, -.5f, -.5f, 1 }, { 0, 0, 1, 1 } }
            };

            const GLuint INDICES[36] =
            {
                0,2,1,  0,3,2,
                4,3,0,  4,7,3,
                4,1,5,  4,0,1,
                3,6,2,  3,7,6,
                1,6,5,  1,2,6,
                7,5,6,  7,4,5
            };

    //....

    glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES), VERTICES, GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(INDICES), INDICES, GL_STATIC_DRAW);

```

In the above example, a cube is created with the necessary vertices in world space. What is the relevance for the indices?

# Answer
> 33 votes
Indices exist to reduce the memory footprint required to represent a 3D model, much in the same way that color palettes can be used to reduce the memory footprint of a 2D image.

Indexing allows you to avoid repeating a full definition of a vertex if you have to duplicate that vertex's data, as you usually need to do for a complex model.

Modern 3D APIs render using triangles; each face of a cube requires two triangles:

```
A--B
|\ |   This cube face has two triangles:
| \|   ABD and ADC.
C--D

```

To specify that face without indices, you must specify the vertices `A, B, D, A, D, C`. Two vertices (`A` and `D`) are repeated in the vertex buffer.

However, with indices, you can have a vertex buffer containing only the required vertices (`A`, `B`, `C`, and `D`) and six indices: `0, 1, 3, 0, 3, 2`. Since indices are generally much smaller than vertices and many vertices generally repeat in practical models, this can be a significant space-savings.

Note that some vertices will only share partial attributes. For example, when rendering a cube with texture mapping, one generally wants unique texture coordinates per face, so you will have multiple vertices with the same position and different texture coordinates. That amount of duplication is acceptable and necessary; it's when you duplicate an *entire* set of vertex attributes that you'd start to see benefits from indexing.

If indeed all your mesh vertices are 100% distinct, there is no benefit to indices (in fact you'd use more space in the consumption of the redundant index buffer). This doesn't always occur, however.

# Answer
> 11 votes
Using indices serves three main purposes:

* Reducing memory requirements by enabling duplicate vertices to be removed from the original mesh.
* Reducing vertex shader calculations by enabling duplicate vertices to be transformed only once.
* Concatenating primitives thereby enabling you to reduce draw calls.

Of these the first one is obvious because you can measure it directly in your own code: if a mesh had, say, 50k vertices but if 30k of them were duplicates, then you've a memory saving.

The second and third are not so obvious - you need to already have made a decision to use indices, and you need to profile your code and isolate "before" and "after" performance in order to get a measurement of them.

For the second one, hardware is able to cache the result of recently transformed vertices. If the same vertex as one that was recently transformed comes along, the cached version can be used instead of having to perform the calculations all over again. Hardware uses the index to identify these, so indices are absolutely necessary to get this behaviour.

For the third, each draw call you make has a CPU overhead irrespective of how much GPU work it needs to do. If everything else is equal, drawing a 50k mesh in 1 draw call is going to be much faster than drawing it in 10k draw calls. But if your mesh is composed of multiple strips, or (even worse) a combination of strips and fans, you can't do it in a single draw call without (1) using indices, or (2) introducing degenerate triangles. But because indices are much smaller than vertices, using indices is preferred in the general case.

# Answer
> 1 votes
The indices say what groups of three vertices together form the faces of the cube. Not every set of three vertices of the triangle are faces of the triangle.

You could use each vertex exactly once, and just repeat many times the ones that are used in more than a triangle, but that would mean extra vertex transforms. With indices you transform the vertices only once and use them as many times as you need.

---
Tags: opengl
---


# Question
Title: Rendering Textured Terrain With SharpDX Toolkit
So i recently moved from XNA to SharpDX Toolkit and started with some basics. The 2d part was easy since nearly nothing has changed but im really struggeling with the 3d part. For example i wanted to render a heightmap based on riemers terrain tutorial however came along the following issue:

I have a little map (or terrain) class that contains the index and vertex arrays as buffer like so:

```
private SharpDX.Toolkit.Graphics.Buffer<VertexPositionNormalTexture> _mesh;
private SharpDX.Toolkit.Graphics.Buffer _indexBuffer;
private readonly static VertexInputLayout InputLayout = VertexInputLayout.New<VertexPositionNormalTexture>(0); // copied from the basic geometry

```

this get filled in propertly and render fine with VertexPositionColor. rendered the common XNA way:

```
//set effect parameters and resources
foreach (EffectPass pass in _effect.CurrentTechnique.Passes) {
    pass.Apply();

    //Globals.DefaultGraphicsDevice.SetRasterizerState(CullNone);

    Globals.DefaultGraphicsDevice.SetVertexBuffer(0, _mesh);

    // Setup the Vertex Buffer Input layout
    Globals.DefaultGraphicsDevice.SetVertexInputLayout(InputLayout);

    // Setup the index Buffer
    Globals.DefaultGraphicsDevice.SetIndexBuffer(_indexBuffer, true);

    // Finally Draw this mesh
    Globals.DefaultGraphicsDevice.DrawIndexed(PrimitiveType.TriangleList, _indexBuffer.ElementCount);
}

```

Now with my own half converted half remade shader i get

a) a black terrain or

b) HRESULT: \[0x80070057\] (wrong parameter)

and i cant figure out why (most likely since i never done much with 3d shaders)

the shader:

```
struct VertexShaderInput {
    float4 Position     : SV_Position;
    float3 Normal       : NORMAL;
    float2 TextureCoords: TEXCOORD0;
};

struct VertexShaderOutput {
    float4 Position     : SV_Position;
    //float4 VPosition      : SV_Position; //im not used to SV_Position and SV_Target so this could be the main problem
    float LightingFactor: TEXCOORD0;
    float2 TextureCoords: TEXCOORD1;
};

struct PixelShaderOutput {
    float4 Color        : SV_Target;
};

//------- Constants --------
float4x4 xView;
float4x4 xProjection;
float4x4 xWorld;
float3 xLightDirection;
float xAmbient;

Texture2D xTexture;
sampler TextureSampler = sampler_state {
    texture = <xTexture>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = mirror;
    AddressV = mirror;
};

VertexShaderOutput TexturedVS(VertexShaderInput VSin) {
    VertexShaderOutput Output = (VertexShaderOutput)0;
    float4x4 preViewProjection = mul(xView, xProjection);
    float4x4 preWorldViewProjection = mul(xWorld, preViewProjection);

    Output.Position = mul(VSin.Position, preWorldViewProjection);
    Output.TextureCoords = VSin.TextureCoords;

    float3 Normal = normalize(mul(normalize(VSin.Normal), xWorld));
    Output.LightingFactor = dot(Normal, -xLightDirection);

    return Output;
}

PixelShaderOutput TexturedPS(VertexShaderOutput PSIn) {
    PixelShaderOutput Output = (PixelShaderOutput)0;

    Output.Color = xTexture.Sample(TextureSampler, PSIn.TextureCoords);
    Output.Color.rgb *= saturate(PSIn.LightingFactor) + xAmbient;

    return Output;
}

technique Textured {
    pass p0 {
        Profile = 9.1;
        AlphaBlendEnable = false;
        CullMode = None;
        PixelShader = TexturedPS;
        VertexShader = TexturedVS;
    }
}

```

im thankfull for any help

(Disclaimer: i moved this from stackoverflow to here since i think it was missplaced and didn't got any attention)

# Answer
I was so close to the result when i posted this question... all i had to do is fix the texture warping and scale the texture coordinates down since it was drawing way too detailed. the black map was caused by a 1px black border on the texture and the clamping of the texture sampler. now its working nearly as it should. only the `AddressU = wrap;` does not want to work right now.
> 0 votes

---
Tags: c#, directx, hlsl, directx11, sharpdx
---


# Question
Title: How can I create 2D shadows that let me detect when the player is inside them?
I'm working on a 2D platform game, and I want my platforms to cast shadows along with some way to detect if the player is inside the shadow area (that is, not hit by the sun).

More specifically: I have a character, some platforms and a sun. When the player is under the shadow of some platform he is safe. If he goes to a location when the sunlight hit him, then he starts losing heath until he enters other shadow spot.

Right now the shadows are boxes with a transparent/diffuse material. Boxes are good because I can determine when the player enters or leaves them, but they are are ugly and don't have any animation. I need a shadow that changes when the sun changes its position, without losing the ability to determine when the player is inside a shadow (I think this can be done using a ray cast)?

How can I accomplish this?

# Answer
> 5 votes
I did a quick sketch of how it could be done.

Yellow round thing is the Sun, obviously, grey things are rays and black ones are boxes. The blue lines are the shadow triangles and yellow dots are the vertex points.

You cast rays down from the Sun to the edges of the blocks and through them. Take the vertices where it hit the box and the ground. Then you draw the mesh in code.

---
Tags: 2d, unity, shadows
---


# Question
Title: How can I compute the common points when spheres intersect?
When two spheres intersect they should share one or two points. I want to know how to compute those points?

I was thinking of something like this:

* -check if the spheres intersect
* -calculate `radius_1` distance from `center_1` in the direction of `center_2`
* -calculate `radius_2` distance from `center_2` in the direction of `center_1`
* -substract the smaller to the larger and have that one as "collision" point

This sounds to me a little too tricky, I wanted to know if there is a simplier way to achieve this?

# Answer
> 8 votes
Let `C₁` and `C₂` be the sphere centres, and `R₁` and `R₂` their radiuses. We pick a point `A` on the intersection circle and we want to find `B`, the centre of the intersection circle:

Pythagoras gives us the following two equalities:

```
AB² = AC₁² - BC₁²
AB² = AC₂² - BC₂²

```

Combining the two and replacing AC₁ with R₁ and AC₂ with R₂:

```
BC₁² - BC₂² = R₁² - R₂²

```

We know that `C₁B + BC₂ = C₁C₂`:

```
                BC₁² - (C₁C₂ - BC₁)² = R₁² - R₂²
BC₁² - C₁C₂² - BC₁² + 2 * C₁C₂ * BC₁ = R₁² - R₂²
                      2 * C₁C₂ * BC₁ = R₁² - R₂² + C₁C₂²
                                 BC₁ = (R₁² - R₂² + C₁C₂²) / (2 * C₁C₂)

```

Giving us the final formula for the C₁B **vector**:

```
C₁B = (R₁² - R₂² + C₁C₂²) / (2 * C₁C₂²) * C₁C₂

```

Using pseudocode:

```
float P = dot(center_2 - center_1, center_2 - center_1);
float Q = (radius_1 * radius_1 - radius_2 * radius_2 + P) / (2.0f * P);
Point B = center_1 + Q * (center_2 - center_1);

```

# Answer
> 1 votes
Here a simple method to compute the center of the intersection circle between two (hyper)spheres that works for every dimension (but 0D) using some vector notation.

Let **C1** and **C2** be the center of your (hyper)spheres, r1 and r2 the radii.

**D** := **C2** \- **C1** is the vector that moves **C1** to **C2**; the leght of **D** (|**D**|) is the distance between centers.

Now d := |**D**| -(r1+r2) is the distance between the (hyper)spheres: positive menans no intersection, 0 menans point intersection, negative means intersection.

In the latter case, -d is an usefull measure of how much the spheres compenetrate.

Now the distance between **C1** and the center(**C**) we are looking for, is r1 - (-d)/2; being -d/2 the half distance and being substracted from r1 because r1 is "responsible" for "half compenetration".

Then **C** = **D** /|**D**| * (r1+d/2)

---
Tags: intersection
---


# Question
Title: How can I handle merging and splitting lots in a city block?
I am currently working on a SimCity-style game in C# using SharpDX. I'm having trouble handling the growing and shrinking the game entities that represent zones within a region. For example:

```
     +-------+-------+-------+-------+
     |       |       |       |       |
     |       |       |       |       |
     |   R   |   R   |   R   |   R   |
     |       |       |       |       |
     +-------+-------+-------+-------+   Residential Zones as initially placed
     |       |       |       |       |   with low populations.
     |       |       |       |       |
     |   R   |   R   |   R   |   R   |
     |       |       |       |       |
     +-------+-------+-------+-------+

     +---------------+-------+-------+
     |               |       |       |
     |               |       |       |
     |       R       |   R   |       |
     |               |       |       |   After time, residential zones merge
     +-------+-------+-------+   R   |   to form larger dwellings.
     |       |       |       |       |
     |       |       |       |       |
     |   R   |   R   |   R   |       |
     |       |       |       |       |
     +-------+-------+-------+-------+
```

I'm not sure how to represent the simulation and display of this kind of behavior. At the moment, I have the following:

* Each zone is represented by an individual object of type `ResidentialZone`.
* Each `ResidentialZone` has a `GridSpace[]` property which can changed when the zone shrinks or expands.
* `OnGrow()`: a new `ResidentialZone` is created combining the properties (population, education, etc.) of the 2+ that it combined.
* `OnShrink()`: new `ResidentialZone`s are created and divide the properties of the one they replaced.
* All Zones (Residential, Commercial, Industrial, Parks, etc.) are stored in a collection of `IZone` within class `ZoneManager` which handles simulation, rendering, placement by the user.

In the eyes of more experiences game developers, does this model represent a good practice and what performance impacts may arise? Any improvements or suggestions?

# Answer
There is no "best" way to solve a software architecture problem. Only the way which works best for *you*.

Does your current implementation work the way you want it to work? Do you see no reasons why it wouldn't work with any other features you have planned? When the answer to both questions is yes, you should keep it.

Also, don't worry too much about the performance. In game development, the performance bottleneck is usually the graphic engine (yes, even for 2d games). It's very rare for game mechanics to actually be the main CPU cycle consumers. And when it is the case it is usually impossible to know beforehand. Programmers are notoriously bad at predicting which performance bottlenecks will affect the user experience the most. The only way to reliably find them is to profile the application with a tool.

Donald Knuth once wrote:

> "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."

First, get an implementation which works and which fits into your software architecture. Then check if it impacts performance too much by using a profiler. When the profiler confirms that the performance is unacceptable, then, and only then, optimize it.
> 2 votes

# Answer
It seems to me that your is like a graphs manipulation problem. So using graphs to model your neighborhood will probably give you more satisfaction both in terms of game dynamics expressivity and performance.

In this modelling scenario, your residential entities are associated to a node in the graph, so the entity does not need to store any topological information. When you merge your zones, you create a new node that take over the ownership of the edge halfs of every node involved into mergin ( you can now merge more than two zones). The edges can be agumented with a cost value so you can specify in which direction is better to merge and so on.

The same considerations apply for splitting nodes, again condition for splitting and for choosing splitting solution has to be met before complete a potential split operation.

In general this approach will add some complexity in your arcitecture -in the sense that the things you are working with become complex things instead simple ones- but probably the challenges you will face will reward you good.
> 1 votes

---
Tags: simulations, gameobject
---


# Question
Title: How can I adjust the UVs of my quad so my texture isn't flipped?
My sprite geometry is reversed using matrix so that it is in the XZ plane. This results in the image used for the sprite to also be reversed, which I don't want:

(source : http://www.badlogicgames.com/wordpress/?p=2032 )

The image is then upside-down (note the 2 and 4):

Would you know how to switch the UVs, or apply a matrix on the image only?

Here is my code to draw the new image (the broken one):

```
curPix.drawPixmap(modelPix, newX, newY, modelX, modelY, tileResolution, tileResolution);

```

This is how the plane is modified in "render:"

```
batch.setProjectionMatrix(cam.combined);
batch.setTransformMatrix(matrix);
batch.begin();
getMap(0).draw(batch);
batch.end();

```

# Answer
> 2 votes
It seems as though you're just seeing the back of the quad, which will be the reverse of the front.

To fix this, simply rotate -90 degrees about the z-axis, so the quad is facing up instead of down. You'll have to move it down the x plane a little after that though.

Otherwise you can rotate the quad 90 degrees about the z-axis, and then 180 degrees about the x-axis to get it facing up. You probably shouldn't mess around with the UV coordinates if you're using a spriteBatch interface.

---
Tags: libgdx, matrix, uv-mapping
---


# Question
Title: How can I create a tile-based game map from a large source image?
I'm trying to make a huge tile-based map for my game. I've authored a large source image of the map and saved it, but now I'm unsure how to break this up into tiles and render it as a grid so I can have tile-based movement and mark certain tiles as collision, et cetera.

How should I go about this?

# Answer
> 1 votes
To represent the *logical* set of tiles in your map (which includes information about the collision or passability of a tile), you can have a `Tile` class, for example:

```
class Tile {
  public bool IsWalkable { get; private set; }
};

```

You must define a tile size (constants `TileSizeX` and `TileSizeY`). Then when you load your map, you know how many tiles the map has via some simple division (`widthInTiles = ImageWidth / TileSizeX` for example). Once you have compute the tile counts in both directions, you can create an array to store all the tiles:

```
Tile[] tiles = new Tile[widthInTiles * heightInTiles];

```

You could then load collision information or other tile properties from another data file, such as a simple text file where each line represented a row of tiles and each character one of the tiles in the row. For example, if `0` represents a passable tile and `1` represents a wall, a `collision.txt` file for a simple small map might look like:

```
111111
100111
100001
101001
111111

```

You can load that text file and read each character, using that data to initialize the individual tiles in the array you just created. You now have the basics of logical tile-based representation of the world, with collision data, using a large non-tiled map as the background.

Note that while you could just render the source background image as a large texture, you probably don't want to do that beyond a certain size. You want to actually split the source image up into smaller images of some defined size (they do *not* have to correspond 1:1 with your tile sizes) and load and render those. This allows you to drop non-visible chunks of the map from memory. You can eventually apply a similar logic to your tile map data if your maps get large enough. You can do this splitting at load time when you read in the original source image, or you can do it offline as a pre-processing step.

If you want to render grid lines, you can bake them into the texture (again, at load time or in a pre-processing tool you write) or render them dynamically overtop the texture chunks for the background.

---
Tags: 2d, tiles, tilemap, grid
---


# Question
Title: Match-3 algorithm to fill empty space left from removing matches
I am currently creating a match 3 game.

I am at the point where I have objects dropping down in the column when only one item is removed. So if an item is removed, the above item moves into its old position etc.

The problem I am having now is that when more than one item is removed from a column, the items in that column only drop down to the first item that was removed. Instead of filling in both items that were removed it just drops down to fill in the first one.

So basically, if two(or more) items are removed from a column the second, third, fourth, etc positions are left blank.

The way I am designing my game is I am using units of 1. So each item takes up 1 unit by x and 1 unit by y. This means that I can position the items like in a grid, at 0x1, 0x2, etc.

What kind of algorithm could I use to move multiple items down to fill the empty space?

# Answer
> 2 votes
Here's a simple algorithm that'll do what you want:

```
For each column
  Find the lowest empty position
     While that position is empty, move every item above it down by 1
  Repeat until there are no empty positions

```

In code that might look like:

```
for(Column c : columns)
   continue = true; //assume there's an empty so we can look for it
   while(continue)
      emptyPosition = getLowestEmpty(c);
      if(emptyPosition == null) //no empties found
          continue = false;
          break;
      while(positionIsEmpty(emptyPosition.column, emptyPosition.row))
          //while the position is empty, move everything above it down
          moveDownItemsAbovePosition(emptyPosition)

```

where `getLowestEmpty(c)` would be something like:

```
getLowestEmpty(Column c)
   for(Row r in c.rows) //assuming bottom to top
      if(positionIsEmpty(c, r))//check if the position is empty
         return position(c,r)//if it is, we've found the bottom most empty
   return null //we didn't find any empties

```

---
Tags: java, algorithm, libgdx
---


# Question
Title: Java High-Resolution Timer for a simple game
I want to work on a model of some kind of simple shape shooter game I would develop for either the desktop or the Android, using the libGDX library. There's something I want to incorporate into the game, and that is a countdown timer with the smallest unit in centiseconds.

The trouble I'm having is which resource to use to incorporate a fully-accurate game timer where it is in sync with real time, meaning that every second on the game timer, when the game is running at full speed, is equal to one second in real time. (I should understand what is a high-resolution timer)

Java's Swing Timer class won't do, and so are the two methods from the static System class. And I'm not very confident about the timer classes I've looked up online, unless I accidentally ran into one of them and never realized it's completely accurate.

I have practiced implementing my own countdown timer except that it ain't synchronized because I'm doing an update for every 10 milliseconds. I asked a similar question on StackOverflow, but I am getting a little too obsessed in trying to find a perfectly good timer.

# Answer
System.nanoTime()

It's a high-resolution timer in nanoseconds. This is as good as it gets in Java. But since it is nanosecond precision, it should be more than enough for your needs.

Regarding your concern on sync with real time: Most games don't care about the real world time but are only interested in elapsed time intervals. However, one second delta time measured with System.nanoTime() is obviously equal to one second in real world.
> 1 votes

---
Tags: java, game-design, timer, prototyping
---


# Question
Title: XNA 4.0: Blender .fbx File Won't Display 3D Model
So I followed the basic 3D model display tutorial found here: http://msdn.microsoft.com/en-us/library/bb197293%28v=xnagamestudio.31%29.aspx

And while I know this is for XNA 3.1, I can still get the screen to show and the background color to change fine. The model file seems to be accepted in the method below:

```
protected override void LoadContent()
    {
        // Used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        grudmud = Content.Load<Model>("Models\\Vikings_grudmud");

        aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
    }

```

The model was created in Blender, so perhaps I'm missing a step in creating a mesh or certain texture for it? I have colored it in Blender and it's a simple blocky humanoid figure. Is there a scaling I should check in Blender so the camera in XNA is not inside the object?

Here's where I actually draw the object and set out some basic properties:

```
protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Aqua);

        Matrix[] transforms = new Matrix[grudmud.Bones.Count];
        grudmud.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in grudmud.Meshes) {

            foreach (BasicEffect effect in mesh.Effects) {
                effect.EnableDefaultLighting();
                effect.World = transforms[mesh.ParentBone.Index] *
                    Matrix.CreateRotationY(modelRotation)
                   * Matrix.CreateTranslation(modelPosition);
                effect.View = Matrix.CreateLookAt(cameraPosition,
                    Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
                    aspectRatio, 1.0f, 10000.0f);
                effect.PreferPerPixelLighting = true;
            }

            mesh.Draw();
        }
        base.Draw(gameTime);
    }

```

The initial camera and player model positions:

```
Vector3 modelPosition = Vector3.Zero;
    float modelRotation = 0.0f;
    Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);

```

I haven't even attempted to implement the face texture yet.

It seems to have a wireframe/mesh, I've just colored in the faces. The model is pretty much centered around the origin.

Am I exporting it wrong? Do I need to specify lighting/camera angles any further?

# Answer
I was having the same problem when following the same tutorial. I took Fibericon's advice and played with the export scale. I had to increase it to 100.0 (from 1.0) for the model to display properly when compiled in XNA. As an alternative, I found decreasing the distance of the camera from 5000.0f to 50.0f made the model visible.

This begs the question *why*. The suggested export scale based on this help page is 1.0. The scale of my model's objects are all 1.0. My XNA code is identical to the OP's.

Regardless, it's working. Thanks Fibericon!
> 2 votes

---
Tags: xna, c#, blender, 3d-meshes
---