# Question
Title: Should I still display splash screens for middleware that has been discontinued?
Usually, you would include splash logos at the beginning of a game to credit various middleware that you've used. Say the company has dissolved or for open source the supporting group has simply moved on and declared the project over. In the hypothetical situation where a middleware project has been discontinued and you still have the legal right to use it, wouldn't you still include the logo for that project at the beginning?

Only concerned with the opening splashes, since I'm pretty sure it would be polite to credit the individuals who worked on that piece in the text credits or at the end.

# Answer
> 2 votes
The use of splash screens depends on the agreements you have (or have accepted by using the software) with a specific company. This will vary from software to software and must be researched for each piece of software you use. Just because the software is no longer being worked on doesn't mean there are no longer legal requirements for its use.

You can remain on the safe side and include it now it you were supposed to include it before. If you don't want to show it anymore, you'll have to do the research for the specific technology you're using.

---
Tags: licensing
---


# Question
Title: Deferred tiled shading, tile frusta calculation in OpenGL
I'm trying to do deferred tiled shading in OpenGL using the compute shader but I have hit a snag when trying to create the frustum for each tile. I'm using AMD's Forward+ demo (written in D3D) as a guide but lights seem to be culled when they shouldn't.

# UPDATE

Read below for updates.

This is my (complete) compute shader:

```
    #version 430 core

#define MAX_LIGHTS 1024
#define MAX_LIGHTS_PER_TILE 40

#define WORK_GROUP_SIZE 16

struct PointLight
{
    vec3 position;
    float radius;
    vec3 color;
    float intensity;
};

layout (binding = 0, rgba32f) uniform writeonly image2D outTexture;
layout (binding = 1, rgba32f) uniform readonly image2D normalDepth;
layout (binding = 2, rgba32f) uniform readonly image2D diffuse;
layout (binding = 3, rgba32f) uniform readonly image2D specular;
layout (binding = 4, rgba32f) uniform readonly image2D glowMatID;

layout (std430, binding = 5) buffer BufferObject
{
    PointLight pointLights[];
};

uniform mat4 view;
uniform mat4 proj;
uniform mat4 viewProj;
uniform mat4 invViewProj;
uniform mat4 invProj;
uniform vec2 framebufferDim;

layout (local_size_x = WORK_GROUP_SIZE, local_size_y = WORK_GROUP_SIZE) in;

shared uint minDepth = 0xFFFFFFFF;
shared uint maxDepth = 0;
shared uint pointLightIndex[MAX_LIGHTS];
shared uint pointLightCount = 0;

vec3 ReconstructWP(float z, vec2 uv_f)
{
    vec4 sPos = vec4(uv_f * 2.0 - 1.0, z, 1.0);
    sPos = invViewProj * sPos;

    return (sPos.xyz / sPos.w);
}

vec4 ConvertProjToView( vec4 p )
{
    p = invProj * p;
    p /= p.w;
    return p;
}

// calculate the number of tiles in the horizontal direction
uint GetNumTilesX()
{
    return uint(( ( 1280 + WORK_GROUP_SIZE - 1 ) / float(WORK_GROUP_SIZE) ));
}

// calculate the number of tiles in the vertical direction
uint GetNumTilesY()
{
    return uint(( ( 720 + WORK_GROUP_SIZE - 1 ) / float(WORK_GROUP_SIZE) ));
}

vec4 CreatePlaneEquation( vec4 b, vec4 c )
{
    vec4 n;

    // normalize(cross( b.xyz-a.xyz, c.xyz-a.xyz )), except we know "a" is the origin
     n.xyz = normalize(cross( b.xyz, c.xyz ));

    // -(n dot a), except we know "a" is the origin
    n.w = 0;

    return n;
}

float GetSignedDistanceFromPlane( vec4 p, vec4 eqn )
{
    // dot( eqn.xyz, p.xyz ) + eqn.w, , except we know eqn.w is zero
    // (see CreatePlaneEquation above)
    return dot( eqn.xyz, p.xyz );
}

vec4 CalculateLighting( PointLight p, vec3 wPos, vec3 wNormal, vec4 wSpec, vec4 wGlow)
{
    vec3 direction = p.position - wPos;

    if(length(direction) > p.radius)
        return vec4(0.0f, 0.0f, 0.0f, 0.0f);

    float attenuation = 1.0f - length(direction) / (p.radius);
    direction = normalize(direction);
    float diffuseFactor = max(0.0f, dot(direction, wNormal)) * attenuation;
    return vec4(p.color.xyz, 0.0f) * diffuseFactor * p.intensity;
}

void main()
{
        ivec2 pixelPos = ivec2(gl_GlobalInvocationID.xy);
        vec2 tilePos = vec2(gl_WorkGroupID.xy * gl_WorkGroupSize.xy) / vec2(1280, 720);

        vec4 normalColor = imageLoad(normalDepth, pixelPos);

        float d = normalColor.w;

        uint depth = uint(d * 0xFFFFFFFF);

        atomicMin(minDepth, depth);
        atomicMax(maxDepth, depth);

        barrier();

        float minDepthZ = float(minDepth / float(0xFFFFFFFF));
        float maxDepthZ = float(maxDepth / float(0xFFFFFFFF));

        vec4 frustumEqn[4];
        uint pxm = WORK_GROUP_SIZE * gl_WorkGroupID.x;
        uint pym = WORK_GROUP_SIZE * gl_WorkGroupID.y;
        uint pxp = WORK_GROUP_SIZE * (gl_WorkGroupID.x + 1);
        uint pyp = WORK_GROUP_SIZE * (gl_WorkGroupID.y + 1);

        uint uWindowWidthEvenlyDivisibleByTileRes = WORK_GROUP_SIZE * GetNumTilesX();
        uint uWindowHeightEvenlyDivisibleByTileRes = WORK_GROUP_SIZE * GetNumTilesY();

        vec4 frustum[4];
        frustum[0] = ConvertProjToView( vec4( pxm / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pym) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f, 1.0f) );
        frustum[1] = ConvertProjToView( vec4( pxp / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pym) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f, 1.0f) );
        frustum[2] = ConvertProjToView( vec4( pxp / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pyp) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f ,1.0f) );
        frustum[3] = ConvertProjToView( vec4( pxm / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pyp) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f, 1.0f) );

        for (int i = 0; i < 4; i++)
            frustumEqn[i] = CreatePlaneEquation(frustum[i], frustum[(i+1) & 3]);

        barrier();

        int threadsPerTile = WORK_GROUP_SIZE * WORK_GROUP_SIZE;

        for (uint i = 0; i < MAX_LIGHTS; i+= threadsPerTile)
        {
            uint il = gl_LocalInvocationIndex + i;

            if (il < MAX_LIGHTS)
            {
                PointLight p = pointLights[il];

                vec4 viewPos = view * vec4(p.position, 1.0f);
                float r = p.radius;

                if (viewPos.z + minDepthZ < r && viewPos.z - maxDepthZ < r)
                {

                if( ( GetSignedDistanceFromPlane( viewPos, frustumEqn[0] ) < r ) &&
                    ( GetSignedDistanceFromPlane( viewPos, frustumEqn[1] ) < r ) &&
                    ( GetSignedDistanceFromPlane( viewPos, frustumEqn[2] ) < r ) &&
                    ( GetSignedDistanceFromPlane( viewPos, frustumEqn[3] ) < r) )

                    {
                        uint id = atomicAdd(pointLightCount, 1);
                        pointLightIndex[id] = il;
                    }
                }

            }
        }

        barrier();

        vec4 diffuseColor = imageLoad(diffuse, pixelPos);
        vec4 specularColor = imageLoad(specular, pixelPos);
        vec4 glowColor = imageLoad(glowMatID, pixelPos);

        vec2 uv = vec2(pixelPos.x / 1280.0f, pixelPos.y / 720.0f);

        vec3 wp = ReconstructWP(d, uv);
        vec4 color = vec4(0.0f, 0.0f, 0.0f, 1.0f);

        for (int i = 0; i < pointLightCount; i++)
        {
            color += CalculateLighting( pointLights[pointLightIndex[i]], wp, normalColor.xyz, specularColor, glowColor);
        }

        barrier();

        if (gl_LocalInvocationID.x == 0 || gl_LocalInvocationID.y == 0 || gl_LocalInvocationID.x == 16 || gl_LocalInvocationID.y == 16)
            imageStore(outTexture, pixelPos, vec4(.2f, .2f, .2f, 1.0f));
        else
        {
            imageStore(outTexture, pixelPos, color);
            //imageStore(outTexture, pixelPos, vec4(maxDepthZ));
            //imageStore(outTexture, pixelPos, vec4(pointLightCount / 128.0f));
            //imageStore(outTexture, pixelPos, vec4(vec2(tilePos.xy), 0.0f, 1.0f));
        }
}

```

This is the part I think is the problem, the culling part:

```
        barrier();

    float minDepthZ = float(minDepth / float(0xFFFFFFFF));
    float maxDepthZ = float(maxDepth / float(0xFFFFFFFF));

    vec4 frustumEqn[4];
    uint pxm = WORK_GROUP_SIZE * gl_WorkGroupID.x;
    uint pym = WORK_GROUP_SIZE * gl_WorkGroupID.y;
    uint pxp = WORK_GROUP_SIZE * (gl_WorkGroupID.x + 1);
    uint pyp = WORK_GROUP_SIZE * (gl_WorkGroupID.y + 1);

    uint uWindowWidthEvenlyDivisibleByTileRes = WORK_GROUP_SIZE * GetNumTilesX();
    uint uWindowHeightEvenlyDivisibleByTileRes = WORK_GROUP_SIZE * GetNumTilesY();

    vec4 frustum[4];
    frustum[0] = ConvertProjToView( vec4( pxm / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pym) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f, 1.0f) );
    frustum[1] = ConvertProjToView( vec4( pxp / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pym) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f, 1.0f) );
    frustum[2] = ConvertProjToView( vec4( pxp / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pyp) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f ,1.0f) );
    frustum[3] = ConvertProjToView( vec4( pxm / float(uWindowWidthEvenlyDivisibleByTileRes) * 2.0f - 1.0f, (uWindowHeightEvenlyDivisibleByTileRes - pyp) / float(uWindowHeightEvenlyDivisibleByTileRes) * 2.0f - 1.0f, 1.0f, 1.0f) );

    for (int i = 0; i < 4; i++)
        frustumEqn[i] = CreatePlaneEquation(frustum[i], frustum[(i+1) & 3]);

    barrier();

    int threadsPerTile = WORK_GROUP_SIZE * WORK_GROUP_SIZE;

    for (uint i = 0; i < MAX_LIGHTS; i+= threadsPerTile)
    {
        uint il = gl_LocalInvocationIndex + i;

        if (il < MAX_LIGHTS)
        {
            PointLight p = pointLights[il];

            vec4 viewPos = view * vec4(p.position, 1.0f);
            float r = p.radius;

            if (viewPos.z + minDepthZ < r && viewPos.z - maxDepthZ < r)
            {

            if( ( GetSignedDistanceFromPlane( viewPos, frustumEqn[0] ) < r ) &&
                ( GetSignedDistanceFromPlane( viewPos, frustumEqn[1] ) < r ) &&
                ( GetSignedDistanceFromPlane( viewPos, frustumEqn[2] ) < r ) &&
                ( GetSignedDistanceFromPlane( viewPos, frustumEqn[3] ) < r) )

                {
                    uint id = atomicAdd(pointLightCount, 1);
                    pointLightIndex[id] = il;
                }
            }

        }
    }

    barrier();

```

The weird thing is that when I visualize the light count per tile, it shows all tiles having some manner of lights (first image).

Second image shows the final output, a thin line of lights down the middle of the screen and nothing above or below. Removing the culling (GetSignedDistanceFromPlane()) gives the desired result, albeit with my framerate dropping like a rock.

My guess would be that the frustum is constructed wrong but I'm unsure of the math behind it and could use some help right now.

Edit: Added another image which shows the expected output.

# UPDATE 1

We've changed how the culling is done, the code now looks like this:

```
barrier();

float minDepthZ = float(minDepth / float(0xFFFFFFFF));
float maxDepthZ = float(maxDepth / float(0xFFFFFFFF));

//total tiles = tileScale * 2
vec2 tileScale = vec2(1280, 720) * (1.0f / float(2*WORK_GROUP_SIZE));
vec2 tileBias = tileScale - vec2(gl_WorkGroupID.xy);

vec4 c1 = vec4(-proj[0][0] * tileScale.x, 0.0f, tileBias.x, 0.0f);
vec4 c2 = vec4(0.0f, -proj[1][1] * tileScale.y, tileBias.y, 0.0f);
vec4 c4 = vec4(0.0f, 0.0f, 1.0f, 0.0f);

 // Derive frustum planes
vec4 frustumPlanes[6];
// Sides
//right
frustumPlanes[0] = c4 - c1;
//left
frustumPlanes[1] = c4 + c1;
//bottom
frustumPlanes[2] = c4 - c2;
//top
frustumPlanes[3] = c4 + c2;
// Near/far
frustumPlanes[4] = vec4(0.0f, 0.0f,  1.0f, -minDepthZ);
frustumPlanes[5] = vec4(0.0f, 0.0f, -1.0f,  maxDepthZ);

for(int i = 0; i < 4; i++)
{
    frustumPlanes[i] *= 1.0f / length(frustumPlanes[i].xyz);
}

//DO CULLING HERE
for (uint lightIndex = gl_LocalInvocationIndex; lightIndex < numActiveLights; lightIndex += WORK_GROUP_SIZE)
{
    PointLight p = pointLights[lightIndex];

    if (lightIndex < numActiveLights)
    {
        bool inFrustum = true;
        for (uint i = 0; i < 4; i++)
        {
            float dd = dot(frustumPlanes[i], view * vec4(p.position, 1.0f));
            inFrustum = inFrustum && (dd >= -p.radius_length);
        }

        if (inFrustum)
        {
            uint id = atomicAdd(pointLightCount, 1);
            pointLightIndex[id] = lightIndex;
        }
    }
}

barrier();

```

This works better, our lights are now culled properly (except min/max depth because it's not implemented properly yet) against our tiles. So far, so good, BUT! We have a problem with edges of lights, the tiles do not cover the entire light radius and performance is godawful. 1024 lights gives at best 40fps with tons of stutter.

This video shows what happens at edges, the grey tiles are what tiles are affected by the light (single pointlight) and the red parts are shaded geometry.

http://www.youtube.com/watch?v=PiwGcFb9rWk&feature=youtu.be

Scaling the radius so that it is larger when culling "works" but makes performance drop even harder.

# Answer
> 7 votes
Final answer, solved the performance problem! Changed my culling loop to this instead (based on the one used by Dice in BF3)

```
uint threadCount = WORK_GROUP_SIZE * WORK_GROUP_SIZE;
    uint passCount = (numActiveLights + threadCount - 1) /threadCount;
for (uint passIt = 0; passIt < passCount; ++passIt)
{
    uint lightIndex =  passIt * threadCount + gl_LocalInvocationIndex;

    lightIndex = min(lightIndex, numActiveLights);

    p = pointLights[lightIndex];
    pos = view * vec4(p.position, 1.0f);
    rad = p.radius_length;

    if (pointLightCount < MAX_LIGHTS_PER_TILE)
    {
        inFrustum = true;
        for (uint i = 3; i >= 0 && inFrustum; i--)
        {
            dist = dot(frustumPlanes[i], pos);
            inFrustum = (-rad <= dist);
        }

        if (inFrustum)
        {
            id = atomicAdd(pointLightCount, 1);
            pointLightIndex[id] = lightIndex;
        }
    }
}

```

I can now do 4096 lights at 80 fps, I'm more than happy.

# Answer
> 3 votes
Have solved the issue, partially. This is the new culling code, which works for everything but the far and near plane. Performance is still pretty bad so if anyone can see what might cause that it would be appreciated.

```
        ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);

    vec4 normalColor = imageLoad(normalDepth, pixel);

    float d = normalColor.w;

    uint depth = uint(d * 0xFFFFFFFF);

    atomicMin(minDepth, depth);
    atomicMax(maxDepth, depth);

    barrier();

    float minDepthZ = float(minDepth / float(0xFFFFFFFF));
    float maxDepthZ = float(maxDepth / float(0xFFFFFFFF));

    vec2 tileScale = vec2(1280, 720) * (1.0f / float( 2 * WORK_GROUP_SIZE));
    vec2 tileBias = tileScale - vec2(gl_WorkGroupID.xy);

    vec4 col1 = vec4(-proj[0][0]  * tileScale.x, proj[0][1], tileBias.x, proj[0][3]);

    vec4 col2 = vec4(proj[1][0], -proj[1][1] * tileScale.y, tileBias.y, proj[1][3]);

    vec4 col4 = vec4(proj[3][0], proj[3][1],  -1.0f, proj[3][3]);

    vec4 frustumPlanes[6];

    //Left plane
    frustumPlanes[0] = col4 + col1;

    //right plane
    frustumPlanes[1] = col4 - col1;

    //top plane
    frustumPlanes[2] = col4 - col2;

    //bottom plane
    frustumPlanes[3] = col4 + col2;

    //near
    frustumPlanes[4] =vec4(0.0f, 0.0f, -1.0f,  -minDepthZ);

    //far
    frustumPlanes[5] = vec4(0.0f, 0.0f, -1.0f,  maxDepthZ);

    for(int i = 0; i < 4; i++)
    {
        frustumPlanes[i] *= 1.0f / length(frustumPlanes[i].xyz);
    }

    //DO CULLING HERE
    for (uint lightIndex = gl_LocalInvocationIndex; lightIndex < numActiveLights; lightIndex += WORK_GROUP_SIZE)
    {
        PointLight p = pointLights[lightIndex];

        if (pointLightCount < MAX_LIGHTS_PER_TILE)
        {
            bool inFrustum = true;
            for (uint i = 3; i >= 0 && inFrustum; i--)
            {
                float dd = dot(frustumPlanes[i], view * vec4(p.position, 1.0f));
                inFrustum = (dd >= -p.radius_length);
            }

            if (inFrustum)
            {
                uint id = atomicAdd(pointLightCount, 1);
                pointLightIndex[id] = lightIndex;
            }
        }
    }

    barrier();

```

In action:

http://www.youtube.com/watch?v=8SnvYya1Jn8&feature=youtu.be

---
Tags: opengl, glsl, tiles, deferred-rendering, frustum
---


# Question
Title: Show message to one player issue in multi-player game
I Needed to show message to only one person of the multi player game,i am using smartfoxserver to developed a board based game and in this game how to differentiate 2 players in unity c#,and also how to display any messages to single person in unity c#, i am new from unity so please help me.

# Answer
I am using SmartFoxServer with Java and JavaScript so I do not really know if this is going to work for you. You should create an EventListener for "click". So like you said, when player 1 is playing and player 2 is click on the board you should send from client 2 (player 2 ) a message to the server with a Command ( for example "CLICK\_BOARD" ). Than you create a handle request function on your server to get the request you allready send form the client. In this Function you can use check for the command. If you get the command "CLICK\_BOARD" than you send back to the client another COMMAND with the name "WRONG\_TURN". On client side when you get this COMMAND you event listener will trigger a function. This function should show the message.

I hope you undestand my ideas.
> 0 votes

---
Tags: c#, unity, multiplayer, smartfox
---


# Question
Title: Why might a Projectile hitting a KActor only call HitWall, and not ProcessTouch?
I have a `Projectile` subclass that seems to work fine. It travels, does `Explode()`, etc. But when it hits one of our `KActors`, I get a `HitWall` event but *not* a `ProcessTouch` event.

So my question is, why would a colliding actor trigger `HitWall`, but not `ProcessTouch`?

# Answer
> 1 votes
From a forum post, it seems there are a few default settings that need to be changed in order to get all the events. Setting `bBlockActors=false` and `BlockActors=false` appeared to solve this problem for someone else experiencing a similar problem.

---
Tags: udk
---


# Question
Title: Implementing David Silver's Cooperative Pathfinding in Real-Time
I'm currently implementing David Silver's Cooperative Pathfinding algorithm for a 2D game with grid-based movement (all eight directions).

The issue I'm having trouble wrapping my mind around is the Reservation Table with respect to real-time. I've fully implemented the algorithm in its own testbed; however, my implementation is turn-based where everybody is moving at the same speed.

The game I'm trying to integrate the group pathfinding into has real-time movement with units having different speeds.

---

I've compiled a few considerations I need to take into account and some that could help me implement this:

1. Enemies do not seek the player's character
2. However, some enemy units will wander
3. Enemies will have a different movement speed depending on enemy type
4. The player moves the avatar by clicking the destination (this initiates a walk)
5. The player can start start running by double clicking a destination (this can happen in-between grid nodes)
6. The player has allies that follow the avatar
7. Allies will run to keep up with the avatar if too far away and start walking again if close enough (this can also happen in-between grid nodes)
8. Speeds are not perfect multiples of each other

---

With those in consideration, my current partial solution consists of the following:

* Because of consideration 1 and 2, enemies will share reservation tables since I can have them move on the same intervals so their times will match up
* Because of considerations 3 and 8, the enemies' reservation tables will differ by movement speeds. *I am thinking of doing it this way because I'm not sure how to use one reservation table for all of them if their speeds are not perfect multiples of each other.*
* Because of the speed-change considerations of 4, 5, 7, and 8, the player's and allies' paths will be recalculated whenever they start walking or start running since that will affect path coordination.
* Because paths can be recalculated for the player avatar on the fly, I will need to have two reservation tables specifically for the player (one for walk, one for run). I would also possibly need to have two reservation tables for the allies to share (one for walk, one for run).
* Because of the fact that paths can be recalculated in-between nodes, I believe I will have to limit changes of speed to only occur when a unit is directly on a node rather than being able to change speeds in-between nodes as it currently works. *Otherwise, I believe I would have to calculated the time it will take to reach the next node and then track that in the reservation table as well somehow.*

---

Finally, here are things I'm wondering about:

* I must be not understanding the Reservation Table completely if coordinating units is this difficult. How do I define the time of a node in the Space-Time map if not by how long it takes one unit to get from one node to another?
* Is diagonal movement going to be an issue when defining the time of a node in the Space-Time map?
* Is there an easier way to handle implementing this short of implementing a different group pathfinding algorithm?
* If there is another pathfinding algorithm you recommend, I am all ears, but at this point in development, there most likely isn't any time to implement something new unless coding it as well as integrating it into the game would take less time than jamming the already-coded algorithm into the game.

---

Feel free to suggest ways of slightly altering how enemies, the player, and the allies move if that will make implementing this significantly easier. I appreciate any help you feel like offering. Thanks for your time!

# Answer
Not being familiar with this approach prior to reading the linked document, it seems like the confusion comes from using multiple reservation tables. That would be missing the point of having a reservation table. You could prevent collisions between units of the same type, but a fast unit and a slow unit trying to cross the same space could still end up in a collision reaction dance as they attempt to move through each other. Further, page 11 of the linked pdf addresses that specific issue stating they are expected to share a reservation table.

If your design calls for a friendly unit to be able to run past a group of enemy units, allies and enemies will share a reservation table as well. If you specifically want them to do a collision dance when they're close together, maybe you could use separate tables for each group, but I would still think it's preferable to keep all their pathing on the same reservation table and rely on behavioral logic to determine if they stop to interact, or continue moving. By which I mean you could hack some of your logic by intentionally pooching the pathfinding, but I very strongly recommend against it.

I think I see where the uncertainty is coming in for diagonal moves, or different speed multiples, but again the pdf would indicate continuing to use the same reservation table, and reserving a larger space for units whose movement speeds do not fit cleanly into the interval established by the table. If a unit is moving diagonally and will partially occupy multiple tiles during some portion of the reservation table, reserve all those tiles for that interval. If, x seconds from now, a faster or slower unit will be partially in one tile and partially in another due to moving at a speed that is not a clean multiple of the interval used in the table, reserve both tiles.

Finally, a change in unit speed from running to walking should not generate a second reservation table, it should refresh that unit's path along the one reservation table all units share.

The only case where I would think it to be appropriate to have multiple reservation tables is if you have different movement elevations (in a 2D game, or 3D rendered game where movement is restricted to 2D planes) where flying units can pass over the heads of ground units without colliding. In a full 3D game, you would use a 4D reservation table.

It might help to do some reading into animation. Conceptually, the reservation table shares (in my mind) some elements with animating a vertex that is expected to move from this point to that, starting at this time, ending at this time, while the game clock is all but guaranteed to *not* update perfectly in time with the model's keyframe intervals.
> 3 votes

---
Tags: algorithm, ai, movement, path-finding
---


# Question
Title: How should I track real-time resource generation in a client-server scenario?
I am currently building a game that has a "City" entity. These cities generate and consume resources such as food variably over a period of time. I need to be able query the server often to find exactly how much food the city at any given point. These queries can take place multiple times per minute. There could also be 400,000 cities to track at a given time.

How would you handle tracking these resources? Would you do it in real time, keeping an instance of the city in memory on the server, with some sort of a snapshot in time of the resources, then computing the growth/consumption from that snapshot time for subsequent queries? Would you work exclusively with a database, using a similar "snapshoting" scheme? Maybe a mixture of the 2, caching recently queried cities in memory for a period of time?

There is also a lot of other data that each city needs to track. A player can queue units to build in a barrack. The armies available in the city will need to be updated as units complete.

I'm interested in everyone's input on where/when/how you'd manage the real time data.

# Answer
For a system this large it would be wise to use a combination of strategies. Here are a few strategies that I would employ:

* Only process a city when absolutely required
    + Update values only when they're needed. Like being viewed by the user or needed in another calculation
    + Use formulas that take time as an input. For example, the population of a city should be defined by a few variables and the time span since it was last updated. This allows you to only update the population values when they're needed and you're not required to continually update them to "keep up".
* Use timed events to trigger calculations instead of checking to see if they need updating every iteration. For example, when building units.
    + Even if the timer is only a few seconds, this is better than checking or updating a value every frame in the interim.
* Simplify the data for each city to the absolute minimum needed. Try to base other values off of existing values.
    + For example, instead of calculating and storing the productivity of a city every time it's updated, calculate the productivity based off the population the their moral. This allows you to get the productivity when you need it, without needing to save it or calculate it unnecessarily every update.
> 2 votes

---
Tags: game-mechanics, mmorts
---


# Question
Title: How do I define spawn patterns for a Fruit Ninja-esque game?
I'm creating a game somewhat similar to Fruit Ninja and others, where bombs are thrown up on the screen and you click or touch them to defuse (here is an example of the game).

There are four bomb spawn points and I want to pre-define launch patterns that are interesting and challenging to the player. I'm struggling to think of a good way of defining this data.

How can I pre-define launch times for up-to 4 spawn points in a way that the data is human-readable (so that I don't have to spend too long tweaking each value)?

# Answer
> 1 votes
I would use a strategy similar to one defined in this question and answer. The sequence for spawning these patterns of bombs is very similar since it will also be time and pattern based.

Alternatively, you can define these patterns in a custom format of your own. Using a text file to make things very simple. For example, with the 4 spawner example, you could have a text file like this to spawn various patterns:

```
 1

 1 1

 1   1

 1     1

 1     1

   1 1

 1   1

   1   1

       1

```

It would be simple to define different numbers of different types of bombs and add new lines for spacing. Additionally, some meta data about the tempo of how the pattern should play could be included at the top of the file.

---
Tags: data-structure
---


# Question
Title: How can I extend btCollisionAlgorithm to enable collision with a voxel terrain?
I am using Bullet, and am attempting to make a collision algorithm that generates contact points off of a cube-based terrain along with the appropriate collision response. I also plan to extend this to include non-box shapes too, however that is not vital at the moment. I've found that using a triangle mesh is too much of a RAM hog for large maps.

I have tried the procedure outlined by Byte56 here, however, I have a number of questions regarding implementing this with Bullet:

* How do you generate a collision shape for the world? Do you use a custom shape? What do you set `m_shapeType` to be on it?
* Or do you still use a box shape the size of the world?
* How do you ensure that contact points are freed?
* How exactly do you modify `processCollision`?

What I've done:

* I've created a terrainShape`that extends`btBoxShape`, the only difference being that`m\_shapeType = CUSTOM\_CONVEX\_SHAPE\_TYPE\`, in order for me to be able to register a new collision algorithm with the dispatcher for objects with only this shape.
* I've extended the `btRigidBody` class in a way similar to Byte56 in his question (see the link in the 2nd paragraph), however `checkCollisionWith(CollisionObject * co)` returns true if *any* voxel in the AABB of `co` is not air.
* I've extended the `btCollisionAlgorithm` class, in a way similar to `btCompoundCollisionAlgorithm`, with `processCollision` doing the following:

1. Check the colliding objects passed as arguments, and determine which is the terrain, and which is the entity.
    2. Clear the manifolds any child algorithms.
    3. Call `resultOut->setPersistantManifold(resultOut)`
    4. Generate new box shapes and transforms in the AABB occupied by the colliding entity, and then call `m_dispatcher->findAlgorithm`. Store the shape, transform and found algorithm in a Child Algorithm struct for each voxel within the AABB.
    5. Iterate over all child algorithms, calling `proccessCollision`.
    6. Iterate over all child algorithms, removing any now outside of the AABB of the colliding entity. (calling `~btCollisionAlgorithm()` then `m_dispatcher->freeCollisionAlgorithm()`)
    7. Call `resultOut->refreshContactPoints()`.

What works: `processCollision` is called whenever the player's AABB intersects with non-air voxels.

What doesn't: the collision response is just plain weird... The player entity starts levitating upwards. If it walks into something, it bounces off violently. Sometimes, it is unable to keep moving on one axis after walking into something. What I suspect is going on is that contact points are not being released after collision response, possibly due to the player entity always being in the world object's AABB. I am curious to see if I am barking up the right tree with respect to `processCollision`?

# Answer
Unfortunately I wasn't able to get reliable results from the method described in the answer you're referencing. Similar to you, I would get weird floating events, or situations where removing a voxel would cause objects floating on top of them to stay floating in air, or do a strange oscillating feather fall to the ground. I abandoned that strategy for a new strategy.

I started creating custom collision meshes for each chunk of voxel terrain. I do that with the `BvhTriangleMeshShape`. This works pretty well:

There are more details on the implementation of the custom collision meshes here.
> 2 votes

---
Tags: bullet-physics, voxels
---


# Question
Title: How to flip 2d skinned quadruped character?
just would like to know is flipping 2d skinned character with one of scale axis good way for left or right movement(flipping direction and animation)? Normal direction would change.(UPDATED) for example i have a 2d skinned dog, and i wanna dog move left when i press left with same animation as right direction. or is there any better way? Thanks.

# Answer
> 1 votes
When drawing the character, you can scale it to -1 along the x axis to perform a flip. Additionally, the `sprite` object has a `flip` function that will allow you to flip the sprite along the x or y axis.

It's a quick way to do left/right movement without redrawing everything. There are other ways to get this result (like creating new animations for the opposite direction), but if they're better or not is something only you can answer.

---
Tags: 2d, libgdx, skinning
---


# Question
Title: Why I am I told "Color0 is missing" when I run the following code?
In the code below, I want to draw a box on my screen. But when I run it, there is an error message:

> The current vertex declaration does not include all the elements required by the current vertex shader. Color0 is missing.

Here is the code in question:

```
    private SpriteBatch _sb;
    private Vector3 _position;

    public Vector3 Position
    {
        get { return _position; }
    }
    private Matrix _world;

    public Matrix World
    {
        get { return _world; }
    }
    private Texture2D _image;
    private VertexPositionColor[] _vertices;
    private short[] _indices;
    private Game _game;
    private IndexBuffer _ib;
    private VertexBuffer _vb;
    private BasicEffect _basicEffect;
    private BoundingBox _boundingBox;

    public BoundingBox BoundingBox
    {
        get { return _boundingBox; }
    }

    public Blackhole(Game game, Vector3 position, Matrix view, Matrix projection)
    {
        _game = game;

        _vertices = new VertexPositionColor[4];
        _vertices[0] = new VertexPositionColor(new Vector3(-100, 100, 0), Color.Red);
        _vertices[1] = new VertexPositionColor(new Vector3(100, 100, 0), Color.Green);
        _vertices[2] = new VertexPositionColor(new Vector3(100, -100, 0), Color.Blue);
        _vertices[3] = new VertexPositionColor(new Vector3(-100, -100, 0), Color.Yellow);

        _indices = new short[6];
        _indices[0] = 0; _indices[1] = 1; _indices[2] = 2;
        _indices[3] = 0; _indices[4] = 2; _indices[5] = 3;

        _vb = new VertexBuffer(game.GraphicsDevice, VertexPositionColor.VertexDeclaration, 4, BufferUsage.WriteOnly);
        _vb.SetData<VertexPositionColor>(_vertices);

        _ib = new IndexBuffer(game.GraphicsDevice, typeof(short), 6, BufferUsage.WriteOnly);
        _ib.SetData<short>(_indices);

        game.GraphicsDevice.SetVertexBuffer(_vb);
        game.GraphicsDevice.Indices = _ib;

        _basicEffect = new BasicEffect(game.GraphicsDevice);
        _basicEffect.View = view;
        _basicEffect.Projection = projection;
        _basicEffect.World = _world;
        _basicEffect.VertexColorEnabled = true;
        _basicEffect.TextureEnabled = false;

        RasterizerState newState = new RasterizerState();
        newState.CullMode = CullMode.None;
        game.GraphicsDevice.RasterizerState = newState;
        _boundingBox = new BoundingBox(new Vector3(_position.X, _position.Y, -1), new Vector3(-_position.X, -_position.Y, 1));
    }

    public void Update(GameTime gt)
    {
        _world = Matrix.Identity * Matrix.CreateTranslation(_position);
    }

    public void Draw(Matrix view, Matrix projection)
    {
        _basicEffect.View = view;
        _basicEffect.Projection = projection;

        foreach (EffectPass f in _basicEffect.CurrentTechnique.Passes)
        {
            f.Apply();

            _game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);
        }
    }

```

What is the cause of my error?

# Answer
> 1 votes
You never initialize `_vb` (your vertex buffer) anywhere in the code you provided.

If you do not construct the vertex buffer, it will be null and have no corresponding vertex declaration (the runtime will try to match the vertex declaration against the shader you've selected, fail to do so, and report that error).

# Answer
> 0 votes
It seems that you forgot to add the colors of the BasicEffect. In Microsoft's tutorial ( http://msdn.microsoft.com/en-us/library/bb203926.aspx), section 3 it is shown how to do that:

```
 basicEffect = new BasicEffect(graphics. GraphicsDevice);

basicEffect.World = worldMatrix;
basicEffect.View = viewMatrix;
basicEffect.Projection = projectionMatrix;

// primitive color
basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
basicEffect.DiffuseColor = new Vector3(1.0f, 1.0f, 1.0f);
basicEffect.SpecularColor = new Vector3(0.25f, 0.25f, 0.25f);
basicEffect.SpecularPower = 5.0f;
basicEffect.Alpha = 1.0f;

```

# Answer
> 0 votes
I somehow solve it by re-writing my code from different reference, even though I can't find the difference that caused this code didn't work.

This is the new one (in whole class version), in case someone can locate the difference.

PS : Just tweak a bit from `VertexPositionTexture` to `VertexPositionColor` and change some code. Maybe this isn't a correct answer to my question though, I posted it because mine succeeded with this (I originally want to achieve Texture, using color only to check my vertex first)

```
public class Blackhole
{
    Texture2D _texture;
    Matrix _view, _world, _projection;
    Vector3 _position;
    VertexPositionTexture[] _vertices;
    short[] _indices;
    IndexBuffer _ib;
    VertexBuffer _vb;
    BasicEffect _basicEffect;
    Game _game;
    float _scale;
    float _rotation;

    public Blackhole(Game game)
    {
        _game = game;
        Initialize();
    }

    public void Initialize()
    {
        _view = Matrix.CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0), new Vector3(0, 10, 0));
        _projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1, 1, 100);
        _world = Matrix.Identity;
        _scale = 2;
        _rotation = 0;
        _position = new Vector3(0, 0, 100);
        LoadContent();
    }

    protected void LoadContent()
    {
        _texture = _game.Content.Load<Texture2D>("blackhole");
        _game.GraphicsDevice.BlendState = BlendState.NonPremultiplied;
        _vertices = new VertexPositionTexture[4];
        _vertices[0] = new VertexPositionTexture(new Vector3(-1f * _scale, 1 * _scale, 0), new Vector2(0, 0));
        _vertices[1] = new VertexPositionTexture(new Vector3(1f * _scale, 1 * _scale, 0), new Vector2(1, 0));
        _vertices[2] = new VertexPositionTexture(new Vector3(1f * _scale, -1 * _scale, 0), new Vector2(1, 1));
        _vertices[3] = new VertexPositionTexture(new Vector3(-1f * _scale, -1 * _scale, 0), new Vector2(0, 1));

        _indices = new short[6];
        _indices[0] = 0; _indices[1] = 1; _indices[2] = 2;
        _indices[3] = 0; _indices[4] = 2; _indices[5] = 3;

        _vb = new VertexBuffer(_game.GraphicsDevice, VertexPositionTexture.VertexDeclaration, 4, BufferUsage.WriteOnly);
        _vb.SetData<VertexPositionTexture>(_vertices);

        _ib = new IndexBuffer(_game.GraphicsDevice, typeof(short), 6, BufferUsage.WriteOnly);
        _ib.SetData<short>(_indices);

        _game.GraphicsDevice.SetVertexBuffer(_vb);
        _game.GraphicsDevice.Indices = _ib;

        _basicEffect = new BasicEffect(_game.GraphicsDevice);
        _basicEffect.TextureEnabled = true;
        _basicEffect.World = _world;
        _basicEffect.Texture = _texture;

    }

    public void Update(GameTime gameTime, Matrix view, Matrix projection)
    {
        _rotation -= 1f;
        _world =
            Matrix.Identity *
            Matrix.CreateRotationZ(MathHelper.ToRadians(_rotation)) *
            Matrix.CreateTranslation(_position);

        _basicEffect.World = _world;
        _basicEffect.View = view;
        _basicEffect.Projection = projection;
    }

    public void Draw(GameTime gameTime)
    {
        foreach (EffectPass item in _basicEffect.CurrentTechnique.Passes)
        {
            item.Apply();
            _game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);
        }
    }
}

```

---
Tags: 3d, xna-4.0, vertex
---


# Question
Title: How can I rotate a bitmap without D3D or OpenGL?
I've just figured out on my own how to scale a portion of a bitmap using `PutPixel`. I would like to know the mathematical theory behind *rotating* a bitmap on my own, using per-pixel operations like `PutPixel`.

I am not interested in using OpenGL or Direct3D to accomplish this, I'd like to know what the fundamental math and programming technique behind the operation is?

# Answer
> 4 votes
Simple linear algebra will provide you the equations needed to rotate any given point `p` by some `angle` about the origin:

```
new_p.x = p.x * cos(angle) - p.y * sin(angle)
new_p.y = p.x * sin(angle) + p.y * cos(angle)

```

To instead rotate around some point other than the origin, say the point `q`, you first translate your point so as to shift the coordinate frame and make `q` the origin:

```
p.x = p.x - q.x
p.y = p.y - q.y

```

Then you perform the rotation as before:

```
new_p.x = p.x * cos(angle) - p.y * sin(angle)
new_p.y = p.x * sin(angle) + p.y * cos(angle)

```

Then you "undo" the translation:

```
new_p.x = new_p.x + q.x
new_p.y = new_p.y + q.y

```

Given a region (typically a rectangular one) of pixels that you want to rotate, and a location you want to rotate about (often the center of that region), you can apply the above process to *every* pixel in that region to find it's new, rotated location and use `PutPixel` or whatever equivalent to write the appropriate color value from the original location.

The typical way to do this is to represent the transformations as transformation matrices, which will allow you to easily compose the "translate, rotate, translate-back" idiom into a single matrix you can apply to many points.

Do note that you should perform the rotation into a temporary buffer of some sort *first* and only write back to the original bitmap until you've completed the computation of the new pixel locations and colors. If you do the operation directly onto the final bitmap, and your angle of rotation is small enough, you may end up with a "smeared" image because you wrote some of the earlier pixels over some of the later pixels and lost the original data of those later pixels.

# Answer
> 3 votes
First, I would like to point out that doing rotation for a bitmap image is slightly different from doing it in OpenGL or DirectX because the rendering API will usually take care of a lot of the details. Two reasons why this is the case

* Using a rotation matrix that have a sin/cos will often result in fractions that cannot be indexed directly in the buffer. So some kind of interpolation is needed to determine the final pixel position. Otherwise the final image will have black spots.
* The rotation image will often have a bigger rectangular buffer than the original image. This is because a bitmap image is represented as an array of pixels. Otherwise, if you use the same buffer size you may end up with a cropped image.

So you need an algorithm to address those problems. The approach is often called **Image Rotation via Inverse mapping**.

1. The algorithm starts with the destination image buffer, by taking the destination image pixels and getting their value from the original image. This is done by transforming each destination pixel back by the inverse rotation, and then looking up the original value. *Keep in mind that rotation matrix inverse equals its transpose so you don't actually need to calculate the inverse.*
2. Next the resulted pixel position might not have a direct pixel position corrosponding to it in the original image. You need to interpolate the result value/index in the original image to make sure that the destination pixel have a value, for example if the result index is (5.5,6.5) one possibility is to take the nearest neighbor to that pixel.

This image is taken from this slide show

```
foreach destPixel in DestImage:
ApproxOriginaPixel = Rotate(destPixel, inverseAngle);
value = Interpolate( OriginalImage, ApproxOriginaPixel );
destPixel  = value;

```

Now regarding the buffer size you can use the same original buffer size, or calculate the new buffer size so you don't get a cropped image.

---
Tags: c++, sdl, pixel, image-processing
---


# Question
Title: How can I determine trajectory from distance and time, without initial velocity?
I'm attempting to develop a Mortar that needs to lead it's shot to the target enemy. The shot will have a pre-determined constant flight time of (2.5 seconds) and it will have where the enemy should be after that time (if the enemies motion is constant).

I'm struggling to figure out the proper equation to get initial velocity (and fire angle required) from just the distance from the predicted location, and the amount of time taken (2.5 seconds).

# Answer
Sorry if this answer is a bit too general, but to be more specific I would have to know whether this takes place in 2 or 3 dimensions, whether the world is flat, etc.

For any projectile motion calculation, it is easiest if we analyse each axis (dimension/component) separately. The two equations used here are:

`d = u * t` (for no acceleration)

`d = u * t + 1/2 * a * t^2` (for the vertical component, where gravity is acting)

I will also use 'u' to represent the initial velocity, 'a' to represent acceleration and 'g' to represent acceleration due to gravity (approximately 9.8 meters per second squared).

Hopefully you have some basic understanding of vectors and kinematics, if not, let me know and I'll fill you in on what you need to know.

From here forth, I will assume that you have two horizontal axes and one vertical axis.

Given that there is no acceleration occurring in the horizontal axes (other than friction, but in the context of a game, it becomes computationally very expensive to calculate this), the initial velocities along each axis are given by:

`u = d/t`

where d is the distance traveled along that axis and t is the time taken to travel this distance.

In the vertical axis, the initial velocity is given by:

`u = d/t + gt/2`

where d is the vertical offset of the final position from the initial position.

Since you specifically asked to find the angle at which the projectile should be shot, the workings are provided below:

horizontal component distance = `sqrt(ux^2 + uy^2)`

where ux and uy are the initial velocities in each axis (assuming z is vertical).

angle from horizontal = `arctan( uz / (sqrt(ux^2 + uy^2)) )`

If your terrain is flat, then `uz = gt/2`, and you can ignore vertical displacement.

If your game is side-scrolling, then there will be only one horizontal axis.

If your game takes place on another planet, uses non-realistic velocities or the shell seems to travel strangely, try using a value other than 9.8 for g.

Hopefully this helps you out, and if you have any further questions, just leave a comment on this answer.

EDIT: Added code formatting for legibility
> 1 votes

# Answer
A quick google search gives you all the equations you'll need. Obviously you'll still need to account for external forces, but this should get you started.

As for the angle, break the velocity into its components of x and y. These should create a nice right angle you can apply trig functions to.
> 0 votes

# Answer
(this is a clarification of the equation in peter's answer)

There is a very simple way to calculate the initial velocity.

using the equation `D = V * t + (1/2) * a * t ^ 2` as mentioned in Peter's answer is all you need.

* V - initial velocity vector of projectile. This is our unknown variable.
* D - vector representing the displacement between your point and the target point
* a - vector acceleration: Earth gravity will be (0,0,-9.8) in terms of meters per second squared, or the equivalent in your choice of units are.
* t - 2.5 seconds

(assuming a Z coordinate facing up)

If on level ground, `D.z = 0`, then `V.z` would simply be `a.z / 2 / t`. You could also use other values of D.z to simulate firing at an uphill/downhill target.

The x and y coordinates V would simply be chosen so that the V.x * t = D.x and V.y * t = D.y, since horizontal acceleration is zero.

If you want angle above horizon, that's just atan(V.z / sqrt(V.x^2 + V.y^2));
> 0 votes

---
Tags: mathematics, physics, projectile-physics, trajectory
---


# Question
Title: Variables in static library are never initialized. Why?
I have a bunch of variables that should be initialized then my game launches, but must of them are never initialized.

Here is an example of the code:

**MyClass.h**

```
class MyClass : public BaseObject {
    DECLARE_CLASS_RTTI(MyClass, BaseObject);
    ...
};

```

**MyClass.cpp**

```
REGISTER_CLASS(MyClass)

```

Where REGISTER\_CLASS is a macro defined as follow

```
#define REGISTER_CLASS(className)\
class __registryItem##className : public __registryItemBase {\
    virtual className* Alloc(){ return NEW className(); }\
    virtual BaseObject::RTTI& GetRTTI(){ return className::RTTI; }\
}\
\
const __registryItem##className __registeredItem##className(#className);

```

and `__registryItemBase` looks like this:

```
class __registryItemBase {
    __registryItemBase(const _string name):mName(name){ ClassRegistry::Register(this); }
    const _string mName;
    virtual BaseObject* Alloc() = 0;
    virtual BaseObject::RTTI& GetRTTI() = 0;
}

```

Now the code is similar to what I currently have and what I have works flawlessly, all the registered classes are registered to a ClassManager before `main(...)` is called. I'm able to instantiate and configure components from scripts and auto-register them to the right system etc...

The problem arrises when I create a static library (currently for the iPhone, but I fear it will happen with android as well). In that case the code in the `.cpp` files is never registered.

Why is the resulting code not executed when it is in the library while the same code in the program's binary is always executed?

---

**Bonus questions**:

For this to work in the static library, what should I do?

* Is there something I am missing?
* Do I need to pass a flag when building the lib?
* Should I create another structure and init all the \__registeredItem##className using that structure?

# Answer
This answer actually fixes the issue:

> > Use the -all\_load linker option to load all members of static libraries. Or for a specific library, use -force\_load path\_to\_archive.
> >
> > In Xcode, you'll want to add these options under "Other Linker Flags" for your executable (not your static library).
> 3 votes

# Answer
My guess is that none of those static library variables are used directly by the executable. The compiler likes to optimize these situations by removing the initialization code of unused variables.

For this thing to work, you have to at least touch each variable (do a read/write that cannot be optimized out\*) that you want initialized from all static libraries. This basically means creating a function in the library that touches all variables and is called from the executable, somewhere before the point the variables are actually used for the first time.

\*- Since this task heavily depends on compiler type, settings and many other things, I'll leave it up to you. For starters, you could try printf'ing some of the contents of those variables.
> 4 votes

---
Tags: c++
---


title: Unity Frustum Culling Issue

text:
# Question
Title: Unity Frustum Culling Issue
I'm creating a game that utilizes off center projection. I've got my game set up in a CAVE being rendered in a cluster, over 8 PC's with 4 of these PC's being used for each eye (this creates a stereoscopic effect). To help with alignment in the CAVE I've implemented an off center projection class.

This class simply tells the camera what its top left, bottom left & bottom right corners are. From here, it creates a new projection matrix showing the the player the left and right of their world. However, inside Unity's editor, the camera is still facing forwards and, as a result the culling inside Unity isn't rendering half of the image that appears on the left and right screens.

Does anyone know of a way to to either turn off the culling in Unity, or find a way to fix the projection matrix issue?

# Answer
> 1 votes
I just made a blog post on how to disable frustum culling on a game object in unity:

http://allenwp.com/blog/2013/12/19/disabling-frustum-culling-on-a-game-object-in-unity/

```
// boundsTarget is the center of the camera's frustum, in world coordinates:
Vector3 camPosition = camera.transform.position;
Vector3 normCamForward = Vector3.Normalize(camera.transform.forward);
float boundsDistance = (camera.farClipPlane - camera.nearClipPlane) / 2 + camera.nearClipPlane;
Vector3 boundsTarget = camPosition + (normCamForward * boundsDistance);

// The game object's transform will be applied to the mesh's bounds for frustum culling checking.
// We need to "undo" this transform by making the boundsTarget relative to the game object's transform:
Vector3 realtiveBoundsTarget = this.transform.InverseTransformPoint(boundsTarget);

// Set the bounds of the mesh to be a 1x1x1 cube (actually doesn't matter what the size is)
Mesh mesh = GetComponent<MeshFilter>().mesh;
mesh.bounds = new Bounds(realtiveBoundsTarget, Vector3.one);

```

---
Tags: unity, culling, frustum
---


# Question
Title: Models are not rendered correctly. OpenGL
I'm working on my university OpenGL project and as a base of it I'm trying to combine several OpenGL tutorials, mainly tutorials from http://ogldev.atspace.co.uk/.

The problem I have is that models I'm rendering are not rendered properly. I don't want to create a post with a wall of code so I'm just supplying a screenshot and main rendering loop, hope that some of you recognize where the error might be or have some guesses. If you need any particular part of the code please let me know.

I am using OpenGL 3.3 and SDL2 for window management.

Rendering loop:

```
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {

        glm::mat4 world_matrix = glm::scale(glm::vec3(1, 1, 1));
        world_matrix *= glm::rotate(world_matrix, 90.0f, glm::vec3(1.0, 0.0, 0.0));
        world_matrix *= glm::translate(glm::vec3(i * 50, j * 50, 0));

        //set methods of m_pEffect object set uniform values for the shader.
        m_pEffect->SetModel(world_matrix);
        m_pEffect->SetView(view);
        m_pEffect->SetProjection(projection);

        m_pMesh->Render();
    }
}

```

Vertex shader:

```
#version 330

layout (location = 0) in vec3 Position;
layout (location = 1) in vec2 TexCoord;
layout (location = 2) in vec3 Normal;

uniform mat4 mProjection;
uniform mat4 mView;
uniform mat4 mModel;

out vec2 TexCoord0;
out vec3 Normal0;
out vec3 WorldPos0;

void main()
{
    gl_Position = mProjection * mView * mModel * vec4(Position, 1.0);
    TexCoord0   = TexCoord;
    Normal0     = (mModel * vec4(Normal, 0.0)).xyz;
    WorldPos0   = (mModel * vec4(Position, 1.0)).xyz;
}

```

# Answer
> 0 votes
Changing `mProjection * mView * mModel` to `mModel * mView * mProjection` should solve the problem in this case but it's not a general rule. Here is why:

Some math facts first, for matrix multiplication `A * B != B * A`; also `A * B = transposed(B) * transposed(A)`

So when you take a tutorial or code and you see in code `MatrixA * MatrixB` and you want to do the same in the shader you have to think how `MatrixA` and `MatrixB` will end up in the shader code (transposed or not transposed). If it will end up transposed then you need to do `MatrixB * MatrixA` to achieve the same result, otherwise A * B.

If a matrix ends up transposed or not is dependent on the rendering Api and the matrix library you used. When you sent the matrix to the shader the api will copy a series of floats and interpret that as a matrix, but it doesn't know if the first **4 floats represent a column or a row** in the matrix.

# Answer
> 0 votes
It's hard to tell from the picture, but I've had errors before that looked like this and it had to do with rendering models using indices. If you are using short integers for your index element buffer you might want to try to use a regular unsigned int. If your model has more than 65k vertices then when you render using something like glDrawElement() you will get the resulting problem.

---
Tags: opengl, rendering, glsl
---


# Question
Title: Why do my velocity estimates have such a large margin of error
I am writing a script in unity that applies a force to the object to advance it a set distance in an environment without friction or drag, producing a cosine force curve.

However, as the target approaches the destination, the force to apply is less than the value specified by the curve as the time unit is too large and will cause the object to reverse direction.

To resolve this, I estimate what the speed will be after applying this frames force and, if that reverses the direction, we take a proportion of the force.

It is working well around 4 times out of 5, but every so often it will not detect the reverse in direction and will apply the force for an extra frame or 2, causing the object to back up.

Closer investigation revealed that basically the problem stems from my estimate being significantly (some times up to 0.05) different from the velocity the next frame. I compute it as follows:

```
Vector3 currentVelocity = ship.rigidbody.velocity;
Vector3 direction = ship.transform.right;

// this is the value I use for the "actual" speed
float velocityAlongDir = Vector3.Dot(currentVelocity, direction);

// this is my estimate
float estimatedVelocity = velocityAlongDir + (applyingForce * lDeltaTime);

```

Where the `applyingForce` is applied thus:

```
ship.rigidbody.AddForce((applyingForce * ship.rigidbody.mass) * transform.right);

```

Some sample data:

```
Predicted velocity: 0.3048308
Actual velocity: 0.2880591
Predicted velocity: 0.2068605
Actual velocity: 0.1900333
Predicted velocity: 0.09798826
Actual velocity: 0.1900333
Predicted velocity: 0.1082982
Actual velocity: -0.007007703

```

As you can see by the last entry, the predicted value doesn't change sing, but the real value does. Trying to work around this using does it go below a small value get different problems where the current velocity is too small etc.

Any idea why my calculation for next frame velocity seems so wrong and is there anything I can do about it?

**Update**

As pointed out in the comments, I needed to apply the force in the `FixedUpdate` and calculate my next frames velocity using `Time.fixedDeltaTime`. However, the following can happen, presumably in adverse frame conditions:

```
Predicted Velocity: 15.67547
Actual Velocity: 15.67547
Predicted Velocity: 17.54726
Actual Velocity: 15.67547 // note the same as the previous update, there has been no physics step!
Predicted Velocity: 17.51759 // estimate is subtly different, because my own timer has advanced

```

I fixed this by using `fixedTime` as opposed to `fixedDeltaTime`. However, then when I do a double update I am wrong for that frame, its like the physics step is trying to make up for the lost time:

```
// all going well...
Predicted Velocity: 52.25977
Actual Velocity: 52.25977
Predicted Velocity: 52.40138

// the estimate is wrong, we are moving at the same speed => no physics update
Actual Velocity: 52.25977
// we predict the same velocity for next frame
Predicted Velocity: 52.40138
// but we are wrong, like it is trying to catch up for lost time
Actual Velocity: 52.543

// then after that point we are precisely right
Predicted Velocity: 52.66479
Actual Velocity: 52.66479

```

This wouldn't be an issue except in the edge case where we do this double step precisely at the point we need to detect when the speed will change and apply the ratio. Since the physics step seems to play catch up, I miss the fact we changed speed.

# Answer
I resolve this (and a related question I asked on SO) as follows.

The first issue, as AdamS pointed out was that I was applying the force in the Update not the FixedUpdate. This resolved the large discrepancies originally posted.

The second issue, where it wouldn't do an FixedUpdate came from the fact that I was still advancing the time as if it had done a fixed update each update, so I used fixedTime so I could tell if there had been an update.

The last case (in this question) came from the fact the forces were accumulating so when there had been 2 updates between fixed updates, it was applying double the force.

This caused its own issues as, because the forces were only being applied per fixed update, low frame rate would cause the ship to not go fast enough (see SO question).
> 2 votes

---
Tags: c#, unity, physics, unityscript
---


# Question
Title: Entity System Texture Rendering Performance Java
I use Artemis and LibGDX. I have the following two components which manipulate a texture:

* ComponentTexture // Stores the texture
* ComponentSource // Define a region for the texture, that will only be shown
* ComponentSize // The size of the texture
* ComponentMirror // Stores wether you want to flup on x and y axe
* ComponentOrigin // The origin of the texture
* ComponentPosition // The position of the texture
* ComponentRotation // Rotation of the texture
* ComponentScale // The scale of the texture

Than I have a System that requires the Texture and position component(Thats the minimum to draw a texture) and draw them to screen, before I render I check if it has some possible extra components.

```
@Override protected void process(Entity entity)
{
    final ComponentTexture  componentTexture    = mComponentTextureMapper.get(entity);
    final ComponentSource   componentSource     = mComponentSourceMapper.getSafe(entity);
    final ComponentSize     componentSize       = mComponentSizeMapper.getSafe(entity);
    final ComponentMirror   componentMirror     = mComponentMirrorMapper.getSafe(entity);
    final ComponentOrigin   componentOrigin     = mComponentOriginMapper.getSafe(entity);
    final ComponentPosition componentPosition   = mComponentPositionMapper.get(entity);
    final ComponentRotation componentRotation   = mComponentRotationMapper.getSafe(entity);
    final ComponentScale    componentScale      = mComponentScaleMapper.getSafe(entity);

    // Texture
    final Texture texture = componentTexture.getTexture();

    // Source
    final Rectangle source;
    if(componentSource == null)
    {
        source = new Rectangle(0, 0, texture.getWidth(), texture.getHeight());
    }
    else
    {
        source = componentSource.getSource();
    }

    // Size
    final Vector2 size;
    if(componentSize == null)
    {
        size = new Vector2(texture.getWidth(), texture.getHeight());
    }
    else
    {
        size = componentSize.getSize();
    }

    // Mirror
    final boolean mirrorX;
    final boolean mirrorY;
    if(componentMirror == null)
    {
        mirrorX = false;
        mirrorY = false;
    }
    else
    {
        mirrorX = componentMirror.isMirrorX();
        mirrorY = componentMirror.isMirrorY();
    }

    // Origin
    final Vector2 origin;
    if(componentOrigin == null)
    {
        origin = new Vector2(0, 0);
    }
    else
    {
        origin = componentOrigin.getOrigin();
    }

    // Position
    final Vector2 position = componentPosition.getPostion();

    // Rotation
    final float rotation;
    if(componentRotation == null)
    {
        rotation = 0;
    }
    else
    {
        rotation = componentRotation.getRotation();
    }

    // Scale
    final Vector2 scale;
    if(componentScale == null)
    {
        scale = new Vector2(1, 1);
    }
    else
    {
        scale = componentScale.getScale();
    }

    mSpriteBatch.draw(texture, position.x - origin.x, position.y - origin.y, origin.x, origin.y, size.x, size.y, scale.x, scale.y, rotation, (int) source.x, (int) source.y, (int) source.width, (int) source.height, mirrorX, mirrorY);
}

```

I can create 5000 Entities with textures and a small rotation animation. I'm wondering about the efficiency of this method and how bad of a performance hit I will get from creating a lot of instances in the method. I plan to optimize this.

**Does anyone have a good idea as to how I can get better performance from drawing textures?**

**How I can avoid the check for every component that the entity has?**

**Thanks for reading :D**

# Answer
> 3 votes
You could create a single component to represent all of the information that a texture would hold. That way you aren't requesting 4 different components every time to go to draw something.

You listed having a transformation component. But you can use that component for all of the extra information you listed, rotations, flips, etc.. You can use a scale on the x or y in the transform that's negative as a "flipped" image and you just check the sign before you draw.

Only requesting two components and not worrying about "extra" components by storing all of that information in existing components would help. Also if you make one component that stores all of the "extra" information that a texture might have that would also reduce the overhead of component requests.

You can do more by passing an array or a container of the components you want to use to the function and looping over it rather than passing a single entity every time.

All of these things might make it faster but profiling would tell and if it's not a bottleneck now you shouldn't worry as much about it until it does become an issue.

# Answer
> 1 votes
First, echoing what Connor said. Breaking components up into a bunch of tiny attributes is a piece of bad advice I keep seeing repeated. You don't want mega-huge components that do 50 different things, no, but you absolutely do not want 50 micro components that all must be combined to do anything useful, especially as it just means your data is now spread all over the place instead of in one place. 1 component = 1 feature is a decent if somewhat loose guideline. Especially if you're sticking with an ECS, either going too large or too small negates any possible performance advantage (Java pushes you to go too small as you can't contiguously allocate user-defined types, unfortunately; C# is a much better choice for a Java-like language for games).

Second, you have `mSpriteBatch.draw(texture, position.x - origin.x, position.y - origin.y, origin.x, origin.y, size.x, size.y, scale.x, scale.y, rotation, (int) source.x, (int) source.y, (int) source.width, (int) source.height, mirrorX, mirrorY);` at the end there but I don't see it declared anywhere. The name indicates it's a member of... something. A single system maybe? Try to avoid using many different batches. It's hard to tell if you are or not.

# Answer
> 0 votes
OK, I made now, one Transform component:

Position, Origin, Rotation, Scale, Size

And a Texture component: Texture, Source, MirrorX, MirrorY

But it seems, that the performance is not better(5000 Entities are the maximum). You spoke from an profiler, I know what it is, but I have nether used one before. Knwo you a recommend profiler, which is easy to use ?

---
Tags: textures, rendering, performance
---


# Question
Title: Sphere turns to ellipsoid further away from origin (OpenGL ES 2, Android)
I'm not even sure what code to share, but maybe someone's been in a similar situation or has a good suggestion.

I'm basically rendering a sphere in the middle of the screen (placed at `(0, 0, 0)`) and it looks fine. However, if I choose to render the same sphere further away from the origin, it gets an egg shape. I think the egg shape is in the direction of the translation. Here's the code that sets up the model matrix:

```
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.scaleM(mModelMatrix, 0, 0.15f, 0.15f, 0.15f);
Matrix.translateM(mModelMatrix, 0, 0, 0, distance);

```

When `distance = 0`, the sphere shows up normally, however if `distance = -1.5f`, then the sphere is sort of stretched on the z axis. Any suggestions for fixing this behavior?

# Answer
> 0 votes
Scaling is based off the origin. Therefore you want to make sure to scale your object before translating it. Otherwise your scaling will be done as if the centre of the object is still (0.f, 0.f, 0.f).

---
Tags: opengl-es2
---


# Question
Title: Why are some of my normals facing away from the camera?
I'm trying to use WebGL to render some simple models, and I'm running into issues where pixels near the edge of my model are passing normals to my fragment shader that point away from the camera. This is of course messing with my attempts to use physically-based shading, because BRDFs are only defined in the hemisphere around the normal vector. These normals aren't just slightly pointing away from the screen; if that was the case, I would chalk it up to floating-point error and clamp to acceptable values. But some of my pixels have v-dot-n values of -0.5 or less.

This happens on pretty much any mesh I try to render. I have verified that my vertex normals point away from the mesh. I have backface culling turned on. This happens with both perspective and orthographic projections. I have tested in both Firefox and Chrome. Everything else about my render looks fine.

My vertex shader looks like this:

```
precision mediump float;

uniform mat4 M;
uniform mat4 V;
uniform mat4 P;

attribute vec3 vertexPos_model;
attribute vec3 vertexNormal_model;

varying vec3 pos_world;
varying vec3 normal_world;

void main() {
    gl_Position = P * V * M * vec4(vertexPos_model, 1.0);
    pos_world = (M * vec4(vertexPos_model, 1.0)).xyz;
    // We can use M here instead of its inverse transpose because it does not scale the model.
    normal_world = mat3(M) * vertexNormal_model;
}

```

And my fragment shader looks like this:

```
precision mediump float;

uniform vec3 cameraPos_world;

varying vec3 pos_world;
varying vec3 normal_world;

void main() {
    vec3 n = normalize(normal_world);
    vec3 v = normalize(cameraPos_world - pos_world);
    float vAngleCos = dot(n, v);
    // This will highlight pixels whose view vectors are outside of the hemisphere around n.
    gl_FragColor = vec4(vec3(clamp(-vAngleCos, 0.0, 1.0)), 1.0);
}

```

Rendering with the fragment shader above gives me results like this:

Apologies if I'm missing something obvious!

# Answer
> 4 votes
You are seeing interpolation artifacts. The surface normals between front and back faces are interpolated between front and back faces, leaving some of the fragments on visible faces having normals facing away from the camera.

Consider this crude drawing:

In this image A and B are your vertex normals while C is an interpolated surface normal between them. C in this case is pointing away from the camera, even though it is part of a front face.

---
Tags: opengl, glsl, webgl, normals
---


# Question
Title: How do I create a 'disable minimap' skill for a StarCraft 2 mod?
I would like to make a "disable minimap" type of skill, which when used will make an area of the minimap black (such that you can't see enemies or allies on the map). How can I accomplish this?

# Answer
> 2 votes
While I'm far from an expert on SC2 modding (having barely even played the game), I've stumbled across this question in the archives here several times and each time I've gone out researching ways in which this might be accomplished.

Unfortunately, every time I've come up empty, and I have to conclude at this point that it's not really possible to use the SC2 mod tools to blacken or "re-fog" a portion of the game.

I did some across this thread, however, which is about solving a problem of 'radar tower' like units, and which you may be able to modify to achieve something *similar* to what you want:

Make a unit with an event, when other units come within a certain radius of that unit, apply a visibility modifier to hide that unit. You'd need to do some further scripting to render the primary unit non-player-controllable, probably, and it won't replace the fog of war on the map, but it could result in making anything that walks into that range invisible, which may be close enough for your purposes.

---
Tags: starcraft-2
---


title: How can I implement a scanline effect?

text:
# Question
Title: How can I implement a scanline effect?
I am working on an old-school platformer in libgdx and I want it to have a "scanline" effect, like this:

My first attempt was to make a little texture and draw it on a full-screen quad. I used two different orthographic camera modes (one for the main tilemap of the game, and a second to render the scanline texture). Sometime the texture is stuck on the tilemap and sometime it is too large, and covers the whole screen in black.

Is my approach using two cameras and a texture reasonable? What's a good solution to achieve this effect?

# Answer
The problem with naively rendering a small scanline texture onto a large full-screen quad is that the texture will scale up, making what *was* a set of single-pixel scanlines in the texture much thicker, blurrier (depending on your interpolation method), and generally uglier.

You should instead *tile* the texture across the quad in such a way as to preserve a 1:1 pixel-to-texel ratio. This involves adjusting the quad's texture coordinates so that they are greater than 1 at the furthest extent, and also setting your textures wrap parameter to repeat instead of clamp. If your texture is 64x64 pixels, and your screen is 1024x768 pixels, you can figure that in the X axis you must tile the texture 16 times (1024 / 64). Similarly, on the Y axis you must tile it 12 times (768 / 64). You can adjust this math for the actual bounds of your texture and screen. Use those numbers (16 and 12) as the maximum extents of your quad's texture coordinates, and you'll get a much better result. Depending on how your orthographic projection is currently set up for the tiles, you may not even need to change it to render this.

Alternatively, you can take a shader approach: render your regular scene to a texture, then render that texture as a fullscreen quad, but omit every odd line of pixels. If you know the bounds of the screen in the shader, you can do this pretty easily (this is *pseudo-code*, vaguely HLSL-ish, but should translate easily):

```
float2    screenSize;
sampler2D textureSampler;
float2    textureCoordinate;

float4 main () {
   // Interpolation of texture coordinates means that we don't get nice
   // integer boundaries we could take the modulus of.
   float half_y = textureCoordinate.y * screenSize.y * 0.5;
   float delta = round(half_y) - half_y;
   float delta_squared = delta * delta;
   if (delta_squared < 0.1) {
      return texture2D(textureSampler, textureCoordinate);
   }

   return float4(0,0,0,0);
}

```
> 4 votes

# Answer
The problem with using a camera is that it will scale the image. What you essentially want is to always draw the same image at the same size (100%). I assume it's big enough to always cover the entire screen.

If this is the case, one solution would be to apply the inverse transformation of the camera on the image so that it draws at a "pixel perfect" size.

The easier option would be to scale it yourself. Eg. if your camera is zoomed to 75%, your image would be scaled to 133% (`1/0.75`).
> 0 votes

---
Tags: textures, libgdx, effect
---


# Question
Title: How can I control an object with tilt gestures?
I want an object (for example a ball) to move right when I tilt my Windows Phone device to the right. The same with the directions left, up and down. If the Windows Phone device isn't getting tilt in a direction, the object should rest in place.

How can I do that?

**Update:** I updated my code but it's still not working. The ball doesn't move if I tilt my Windows Phone device. In addition, the ball just moves continuously upwards.

What is wrong?

I don't know how to normalize the ball's velocity vector afterwards. How can I do that?

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Motion motion;
    Texture2D Ball;
    Vector2 BallPos = new Vector2(400, 300);
    Vector2 BallVelocity;
    float m_pitchForwardThreshold = 1f;
    float m_pitchBackwardThreshold = -1f;
    float m_speed = 0.5f;
    float m_rollForwardThreshold = 1f;
    float m_rollBackwardThreshold = 1f;

    void motion_CurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> e)
    {
        UpdateUI(e.SensorReading);
    }

    private void UpdateUI(MotionReading e)
    {
        float pitch = e.Attitude.Pitch;
        float roll = e.Attitude.Roll;

        if (pitch >= m_pitchForwardThreshold)
        {
           BallVelocity.Y = m_speed;
        }

        if (pitch <= m_pitchBackwardThreshold)
        {
            BallVelocity.Y = -m_speed;
        }

        if (roll >= m_rollForwardThreshold)
        {
            BallVelocity.Y = m_speed;
        }

        if (roll <= m_rollBackwardThreshold)
        {
            BallVelocity.Y = -m_speed;
        }

        BallPos = new Vector2(BallPos.X + BallVelocity.X, BallPos.Y + BallVelocity.Y);
    }

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        TargetElapsedTime = TimeSpan.FromTicks(333333);
        InactiveSleepTime = TimeSpan.FromSeconds(1);
    }

    protected override void Initialize()
    {
        if (Motion.IsSupported)
        {
            motion = new Motion();
            motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
            motion.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<MotionReading>>(motion_CurrentValueChanged);
            motion.Start();
        }

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        Ball = Content.Load<Texture2D>("BallSprite");
    }

    protected override void Update(GameTime gameTime)
    {

        base.Update(gameTime);
    }

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

        spriteBatch.Begin();
          spriteBatch.Draw(Ball, BallPos, null, Color.White, 0, new Vector2(Ball.Width/2, Ball.Height/2), 1f, SpriteEffects.None, 1);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

# Answer
> 0 votes
The Windows Phone `Motion` class can be used to read the current orientation (`CurrentValue`, which will be a motion reading) a yaw/pitch/roll attitude. The value of each measure will be in radians. The yaw/pitch/roll measurements are the same as those in traditional flight dynamics (so it's pitch and roll you want).

If you give your ball a velocity vector, you can then adjust that vector in your game's update logic for the ball based on the current values of the phone's attitude. For example, you might do something like:

```
// One-time setup...
var motion = new Motion();
var ball = new Ball();

// Elsewhere, in the update logic...
var reading = motion.CurrentValue as MotionReading;
if (reading != null) {
  var pitch = reading.Attitude.Pitch;
  var roll = reading.Attitude.Roll;
  if (pitch >= m_pitchForwardThreshold) {
    ball.Velocity.Y = m_speed;
  }

  if (pitch <= m_pitchBackwardThreshold) {
    ball.Velocity.Y = -m_speed;
  }

  // Repeat for roll...
}

```

In this scenario, the thresholds are used to check if the attitude measurement gets far enough out of the 'dead zone' of the normal orientation of the phone. I'm not familiar offhand with the way in which the radian values of this sensor will map to reality and the orientation of the device, so you'll need to do a bit of experimenting there, and also to find values that are comfortable for your game.

Do make sure to normalize your ball's velocity vector afterwards, if you choose to go *exactly* this route; otherwise applying both pitch and roll will make the ball move much faster. Or maybe that's what you want. Just be aware of it.

Another thing to be aware of with any motion-based controls is that a user may not always keep the device in a relatively fixed orientation while playing your game (they may transition from sitting to laying down, for example), which will not alter their *perception* of the device's orientation (relative to themselves) but will alter the device's absolute orientation in space. You need to be aware of this when using motion sensors, and perhaps rely on other sensors (such as the gyroscope, if available, or accelerometer) to help recalibrate your motion data when necessary. There are questions on that very subject floating around on this site, so you may want to search.

---
Tags: xna, c#, windows-phone-7, windows-phone-8
---


# Question
Title: character movement data passing on server
I am trying to build my first online game using unity with photon, the data transfer between server and clients is implemented but I am facing a great problem; How/What should be transferred to synchronise the movement data?

My game has a lobby and may have as many as 20 people online at the same time if I pass the position of every players to server and then server to clients, I believe the server would be overloaded, wouldn't it?

Hence I think an other way is to pass the movement of characters:
1) only when a player presses a movement key, then pass it to server and other clients,
2) if the player releases the key, then pass the position for validation.
It is workable? Will there any inconsistency between the clients?

I Hope someone can give me some advice, Thank you!

# Answer
> 0 votes
No, that's pretty much how it's done: everyone sends their input to the server, the server uses that to update the simulation, and then passes the world back to the client - perhaps an incremental update, or the subset each client sees, and so on.

I have the feeling this topic is more complex than you imagine right now. I've written at length on the topic of client/server multiplayer games here: http://www.gabrielgambetta.com/fast\_paced\_multiplayer.html It will help you with the problems you'll encounter shortly.

---
Tags: movement, server
---


# Question
Title: How can I create a shader that will reproduce this lighting effect on terrain?
Notice the way in which the major light source in each image reflects off the ground, as a function of the distance between the light source and the viewer (?).

Is this a (bumped) specular map? The effect is seen all over in World of Warcraft; I specifically remember it on the snow in Dun Morogh, and on the shores of Darrowmere lake. Looking directly toward the sun is required. The effect is also commonly on the surface of water in RL and in CG. Specifically, I want to build the effect where the reflection is more intense on the ground surface closer to the light source, and falls off as it approaches the viewer.

# Answer
> 14 votes
I imagine if I was going to build such a shader there are certain phenomenas that I will start with.

First the sunlight is directional, meaning it does't have position nor attenuation.

Second the diffuse component is simply calculated by taking a dot product between the sun direction and the surface normals, adding normal mapping might add to the detail.

The tricky part is modeling the sun directional specular component. So to achieve similar effect I would break it into smaller problems:

* The first is the microfacets of the surface this can be simulated using any variation of bump or normal mapping, this can be applied to both diffuse and the specular component.
* The second part is the uneven distribution of the specular lighting. This can be done using some kind of specular maps.
* Now the most tricky part is the directional specular map this can be achieved using Ward Anisotropic lighting model, which gives you two parameters to control the anisotropy of the specular reflection, namely `Ax, Ay` in the following Wards equation.

Where:

* The specular term is zero if dot(**N**, **L**) \< 0 or dot(**N**, **R**) \< 0.
* The vector **R** is the mirror reflection of the light vector off the surface.
* **L** is the direction from the surface point to the light.
* **H** is the half-angle direction.
* **N** is the surface normal.
* **X** and Y are two orthogonal vectors in the normal plane which specify the anisotropic directions, the tangent and bitangent vectors can be used as the `X,Y` vectors, especially that the tangent space is so common in computer graphics that could be calculated in any engine (usually calculated based on texture coords).

Notice in the image, how the specular lighting is directional unlike the common Phong specular light. Here is an article on the Ward model and how to achieve different effects. **EDIT** More information on the suitability of BRDF in terms reducing the light intensity closer to the viewer, can be found here.

Finally another (optional) two points that I guess could add to the final image,

* First I am sure using ambient occlusion will help getting more believable results.
* The second is that implementing some kind of Fresnel reflection could add a nice effect to the image, especially in water and ice scenes.

# Answer
> 3 votes
The reflection itself is just the specular reflection that you get as an output of the functions of your specific illumination model.

There are many different illumination models of varying levels of complexity that will produce a reflection shape similar to this, but a similar look to this can already be achieved with a simple bare bones blinn-phong lighting model, which is (now) probably the most basic lighting model used by graphics engines, and most likely also used by World of Warcraft.

It will not be physically correct and completely equal to your images, but it will look very similar. Concept3D's example of the Ward model is more physically correct and works for more complex surface types (namely, materials where the microscopic bumps in their surfaces are not uniformly distributed, but have different probability distributions), but I don't know of any concrete examples of real time renderers that use it, due to poor gains in terms of quality/performance.

In practice, such types of reflections on surfaces are supplemented by additional specular/gloss and normal textures, that modify the shininess/roughness of a surface, and the direction of the normals of the surface, respectively, which are both inputs to the lighting equations of typical lighting models. This is done because in the real world, the physical properties of surface most often (except for maybe something like plastic, or a mirror) don't stay the same all over the surface, but can vary wildly from pixel to pixel.

# Answer
> 0 votes
Specular bump mapping (normal mapping) or parallax mapping.

---
Tags: shaders, lighting, terrain-rendering
---