# Question
Title: Turning a board game idea into a browser based, slow paced gameplay
Suppose I want to create a strategy game with global mutable state shared between all players (think game board). But unlike a board game, I don't want it to be real time action and/or turn-based. Instead, players should be able to log in at any time of the day and spend a fixed number of action points per day as they wish. As opposed to a few hours, game sessions would run over a few weeks.

This is meant to reward good strategy rather than time spent playing (as an alternative, hardcore players could always play multiple games in parallel instead) as well as all kind of issues related to live playing like disconnections and synchronization. The game should remain addictive still have a low time investment footprint for casual players.

So far so good, but this still leaves open the question of *when* to solve actions and when they should be visible. I want to avoid "ninja play" like doing all your moves just a few minutes before daily point reset to take other players by surprise, or people spamming F5 to place a well-timed action which would defeat the whole point of a non real-time game.

I thought of a couple of approaches to that :

* Resolve all events in a single scheduled process running once a day. This basically means a "blind" gameplay where players can take actions but don't see their results immediately. The thing is, I played a similar browser game a few years ago and didn't like the fact that you feel disconnected and powerless until there's that *deus ex machina* telling you what really happened during all that time. You see the world evolve in large increments of one day, which often doesn't seem like seeing it evolve at all.
* For actions that have an big impact on the game or on other players (attacks, big achievements), make them visible to everyone immediately but delay their effect by something like 24 hours. Opposing players could be notified when such an event happens, so that they can react to it.

Do you have any other ideas how I could go about solving this ? Are there any known approaches in similar existing games ?

# Answer
> 2 votes
You could take some inspiration from the game Neptune's Pride which sounds a lot like you want to do - a board game, browser based, played over weeks.

To address your question:

> but this still leaves open the question of when to solve actions and when they should be visible

NP doesn't really 'delay' actions, but it makes them take a long time. For instance, moving spaceships between planets takes at least several hours. Some effects of the action of moving them are immediate: the spaceships stop defending the planet they departed from, and other players see your move, at the moment you play the action. Some effects take a long time: the ships attack the planet they move to, only hours after you did the action.

In addition, players are allowed to queue actions for their spaceships, so they don't have to log in every few hours to redirect them.

In the case of Neptune's Pride, this does not completely resolve the issue. Logging in regularly (every few hours) will have a clear advantage over logging in once a day. This might be partially unavoidable, but take a lesson from what NP did wrong in that regard: do not allow your players to upgrade the speed of their ships, or whatever the equivalent is in your game. Allowing players to circumvent the delay in any way may very well break the game again.

Note that NP does not have action points, but the idea is the same.

**Conclusion**: I'd advice you not to delay actions, but to simply make them take a long time (hours, days, up to you), during which other players can react.

# Answer
> 4 votes
Instead of completely refilling all players action points at a fixed time, you could instead give them a small amount of action points every few minutes and allow them to safe up action points up to one or a couple days worth of points.

A player who wants to do something big will have to safe their action points for about a day. Afterwards they will be unable to act again until their AP have refilled.

The web-based game Urban Dead, which simulates a zombie apocalypse with players playing both survivors and zombies, uses a mechanic like this. It does however miss the goal of being equally playable for both casual gamers and power gamers by offering certain actions which leave other characters in very vulnerable situations which can be resolved by the victim with minimal AP spending. This makes it useful for survivor-players to log in every few hours to check if the zombie players broke down the barricades of the building they are in (high AP investment for the zombies) and move to a different building (low AP investment for the survivor).

You could avoid this problem in your game by having player attacks cause damage to the victim, but not leave the victim more vulnerable to following actions by other players.

# Answer
> 3 votes
You might want to look at internet Diplomacy, which takes the simultaneous moves approach. Diplomacy assumes you will be discussing moves with other players, so you have some idea of what is going on even though you can't see actual moves (and other players may be lying to you about their plans).

I'm not sure whether this helps, but it's at least an example of a game that seems to work in a similar situation.

# Answer
> 1 votes
Each turn will last about a day, unless all players complete their turns. If all players in the current game have completed their turns, the next turn starts (players AP pools are refilled). This not only ensures everyone has a equal chance to spend their points, it automatically adjusts for the times players usually login and allows for more hardcore players to play through a game more quickly if everyone is completing their turns quickly.

# Answer
> 1 votes
The simplest answer:

* Update game state at a fixed time
* Let players make their moves at any time between updates, but do NOT show those moves until update occurs

Something you need to consider very strongly is that whatever model you choose must be very simple for players to understand. Anything that departs from the above isn't. A more complex rule set for moves would draw concentration to them at the expense of other parts of gameplay - so don't do that unless it is what you want.

---
Tags: game-design, browser-based-games, events, board-game
---


title: in-app purchase in cocosSd-x 3.0

text:
# Question
Title: in-app purchase in cocosSd-x 3.0
I am working within a team, and we're at the point of finishing our first cocos2d-x c++ application.

We want to add in-app purchases. for what, we made a search for this. We found 2 solutions:

1- The native solution

2- SOOMLA

What do you think about this, and according to you what is the best solution for in-app purchases with cocos2d-x.

Best regards.

# Answer
> 0 votes
I'm biased as i'm one of the creators of SOOMLA but I really think that SOOMLA is the better way to go because:

1. We did all the work of integrating to the IAP providers. We fought all the fights for you so you can easily add IAP into your game.
2. The economy model SOOMLA introduces is easy to use and makes things easier for you. It will also allow you to keep your users' balances in a dedicated storage and control your entire game economy.

Again, i'm one of the creators of the SOOMLA framework so my opinion is a bit biased BUT we really believe we make life easier for game developers.

---
Tags: android, ios, cocos2d-x
---


# Question
Title: Collision Detection on floor tiles Isometric game
I am having a very hard to time figuring out a bug in my code. It should have taken me 20 minutes but instead I've been working on it for over 12 hours. I am writing a isometric tile based game where the characters can walk freely amongst the tiles, but not be able to cross over to certain tiles that have a collides flag. Sounds easy enough, just check ahead of where the player is going to move using a Screen Coordinates to Tile method and check the tiles array using our returned xy indexes to see if its collidable or not. if its not, then don't move the character. The problem I'm having is my Screen to Tile method isn't spitting out the proper X,Y tile indexes. This method works flawlessly for selecting tiles with the mouse. ***NOTE: My X tiles go from left to right, and my Y tiles go from up to down. Reversed from some examples on the net.*** Here's the relevant code:

```
    public Vector2 ScreentoTile(Vector2 screenPoint) {
            //Vector2 is just a object with x and y float properties
            //camOffsetX,Y are my camera values that I use to shift everything but the
                //current camera target when the target moves
            //tilescale = 128, screenheight = 480, the -46 offset is to center
                // vertically + 16 px for some extra gfx in my tile png
    Vector2 tileIndex = new Vector2(-1,-1);

    screenPoint.x -= camOffsetX;
    screenPoint.y = screenHeight - screenPoint.y - camOffsetY - 46;

    tileIndex.x = (screenPoint.x / tileScale) + (screenPoint.y / (tileScale / 2));
    tileIndex.y = (screenPoint.x / tileScale) - (screenPoint.y / (tileScale / 2));

    return tileIndex;
}

```

The method that calls this code is:

```
    private void checkTileTouched () {

    if (Gdx.input.justTouched()) {
            if (last.x >= 0 && last.x < levelWidth && last.y >= 0 && last.y < levelHeight) {
                if (lastSelectedTile != null) lastSelectedTile.setColor(1, 1, 1, 1);
                Sprite sprite = levelTiles[(int) last.x][(int) last.y].sprite;
                sprite.setColor(0, 0.3f, 0, 1);
                lastSelectedTile = sprite;
            }
    }
    if (touchDown) {
        float moveX=0,moveY=0;
        Vector2 pos = new Vector2();

            if (player.direction == direction_left) {
                moveX =  -(player.moveSpeed);
                moveY =  -(player.moveSpeed / 2);
                Gdx.app.log("Movement", String.valueOf("left"));
            } else if (player.direction == direction_upleft) {
                moveX = -(player.moveSpeed);
                moveY = 0;
                Gdx.app.log("Movement", String.valueOf("upleft"));
            } else if (player.direction == direction_up) {
                moveX = -(player.moveSpeed);
                moveY = player.moveSpeed / 2;
                Gdx.app.log("Movement", String.valueOf("up"));
            } else if (player.direction == direction_upright) {
                moveX = 0;
                moveY = player.moveSpeed;
                Gdx.app.log("Movement", String.valueOf("upright"));
            } else if (player.direction == direction_right) {
                moveX = player.moveSpeed;
                moveY = player.moveSpeed / 2;
                Gdx.app.log("Movement", String.valueOf("right"));
            }  else if (player.direction == direction_downright) {
                moveX = player.moveSpeed;
                moveY = 0;
                Gdx.app.log("Movement", String.valueOf("downright"));
            }  else if (player.direction == direction_down) {
                moveX = player.moveSpeed;
                moveY = -(player.moveSpeed / 2);
                Gdx.app.log("Movement", String.valueOf("down"));
            }  else if (player.direction == direction_downleft) {
                moveX = 0;
                moveY = -(player.moveSpeed);
                Gdx.app.log("Movement", String.valueOf("downleft"));
            }
            //Player.moveSpeed is 1
                    //tileObjects.x is drawn in the center of the screen (400px,240px)
                    // the sprite width is 64, height is 128

            testX = moveX * 10;
            testY = moveY * 10;

            testX += tileObjects.get(player.zIndex).x + tileObjects.get(player.zIndex).sprite.getWidth() / 2;
            testY += tileObjects.get(player.zIndex).y + tileObjects.get(player.zIndex).sprite.getHeight() / 2;

            moveX += tileObjects.get(player.zIndex).x + tileObjects.get(player.zIndex).sprite.getWidth() / 2;
            moveY += tileObjects.get(player.zIndex).y + tileObjects.get(player.zIndex).sprite.getHeight() / 2;

            pos = ScreentoTile(new Vector2(moveX,moveY));
            Vector2 pos2 = ScreentoTile(new Vector2(testX,testY));

            if (!levelTiles[(int) pos2.x][(int) pos2.y].collides) {
                Vector2 newPlayerPos = ScreentoTile(new Vector2(moveX,moveY));
                CenterOnCoord(moveX,moveY);
                player.tileX = (int)newPlayerPos.x;
                player.tileY = (int)newPlayerPos.y;
            }
    }
}

```

---

When the player is moving to the left (downleft-ish from the viewers point of view), my Pos2 X values decrease as expected but pos2 isnt checking ahead on the x tiles, it is checking ahead on the Y tiles(as if we were moving DOWN, not left), and vice versa, if the player moves down, it will check ahead on the X values (as if we are moving LEFT, instead of DOWN). instead of the Y values.

I understand this is probably the most confusing and horribly written post ever, but I'm confused myself so I'm having a hard time explaining it to others lol. if you need more information please ask!! I'm so frustrated after over 12 hours of working on it I'm about to give up.

# Answer
I realize this question is over 2 years old, but I am going to answer it anyway.

Your screen dimensions are not equal in length and height and you are using screen dimensions to project into `levelTile`. When you scale both `moveX` and `moveY` by 10, it causes your forward projection to become skewed.

In order for your forward projection to be accurate there are a couple of solutions.

1)You could scale each component relative to the screens aspect ration. Looking at your comment, the screen is 800x480. 480/800 = 0.6.

```
testX = moveX * 10;
testY = moveY * 6;

```

2) Calculate the movement vector relative to the `levelTiles`, then scale that and test for collision.

```
Vector2 playerTile = new Vector2(player.tileX, player.tileY);
Vector2 moveToTile = ScreenToTile(new Vector2(moveX, moveY));
Vector2 tileMovementVector = playerTile - moveToTile;

// set the amount of forward projection (I am doubling the movement,
// but set this to what is relevant)
float projectionFactor = 2.0f;
Vector2 forwardTileProjection = tileMovementVector * projectionFactor;

if (!levelTiles[(int)forwardTilePojection.x][(int)forwardTilePojection.y].collides) {
   ...
}

```
> 2 votes

---
Tags: 2d, java, collision-detection, tiles, isometric
---


title: draw fog of war using shaders

text:
# Question
Title: draw fog of war using shaders
I am making a RTS game, and I'd like some advice on how to best render fog of wars, given what I'm already doing.

You can imagine this game as being a classic RTS like Age of Empires 2, where the fog of war will basically be handled by a 2D array telling if a given "tile" is explored or not. The specific things to consider here are :

1) I'm only doing a few draw calls to draw the whole screen, using shaders, and I'm not drawing "tile by tile" in a 2D loop

2) The whole map is much bigger than the screen, and the screen can move every frame or so

In that case, how could I draw the fog of war ? I have no issue maintaining on the CPU-side a 2D array giving the fog of war for each tile, but what would be the best way to actually display it dynamically ? thanks!

# Answer
> 1 votes
I'm not very sure of what type of fog you want to display, but if you want to do an AoEII fog, so a black fog, it would be something like that:

Your fog tileset:

And your code should be like that (it's pseudocode). Here I blit tile by tile but you can replace with your own technical:

```
Let fog[nTileX][nTileY] be your fog array
    // values: 1 discovered tile and 0 undiscovered

For i = 0; i < nTileX; i++
    For j = 0; j < nTileY; j++
        If fog[i][j] == 1 Then
            Blit your tile at pos (i, j)
        Endif
    Endfor
Endfor

For i = 0; i < nTileX; i++
    For j = 0; j < nTileY; j++
        If fog[i-1][j] == 0 Then
            If fog[i][j-1] == 0 Then
                Blit fog tile number 8
            Elseif fog[i][j+1] == 0 Then
                Blit fog tile number 5
            Else
                Blit fog tile number 1
            Endif
        Endif
        If fog[i+1][j] == 0 Then
            If fog[i][j-1] == 0 Then
                Blit fog tile number 6
            Elseif fog[i][j+1] == 0 Then
                Blit fog tile number 7
            Else
                Blit fog tile number 3
            Endif
        Endif
        If fog[i][j+1] == 0 Then
            Blit fog tile number 2
        Endif
        If fog[i][j-1] == 0 Then
            Blit fog tile number 4
        Endif
    Endfor
Endfor

```

If you want the tiles you already explored but where you are not present to be darkened, and with the building you saw when you explored, you can take a screenshot at each frame, and each new frame you add an alpha filter to it, and then you blit it after filling the screen of black.

---
Tags: opengl, shaders, graphics, fog-of-war
---


# Question
Title: Embed Unity3D and load multiple games from a single app
Is is possible to export an entire unity3d project/game as an AssetBundle and load it on iOS/Android/Windows on an app that doesn't know anything about such game beforehand? What I have in mind is something like the web plugin does - it loads a series of .unity3d files over http, and render inline in the browser window.

Is it even possible to do something closer for iOS/Android?

I have read a lot of docs so far, but still can't be sure:

The code from the post at http://forum.unity3d.com/threads/112703-Override-Unity-Data-folder-path?p=749108&viewfull=1#post749108 works for Android, but how about iOS and other platforms?

# Answer
> 1 votes
Theoretically speaking, you could achieve something along those lines using AssetBundles, your "main game" would simply be a container loading asset bundles from your favorite CDN, and you would write new "games" on different scenes.

Each scene could be a game on it's own, stored in an asset bundle - and the main game scene simply switches between scenes/games.

This topic on the Unity forums seems to address how to pack scenes into Asset Bundles: http://answers.unity3d.com/questions/398630/importing-a-scene-from-assetbundle.html

Good luck

---
Tags: unity
---


# Question
Title: Biome Transition in a Grid & Borderless World
I have a universe: a list of "Systems", each with their own center, type and radius.

A small part of such a universe could look like this:

Systems:

* Can be very close to a different system, e.g. overlap
* Can be inside another, much bigger system
* Can be very far away from any other systems
* Spawn system specific entities and particles inside the system radius
* Have some properties like background color

So far so good. However, the player can fly around freely, inside and outside of systems, in real time.

**How do I interpolate and determine things like the background color now, depending on camera position?**

E.g. if you are halfway between a green and a red system you should see a background halfway between red and green, or if you are inside a lilac system near the center and at the border of a green system you should get a mostly lilac background etc.

# Answer
I figured that what essentially needs to be done is similar to what the computer is doing when blending sprites.

So what we need to do is:

1. Find all systems that overlap with Point A.
2. Determine a color and a alpha value at Point A for each system. In graphics context this is usually sampled from a bitmap, but in this case we just use a simple radial gradient function.
3. Determine a "drawing order". In this case we sort by the size of the system so that smaller systems will be "drawn" on top of larger systems.
4. Set the background color to a fixed value.
5. Alpha blend all colors together, in the order previously determined.

Or in Pseudo code:

```
Vec2 A;
List<System> OverlappingSystems = [... systems overlapping Point A ...];
OverlappingSystems.sortBy(Radius);
Color BGColor = Black;
for(System in OverlappingSystems)
  BGColor = AlphaBlend(BGColor, System.BackgroundColor, System.AlphaAt(A));

```

AlphaAt would be defined as following:

```
func AlphaAt(Vec2 Point)
{
  return Max(1 - DistanceBetween(Point, Center)/Radius, 0);
}

```

And AlphaBlend as:

```
func AlphaBlend(Destination, Source, Number Alpha)
{
  return Destination*(1-Alpha) + Source*Alpha;
}

```

Different blending modes can be used as needed, for example Multiplication or Addition:

```
// Multiplication
Destination * (Source*Alpha + White*(1-Alpha));
// Addition
Destination + Source*Alpha;

```

These operations are even order independent making the sorting unnecessary.
> 2 votes

# Answer
I would say you should break the problem down into these two simple functions, which you can choose as you like:

* A function which determines the "weight" of a system according to the distance of the player from it and its radius.

For example, `radius / distance` would be a simple smooth one. `radius < distance ? 1/radius : 0` would produce sharp boundaries and allow small systems inside large ones to override them.
* A function which takes a list of background colors, with associated computed "weights", and produces a single background color.

For example, it could mix them according to the weights (multiply each color by weight, sum all, divide by sum of weights); in some pseudocode:

```
function mixColors(colors, weights) {
  var accum_weight = 0, accum_color = Vector(0, 0, 0);
  for i from 0 to colors.length - 1 {
    accum_weight += weights[i];
    accum_color += colors[i] * weights[i];
  }
  if (accum_weight > 0) {  // don't divide by zero
    accum_color /= accum_weight;
  }
  return accum_color;
}

```

Or it could take the one with the highest weight, possibly combined with time-based transitions as mentioned below.

```
function mixColors(colors, weights) {
  var best_weight = 0, best_color = Vector(0, 0, 0);
  for i from 0 to colors.length - 1 {
    if weights[i] >= best_weight {
      best_weight = weights[i];
      best_color = colors[i];
    }
  }
  return best_color;
}

```

Then the overall algorithm is that you apply the first function for each system, and feed the results into the second function, and that's your background color. Different functions produce different effects; the reason I've specified the above design is because it allows you to experiment with the specific results without needing to design new algorithms, just simple arithmetic.

---

Another thing that is often done in games with this sort of feature (especially with music rather than color) is to change the background over *time*. That is, when the color changes significantly you interpolate to the new color at a fixed rate over time rather than taking it only from the player position. This can be added to the above process as a final step of computation, if you want it.
> 5 votes

---
Tags: procedural-generation, maps
---


# Question
Title: How to follow object on CatmullRomSplines at constant speed (e.g. train and train carriage)?
I have a CatmullRomSpline, and using the very good example at https://github.com/libgdx/libgdx/wiki/Path-interface-%26-Splines I have my object moving at an even pace over the spline.

Using a simple train and carriage example, I now want to have the carriage follow the train at the same speed as the train (not jolting along as it does with my code below). This leads into my main questions:

1. How can I make the carriage have the same constant speed as the train and make it non jerky (it has something to do with the derivative I think, I don't understand how that part works)?
2. Why do I need to divide by the line length to convert to metres per second, and is that correct? It wasn't done in the linked examples?

I have used the example I linked to above, and modified for my specific example:

```
    private void process(CatmullRomSpline catmullRomSpline) {
        // Render path with precision of 1000 points
        renderPath(catmullRomSpline, 1000);
        float length = catmullRomSpline.approxLength(catmullRomSpline.spanCount * 1000);

        // Render the "train"
        Vector2 trainDerivative = new Vector2();
        Vector2 trainLocation = new Vector2();
        catmullRomSpline.derivativeAt(trainDerivative, current);
        // For some reason need to divide by length to convert from pixel speed to metres per second but I do not
        // really understand why I need it, it wasn't done in the examples???????
        current += (Gdx.graphics.getDeltaTime() * speed / length) / trainDerivative.len();
        catmullRomSpline.valueAt(trainLocation, current);
        renderCircleAtLocation(trainLocation);
        if (current >= 1) {
            current -= 1;
        }

        // Render the "carriage"
        Vector2 carriageLocation = new Vector2();
        float carriagePercentageCovered = (((current * length) - 1f) / length); // I would like it to follow at 1 metre behind
        carriagePercentageCovered = Math.max(carriagePercentageCovered, 0);
        catmullRomSpline.valueAt(carriageLocation, carriagePercentageCovered);
        renderCircleAtLocation(carriageLocation);
    }

    private void renderPath(CatmullRomSpline catmullRomSpline, int k) {
        // catMulPoints would normally be cached when initialising, but for sake of example...
        Vector2[] catMulPoints = new Vector2[k];
        for (int i = 0; i < k; ++i) {
            catMulPoints[i] = new Vector2();
            catmullRomSpline.valueAt(catMulPoints[i], ((float) i) / ((float) k - 1));
        }

        SHAPE_RENDERER.begin(ShapeRenderer.ShapeType.Line);
        SHAPE_RENDERER.setColor(Color.NAVY);
        for (int i = 0; i < k - 1; ++i) {
            SHAPE_RENDERER.line((Vector2) catMulPoints[i], (Vector2) catMulPoints[i + 1]);
        }
        SHAPE_RENDERER.end();
    }

    private void renderCircleAtLocation(Vector2 location) {
        SHAPE_RENDERER.begin(ShapeRenderer.ShapeType.Filled);
        SHAPE_RENDERER.setColor(Color.YELLOW);
        SHAPE_RENDERER.circle(location.x, location.y, .5f);
        SHAPE_RENDERER.end();
    }

```

To create a decent sized CatmullRomSpline for testing this out:

```
Vector2[] controlPoints = makeControlPointsArray();
CatmullRomSpline myCatmull = new CatmullRomSpline(controlPoints, false);

....

private Vector2[] makeControlPointsArray() {
    Vector2[] pointsArray = new Vector2[78];
    pointsArray[0] = new Vector2(1.681817f, 10.379999f);
    pointsArray[1] = new Vector2(2.045455f, 10.379999f);
    pointsArray[2] = new Vector2(2.663636f, 10.479999f);
    pointsArray[3] = new Vector2(3.027272f, 10.700000f);
    pointsArray[4] = new Vector2(3.663636f, 10.939999f);
    pointsArray[5] = new Vector2(4.245455f, 10.899999f);
    pointsArray[6] = new Vector2(4.736363f, 10.720000f);
    pointsArray[7] = new Vector2(4.754545f, 10.339999f);
    pointsArray[8] = new Vector2(4.518181f, 9.860000f);
    pointsArray[9] = new Vector2(3.790908f, 9.340000f);
    pointsArray[10] = new Vector2(3.172727f, 8.739999f);
    pointsArray[11] = new Vector2(3.300000f, 8.340000f);
    pointsArray[12] = new Vector2(3.700000f, 8.159999f);
    pointsArray[13] = new Vector2(4.227272f, 8.520000f);
    pointsArray[14] = new Vector2(4.681818f, 8.819999f);
    pointsArray[15] = new Vector2(5.081817f, 9.200000f);
    pointsArray[16] = new Vector2(5.463636f, 9.460000f);
    pointsArray[17] = new Vector2(5.972727f, 9.300000f);
    pointsArray[18] = new Vector2(6.063636f, 8.780000f);
    pointsArray[19] = new Vector2(6.027272f, 8.259999f);
    pointsArray[20] = new Vector2(5.700000f, 7.739999f);
    pointsArray[21] = new Vector2(5.300000f, 7.440000f);
    pointsArray[22] = new Vector2(4.645454f, 7.179999f);
    pointsArray[23] = new Vector2(4.136363f, 6.940000f);
    pointsArray[24] = new Vector2(3.427272f, 6.720000f);
    pointsArray[25] = new Vector2(2.572727f, 6.559999f);
    pointsArray[26] = new Vector2(1.900000f, 7.100000f);
    pointsArray[27] = new Vector2(2.336362f, 7.440000f);
    pointsArray[28] = new Vector2(2.590908f, 7.940000f);
    pointsArray[29] = new Vector2(2.318181f, 8.500000f);
    pointsArray[30] = new Vector2(1.663636f, 8.599999f);
    pointsArray[31] = new Vector2(1.209090f, 8.299999f);
    pointsArray[32] = new Vector2(1.118181f, 7.700000f);
    pointsArray[33] = new Vector2(1.045455f, 6.880000f);
    pointsArray[34] = new Vector2(1.154545f, 6.100000f);
    pointsArray[35] = new Vector2(1.281817f, 5.580000f);
    pointsArray[36] = new Vector2(1.700000f, 5.320000f);
    pointsArray[37] = new Vector2(2.190908f, 5.199999f);
    pointsArray[38] = new Vector2(2.900000f, 5.100000f);
    pointsArray[39] = new Vector2(3.700000f, 5.100000f);
    pointsArray[40] = new Vector2(4.372727f, 5.220000f);
    pointsArray[41] = new Vector2(4.827272f, 5.220000f);
    pointsArray[42] = new Vector2(5.463636f, 5.160000f);
    pointsArray[43] = new Vector2(5.554545f, 4.700000f);
    pointsArray[44] = new Vector2(5.245453f, 4.340000f);
    pointsArray[45] = new Vector2(4.445455f, 4.280000f);
    pointsArray[46] = new Vector2(3.609091f, 4.260000f);
    pointsArray[47] = new Vector2(2.718181f, 4.160000f);
    pointsArray[48] = new Vector2(1.990908f, 4.140000f);
    pointsArray[49] = new Vector2(1.427272f, 3.980000f);
    pointsArray[50] = new Vector2(1.609090f, 3.580000f);
    pointsArray[51] = new Vector2(2.136363f, 3.440000f);
    pointsArray[52] = new Vector2(3.227272f, 3.280000f);
    pointsArray[53] = new Vector2(3.972727f, 3.340000f);
    pointsArray[54] = new Vector2(5.027272f, 3.360000f);
    pointsArray[55] = new Vector2(5.718181f, 3.460000f);
    pointsArray[56] = new Vector2(6.100000f, 4.240000f);
    pointsArray[57] = new Vector2(6.209091f, 4.500000f);
    pointsArray[58] = new Vector2(6.118181f, 5.320000f);
    pointsArray[59] = new Vector2(5.772727f, 5.920000f);
    pointsArray[60] = new Vector2(4.881817f, 6.140000f);
    pointsArray[61] = new Vector2(5.318181f, 6.580000f);
    pointsArray[62] = new Vector2(6.263636f, 7.020000f);
    pointsArray[63] = new Vector2(6.645453f, 7.420000f);
    pointsArray[64] = new Vector2(6.681817f, 8.179999f);
    pointsArray[65] = new Vector2(6.627272f, 9.080000f);
    pointsArray[66] = new Vector2(6.572727f, 9.699999f);
    pointsArray[67] = new Vector2(6.263636f, 10.820000f);
    pointsArray[68] = new Vector2(5.754546f, 11.479999f);
    pointsArray[69] = new Vector2(4.536363f, 11.599998f);
    pointsArray[70] = new Vector2(3.572727f, 11.700000f);
    pointsArray[71] = new Vector2(2.809090f, 11.660000f);
    pointsArray[72] = new Vector2(1.445455f, 11.559999f);
    pointsArray[73] = new Vector2(0.936363f, 11.280000f);
    pointsArray[74] = new Vector2(0.754545f, 10.879999f);
    pointsArray[75] = new Vector2(0.700000f, 9.939999f);
    pointsArray[76] = new Vector2(0.918181f, 9.620000f);
    pointsArray[77] = new Vector2(1.463636f, 9.600000f);
    return pointsArray;
}

```

Disclaimer: My math is very rusty, so please explain in lay mans terms....

# Answer
> 1 votes
You're using a fixed offset from the train, rather than taking into account the fact that a parameter difference of 1/length is not 1 meter along the whole spline. In places with a large derivative, this offset will be greater than 1 meter. In places with a small derivative, it will be less.

Try something like this instead:

```
float followOffset = 1f/trainDerivative.len();

float carriagePercentageCovered = (((current * length) - followOffset) / length);

```

Note that even this is only a first approximation, and you may continue to see some variation in spacing without further iterations. If this proves to be an issue, let me know in a comment and I can show you how to refine the movement further.

---
Tags: libgdx, movement, path-finding, splines
---


# Question
Title: Should I have a public development blog?
Should I keep a public development blog for a game I'm creating?

What are the benefits and issues of this activity?

# Answer
> 38 votes
You'll hear from a lot of people that ideas are worthless. Execution and passion are what matter.

There are a lot of good reasons to run a public development blog.

* It builds exposure for your game.
* It can start a community around the product.
* It builds exposure for you as a developer.
* It gives you exposure to people who might be interested in contributing.
* Blogging about what you're doing forces you to teach whatever concept you're trying to give to others, which is a really good learning tool.
* It forces you to finish something good enough to the point where you're willing to show it off on a regular basis

But there are also some bad ones

* You might give into bad critique too early if you have a special vision for what your game is going to be
* If you can't pull off what you're trying to accomplish, your failure is public.
* It takes time. If you are trying to build a community you need to provide a constant stream of content to keep people interested. That can take away from your development time.
* Somebody who has access to more resources (talent, money, etc) could "steal your idea".

Worrying about somebody "stealing your idea" isn't worth it. Once your game is finished, if it's any good, somebody's going to borrow from it. Even if it's an unabashed rip off they may do a better job than you can. The only thing hiding your idea gives you is a theoretical head start. It's better to just release something good and give it to an audience that wants it than trying to hide it away.

But at the end of the day you have to ask yourself why you'd want to start a blog. Can you actually pull off what you think you want to do? Are you focusing on the product itself or are you thinking a bit more ahead about what happens after the product is finished (either by shipping or getting shelved)?

# Answer
> 6 votes
I maintain a blog for my game, and I did wonder this same thing in the beginning. Although I wouldn't call my game original, there isn't another game just like it. Like many games (or even ideas in general), it's built on the shoulders of the giants before. It's all about how you implement your idea, not the idea its self. No one will be able to implement the idea like you can, especially since it's your idea and only you know all the details. If you're in development for the joy of making your ideas a reality, I think you'll find maintaining a blog very rewarding.

I find that blogging about features as I add them really makes me understand the features better. It's fun to get feedback about the game as you're making it. When people say how cool your game looks or that they want to play it, it really motivates you. Good luck!

# Answer
> 1 votes
I've asked myself the same question a few weeks ago and decided to give it a try. I've started a small blog. It's more about game development in general and not so much about my game.

I'm a hobby game developer and indeed maintaing a blog takes a relevant part of my available time. Even worse sometimes writing blog posts makes more fun than continuing with my game.

On the other hand writing blog posts forces me to divide my projects in smaller components and keep focus on one problem at a time. A result was also an improved code quality and architecture.

Not sure if this blog will help me promoting my game, if it is finished. But a least it is fun.

---
Tags: motivation
---


# Question
Title: What is the correct way to reset and load new data into GL_ARRAY_BUFFER?
I am using an array buffer for colors data. If I want to load different colors for the current mesh in real time what is the correct way to do it. At the moment I am doing:

```
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, SIZE, colorsData, GL_STATIC_DRAW);
glEnableVertexAttribArray(shader->attrib("color"));
glVertexAttribPointer(shader->attrib("color"), 3, GL_FLOAT, GL_TRUE, 0, NULL);
glBindBuffer(GL_ARRAY_BUFFER, 0);

```

It works, but I am not sure if this is good and efficient way to do it. What happens to the previous data ? Does it write on top of it ?

Do I need to call :

```
glDeleteBuffers(1, colorBuffer);
glGenBuffers(1, colorBuffer);

```

before transfering the new data into the buffer ?

# Answer
> 4 votes
`glBufferData()` overwrites the previous data, and is generally what you should use to load new data into a GL buffer. Conceptually it is similar to overwriting data in an array.

`glDeleteBuffers()` and `glGenBuffers()` destroy and recreate a buffer. Conceptually they are similar to `free()` and `malloc()`. If you're just writing new data into the buffer, destroying it and recreating it is not only overkill, but will almost certainly bring a performance penalty.

But, above all, what is the problem you're experiencing?

# Answer
> 1 votes
You don't need to rebind the VAO or reset the vertex attributes. You can just overwrite the data in place:

```
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, SIZE, colorsData, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

```

When glDraw\* is called the new data will be used.

I use `GL_DYNAMIC_DRAW` because you would change the data often whereas `GL_STATIC_DRAW` would indicate that you won't change it often. It really doesn't make a difference but allows the driver to optimize differently.

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


title: Issue porting Cocos2d-x to Android

text:
# Question
Title: Issue porting Cocos2d-x to Android
I've written a basic game using Cocos2D-x on XCode. It works fine on the iPhone. Now I'm trying to port it to Android. When I run the script ./build\_native.sh inside the `proj.android` folder, it gives me the following error:

```
jni/../../Classes/MemoryModeLayer.cpp: In member function 'void MemoryModeLayer::startNewGame()':
jni/../../Classes/MemoryModeLayer.cpp:109:25: error: 'time' is not a member of 'std'
jni/../../Classes/MemoryModeLayer.cpp:109:25: note: suggested alternative:
/Users/abc/android-ndk-r9d/platforms/android-8/arch-arm/usr/include/time.h:40:17: note:   'time'
jni/../../Classes/MemoryModeLayer.cpp:111:5: error: 'random_shuffle' is not a member of 'std'
jni/../../Classes/MemoryModeLayer.cpp:112:5: error: 'random_shuffle' is not a member of 'std'
make: *** [obj/local/armeabi/objs/cocos2dcpp_shared/__/__/Classes/MemoryModeLayer.o] Error 1
make: Leaving directory `/Users/abc/cocos2d-x-2.2.3/projects/Game/proj.android'

```

In MemoryModeLayer.cpp I have the following:

```
std::srand(unsigned(std::time(0)));
std::random_shuffle(_xCod, _xCod + _numberOfRows);
std::random_shuffle(_yCod, _yCod + _numberOfColumns);

```

I've included the following headers as well:

```
#include <string>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <iomanip>

```

Also added using namespace std in the header file. Is there anything else that I should do?

# Answer
> 0 votes
There was a problem with the Application.mk file. Had to change the STL library lookup like so:

```
Add APP_STL := stlport_static to the Application.mk file. It may already have APP_STL := gnustl_static.

```

This blog post was very helpful!

http://blog.codetactics.com/2013/06/05/porting-a-cocos2d-x-ios-game-to-android/

---
Tags: c++, android, cocos2d-x
---


# Question
Title: Is there a way to earn money from non-mobile HTML5 game?
I'm just a hobbyist, who has some ideas, that would not fit on a mobile screen. I have searched for some method, to make a bit of money from them, but I've found just for mobile-optimized games.

So the question is: is there any way to earn some money from these games, too?

# Answer
> 2 votes
A non-mobile HTML5 game is a website. One way to monetize a website is through advertisement. A painless solution which requires minimal work on your part is a system like Google Adsense which automatically chooses advertisement which might appeal to your audience, injects it into your website and pays you for every click.

You could also attempt to monetize your game through subscription or ingame micro transactions. But in that case you will have to create the payment infrastructure yourself and design your game in a way that these integrate well into the gameplay.

When you don't want your game to be embedded in a website and would rather want to market it as a stand-alone executable, there are also tools to wrap a web appliction in an executable. These usually work by creating a browser window without any toolbars or menus and loading your HTML page into it. Most users won't be able to distinguish it from a native application. However, I never used a tool like this, so I don't feel comfortable making product recommendations in this regard.

You can then market it just like any other game, for example on a digital download platform like, for example, Desura (Steam would also be an option, but the greenlight process is a barrier which is too high for most hobbyists).

---
Tags: html5, monetization
---


# Question
Title: Does one's choice of 3d modeling software used during asset creation affect performance at runtime?
Does software used to create 3d assets (for game development specifically) have an impact on the efficiency of the program?

In other words, is it possible to reduce the operating footprint of an application merely by utilizing alternative development software during production of 3d assets? If you use two different applications to create a 3-dimensional image of a box, can one of them result in better performance if aspects of the image are identical?

I am attempting to get the information I need without causing unnecessary debate over specific software choice.

# Answer
> 8 votes
Indirectly, yes.

A 3d model is a collection of polygons\*. The less polygons it has, the faster it can be rendered by a 3d engine. That means a 3d modeling program for game development should assist the artist in creating good looking 3d models with the fewest number of polygons possible. On the other hand, a software which focuses on use-cases where image quality is the primary goal and rendering time is just of secondary concern (like CGI effects for a movie) can be much more wasteful with the polygon-count.

The difference might not be apparent with a test-case as simple as a box. I would dare to say that any 3d modeling tool which uses more than 12 polygons to create a box-primitive (2 triangles to form each of the six rectangles) would be quite strange.

But it might be more apparent when it comes to approximating round shapes with polygons. You can not create a perfectly round shape with a polygon-based 3d model. When you want something round in a game, you need to approximate the shape with a large number of polygons. How many you need to make it appear round-ish enough depends on how large the object is going to appear on the players screen in the finished game. This is something the 3d modeling software can not anticipate. The artist has to make this decision during the design phase.

An inexperienced 3d modeler who just clicks on the "make sphere" tool might not realize that it causes the program to create a much higher number of polygons than necessary. An experienced 3d modeler might notice the problem, but might have a hard time to convince the program to use exactly the number of polygons they want and eventually just give up and have the program have its way to meet the deadline.

A good 3d modeling software for games might also provide tools to automatically reduce the polygon-count of a 3d model without notably affecting its appearance while another software might offer no such tool or only tools with worse results.

<sub>\*) In practice, a 3d model is often a lot more than just polygons. Different kinds of textures, animation bones, etc.. But everything I wrote about polygons also applies to these aspects.</sub>

# Answer
> 1 votes
No

but that answer has a number of caveats, so I'm not really disagreeing with Phil, just looking at it from a different perspective.

In particular, the model must be identical in each case (eg. a 3d model from Maya and an identical model exported from 3ds Max are treated exactly the same by the game engine). However different modeling tools tend to nudge you toward different approaches to modeling, and thus a newbie who doesn't really know what he's doing is likely to create models that aren't technically identical, even though to the untrained eye they look the same.

For example, a low-pol model that simulates detail using a normal map will be much more efficient to render than a high-pol model with that same detail apparent in the polygons. The visual appearance may be the same however (indeed, the whole *point* of normal maps is to transfer detail from a detailed high-pol model onto an efficient low-pol model).

---
Tags: 3d, assets
---


title: Camera vs Viewport

text:
# Question
Title: Camera vs Viewport
I'm don't have a clear understanding of what precisely is the difference between the camera coordinates and the viewport coordinates. Can anyone please clarify?

# Answer
**Camera** is like a camera with which Batman movie is filmed. It exists in a virtual world and can be moved around, targeting different scenes, changing focal length and other camera properties. You can have many cameras and switch between them. You can even film on several cameras at once.

Typical camera coordinates are: position in virtual world, facing direction, up-vector, field-of-view, etc.

**Viewport** is a cinema screen. It is a place where image recorded by camera is shown. In PC world that is an area in the screen within some window or a full-screen image. You can show feeds from several cameras at once (like in those console racing games between 2-4 players).

Typical viewport coordinates are: position on display, height and width.
> 45 votes

# Answer
The viewport coordinates are the coordinated where it is placed on the screen. (For example inside a win32 window).

The camera coordinates are the position of the camera INSIDE the viewport, that is inside the 2D/3D space you set in your OpenGL application. The camera can't go outside that viewport because it is in the space you set where opengl can do its work, inside a Win32 window.
> 0 votes

---
Tags: opengl, camera, viewport
---


# Question
Title: Omni-directional light shadow mapping with cubemaps in WebGL
First of all I must say, that I have read a lot of posts describing an usage of cubemaps, but I'm still confused about how to use them.

My goal is to achieve a simple omni-directional (point) light type shading in my WebGL application.

I know that there is a lot more techniques (like using Two-Hemispheres or Camera Space Shadow Mapping) which are way more efficient, but for an educational purpose cubemaps are my primary goal.

Till now, I have adapted a simple shadow mapping which works with spotlights (with one exception: I don't know how to cut off the glitchy part beyond the reach of a single shadow map texture): \>\>\>glitchy shadow mapping\<\<\<

So for now, this is how I understand the usage of cubemaps in shadow mapping:

1. Setup a framebuffer (in case of cubemaps - 6 framebuffers; 6 instead of 1 because every usage of framebufferTexture2D slows down an execution which is nicely described \>\>\> here \<\<\<) and a texture cubemap. Also in WebGL depth components are not well supported, so I need to render it to RGBA first.

```
this.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.texture);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
for (var face = 0; face < 6; face++)
    gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.RGBA, this.size, this.size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);

this.framebuffer = [];
for (face = 0; face < 6; face++) {
    this.framebuffer[face] = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer[face]);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, this.texture, 0);
    gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.depthbuffer);

    var e = gl.checkFramebufferStatus(gl.FRAMEBUFFER); // Check for errors
    if (e !== gl.FRAMEBUFFER_COMPLETE) throw "Cubemap framebuffer object is incomplete: " + e.toString();
}

```
2. Setup the light and the camera (I'm not sure if **should I store all of 6 view matrices** and send them to shaders later, or is there a way to do it with just one view matrix).
3. Render the scene 6 times from the light's position, each time in another direction (X, -X, Y, -Y, Z, -Z)

```
for (var face = 0; face < 6; face++) {
    gl.bindFramebuffer(gl.FRAMEBUFFER, shadow.buffer.framebuffer[face]);
    gl.viewport(0, 0, shadow.buffer.size, shadow.buffer.size);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    camera.lookAt( light.position.add( cubeMapDirections[face] ) );
    scene.draw(shadow.program);
}

```
4. In a second pass, calculate the projection a a current vertex using light's projection and view matrix. Now I don't know If **should I calculate 6 of them**, because of 6 faces of a cubemap. ScaleMatrix pushes the projected vertex into the 0.0 - 1.0 region.

```
vDepthPosition = ScaleMatrix * uPMatrixFromLight * uVMatrixFromLight * vWorldVertex;

```
5. In a fragment shader calculate the distance between the current vertex and the light position and check if it's deeper then the depth information read from earlier rendered shadow map. I know how to do it with a 2D Texture, but I have no idea **how should I use cubemap texture here**. I have read that texture lookups into cubemaps are performed by a normal vector instead of a UV coordinate. **What vector should I use?** Just a normalized vector pointing to the current vertex? For now, my code for this part looks like this (not working yet):

```
float shadow = 1.0;
vec3 depth = vDepthPosition.xyz / vDepthPosition.w;
depth.z = length(vWorldVertex.xyz - uLightPosition) * linearDepthConstant;

float shadowDepth = unpack(textureCube(uDepthMapSampler, vWorldVertex.xyz));
if (depth.z > shadowDepth)
        shadow = 0.5;

```

Could you give me some hints or examples (preferably in WebGL code) how I should build it?

**UPDATE:** I figured out that view matrices are superfluous in the case of program rendering the scene with shadows. One can read the adequate texel from the shadow cubemap by using one of those vectors: `lightPosition - worldVertexPosition` or `worldVertexPosition - lightPosition` (right now I don't know which is the correct one, because both gives a not complete shadowing result - the first one mirrors the shadow and doesn't display anything from the -Y light cubemap face while the second one displays the bottom face correctly, but it does right only that: \>\>\>img here\<\<\<)

```
shadowDepth = unpack(textureCube(uDepthCubemapSampler, vWorldVertex.xyz - uLightPosition));
or
shadowDepth = unpack(textureCube(uDepthCubemapSampler, uLightPosition - vWorldVertex.xyz));

```

**UPDATE2:** Finally, by trial and error, I managed to get this thing working. The problem was that the cubemap texture is mirrored, so I had to scale the regular projection matrix by (1, -1, 1) in order to un-flip it. Also, the right vector to read cubemap is `vWorldVertex.xyz - uLightPosition`. Now everything seems to be working nice!

# Answer
Finally, by trial and error, I managed to get this thing working.

The problem was that the cubemap texture is mirrored, so I had to scale the regular projection matrix by (1, -1, 1) in order to un-flip it.

Also, the right vector to read the cubemap is `vWorldVertex.xyz - uLightPosition`.

Now everything seems to be working nice!
> 1 votes

---
Tags: javascript, webgl
---


title: XNA Load/Unload logic (contentmanager?)

text:
# Question
Title: XNA Load/Unload logic (contentmanager?)
I am trying to make a point-and-click adventure game with XNA, starting off simple. My experience with XNA is about a month old now, know how the classes and inheritance works (basic stuff).

I have a problem where I cannot understand how I should load and unload the textures and game objects in the game, when the player transitions to another level. I've googled this \>10 times, but all I find is hard coding while I don't even understand the basics of unloading yet.

All I want, is transitioning to another level (replacing all the sprites with new ones).

Thanks in advance

# Answer
> 0 votes
The way I handle level transitions is through game states. Let me give a little example:

Game states of: TitleScreen, Menu, Level1, Level2, Level3, Credits, Pause

So each game state can use it's own LoadContent and UnloadContent.

When TitleScreen is active, LoadContent loads a Title Image, then unloads them. When the Menu becomes active, it loads any graphics need with the menu, then unloads them. When Level1 becomes active, it loads all it's assets etc.

The only difference is a Pause game state, in which it doesn't load or unload, it just sits and doesn't call GameUpdate until the "unpause" is pressed.

How you manage gamestates is up to you. I like to create an enum named GameState

Something like this

```
public enum GameState
{
    TitleScreen,
    Menu,
    Level1,
    Level2,
    Level3,
    Pause
};

GameState currentGameState = GameState.TitleScreen;

```

Then just use a switch

```
switch(this.gameState)
    {
        case GameState.TitleScreen:
            //Load TitleScreen Stuff
            break;
       case GameState.Menu:
            //Load Menu Stuff
            break;
       case GameState.Level1:
            //Load Level 1 assets
            break;
        //etc

        default:
            throw new Exception("Something Broke.");
        break;

    }

```

You can then leverage the gamestates to cleanly handle your loading and unloading of game assets.

---
Tags: xna, monogame
---


title: SDL2 window as child of Win32 GUI

text:
# Question
Title: SDL2 window as child of Win32 GUI
I'm building an editor. Is it possible to create a child window of **SDL2** within a Win32 gui? *(The most obvious page from SDLTutorials works for earlier versions of SDL)*

# Answer
Yes it is SDL 2 allows you to tie your window directly to a window handle of a parent window. You can also plug DirectX and/or OpenGL directly into an SDL window. (This is, I think, how SDL2's OpenGL layer does it)

See SDL\_CreateWindowFrom

**EDIT**
Below is the code for the SDL portion of the program. You would create the win32 window as normal and it looks like you still need to use the win32 event system. I have not tried the SDL's in conjunction with it however.

```
SDL_InitSubSystem(SDL_INIT_VIDEO);
SDL_Window* sdlWnd = SDL_CreateWindowFrom(hWnd);
SDL_SetWindowTitle(sdlWnd, "SDL Window - Set by SDL");
SDL_Surface* s = SDL_GetWindowSurface(sdlWnd);
SDL_FillRect(s, &s->clip_rect, 0xffff00ff);
SDL_UpdateWindowSurface(sdlWnd);

```

This will open the window from `hWnd` and set the title and color the window magenta.

**EDIT 2**
Events do work and you will use the event loop inside of a main loop (or however you choose to do it) as normal. You do not need to use the WndProc callback. But, it must be present for window creation (it may look like below):

```
LRESULT CALLBACK WndProc(HWND h, UINT m, WPARAM w, LPARAM l) { return DefWindowProc(h, m, w, l); }

```

**EDIT 3**
It looks like events are a bit wonky in SDL when using system events. You will basically have to fall back on system events either by using SDL\_SYSWMEVENT (get the WM\_EVENT from `Ev.syswm.msg->msg.win.msg`) or use the WndProc.

For example, the events stop working if you resize the window or do anything of that nature.
> 3 votes

---
Tags: c++, sdl, gui, win32
---


# Question
Title: How should I handle a modelview stack with multiple shader programs involved?
I'm building a framework where each object has an associated program and each object has a 'draw' method.

What is the best choice, to have a single modelview stack handled by a Renderer class or to have a modelview stack for each program? In the preferred case how can I handle optimally a "world" transformation that affects all the objects independently by the program (i.e. moving the camera)

# Answer
> 2 votes
You shouldn't need a "stack" at all.

You should have a single "drawable" type (you generally do not need more than one; variations on a request to draw are *data* and individual game entities should not draw themselves). The `Drawable` type contains:

* A *reference* to the geometry being drawn.
* A *reference* to the shader program used to draw.
* *References* to any textures needed by the prior two items.
* A matrix storing the object's world transformation.

(The references are key to avoid data duplication and to allow for sorting by these objects prior to rendering when possible, since that helps minimize state changes and improve rendering performance.)

To handle a transformation like the camera, store the camera's viewing transformation in a `Camera` object that represents the camera.

To handle actual world transformations applied to multiple objects, such as supporting the bulk selection and moving of many entities, you'll probably want a higher-level system. This is generally not the domain of the renderer itself. Something that can maintain the collection of grouped objects and apply a requested transformation to their existing transformations (for example, a `Selection` type if all you're doing is selection-related stuff).

A scene graph is occasionally useful for that kind of thing, though you should proceed with caution there as scene graphs tend to create black holes of over-engineering and design paralysis.

---
Tags: opengl, rendering, models, oop
---


# Question
Title: Which unit test framework for c++ based games?
Which combination of testing tools do you feel is best? Given the framework / library of your choice you might consider:

---

Note: While this is potentially a generic question like the one on SO I would argue that game development is usually bound to a specific work flow which influences the choice for testing. For a higher-level perspective, see question Automated testing of games.

# Answer
I found **UnitTest++** to be very easy to work with. I will yet have to try amop alongside with it, which was mentioned to be a good companion to UnitTest++ for mock object functionality. Otherwise Google Mock is a popular choice. Also, you may want to read up on UnitTest++ and Mock Objects.

UnitTest++ can be set up with your Continuous Integration approach, e.g. with Hudson

You may want to read this inspiring post if you're not convinced unit testing and games go well together.
> 7 votes

# Answer
Another vote for UnitTest++. Very easy to integrate, compiled for our target embedded platform very easily, straightforward and easy-to-use. We have also integrated it with Hudson. We looked at GoogleTest but rejected it (I think it had issues compiling for our target platform) but it has a similar feature set and might be suitable for you.

Additionally you might want to look into some kind of smoke testing framework. In my experience it is difficult to get sufficient test coverage for a game with unit tests alone. Especially if you are introducing unit testing to an existing codebase, and even moreso for a large team. Smoke testing would be testing high-level things like "make sure all the levels load". My theory is that if I have both kinds of testing then at some point they might meet in the middle and give decent converage. :)
> 4 votes

# Answer
Back when I was working in C++ (disclaimer: this was about 2005), I used a *slightly modified* version of **TUT (Template Unit Test Framework)**. I liked it because it was so lightweight, which made it easy to modify, and meant there was very little "glue" required when writing tests.

Here is one very simple modification I made, that makes it even eaiser/cleaner to write tests:

```
static int BogusFunction() { return __COUNTER__; } // Increment the __COUNTER__ to the correct position for the begining of the tests
#define TEST template<> template<> void object::test<__COUNTER__>()
#define ENSURE(msg, cond) ensure(msg, cond, __FILE__, __LINE__)
#define ENSURE_EQUALS(msg, actual, expected) ensure_equals(msg, actual, expected, __FILE__, __LINE__)
#define ENSURE_DISTANCE(msg, actual, expected, distance) ensure_distance(msg, actual, expected, distance, __FILE__, __LINE__)
#define FAIL(msg) fail(msg, __FILE__, __LINE__)

```

The other change I made was to its output format, so that test failures would appear correctly in Visual Studios's error list (when run as part of a build), clickable to go to the file and line of the failed test.

(The ability to do this sort of thing means that *it* can be made to fit into your TDD/CI process, rather than forcing you to fit into its.)

Here is an example test (from the command-stack from my editor):

```
TEST // Undoing a command
{
    cs.AddCommand(new TestCommand);
    cs.AddCommand(new TestCommand(od));

    ENSURE("Undo success", cs.Undo());
    ENSURE_EQUALS("Stack size", cs.size(), 2);
    ENSURE_EQUALS("Command's Undo() was called", od.undo, 1);
    ENSURE_EQUALS("Command's Redo() not called", od.redo, 0);

    ACommandStack::const_iterator it = cs.end();
    ENSURE("Command is redoable", cs.GetUndoPos() == --it);
}

```

(In the above code, `cs` and `od` are per-module fixtures, and `TestCommand` is a mock object.)
> 2 votes

# Answer
When it comes to C++, I have tried and used the googletest framework, http://code.google.com/p/googletest/. It's simple to set up, easy to use and works great.
> 2 votes

# Answer
I'm not a professional game developer, but I am a professional embedded developer. Perhaps not exactly like games but close. At my place of work we've used a few.

I really like google test. It has all of the best features of the recent unit test frameworks, while keeping it all in a minimal, stream lined interface.

Next on my list is Boost Test. Google test's api is a bit more modern than Boost.Test, but Boost Test has done an amazing job of adding new features and ditching the crufty CppUnit paradigm.

I've also used CxxTest. It's quite well done but you can tell that it's not as modern as either Boost.Test or Google Test. In particular, its support for test suites and fixtures is a bit awkward.

I like to use the advanced features, but if you're a minimalist you'll never see the difference between the three. Most of my colleagues would be happy with a unit test framework that supports auto registering test (in a declarative manner ) and has some sort of a CHECK\_EQUALS(a,b) macro.
> 2 votes

# Answer
My favorite testing library is QuickCheck http://en.wikipedia.org/wiki/QuickCheck. There is an experimental C++ version, but it looks too heavy weight, but even without a dedicated library the principles are easy to use.

All of my classes have a genArbitrary method that can generate a random instance. I use this for smoke testing invertible processes, like loading and unloading. I can generate thousands of random scenes and check that various properties hold (like the scene I serialize is the same as the scene I deserialize).

It doesn't replace traditional unit tests (it does reduce the need for many potential unit tests), but its a great way to discover bugs, and it helps stress test my memory allocation strategy (along with Valgrind). Its great to watch over a million allocations come out Valgrind pure :).

I used to use CxxTest as a test harness, which I liked. Now all of my tests are separate exes. I just have a folder called Test, and ever file that begins with Test\_ becomes a test. So far it is a really easy lightweight to make tests.
> 1 votes

# Answer
With Java, there are so many good libraries... Not the case of C++.

For C++ users, there is a chain tool from Kitware that is very interesting:

* CMake: make tool
* CDash: continuous integration tool

Kitware writes C++ codes for Computer Science.

For personal projects, i use the Boost unit test library (on Desktop platform). For Continuous Integration, i use Hudson:

* easy install on Tomcat
* scriptable
> 0 votes

# Answer
I'll second the TUT (Template Unit Test) framework; it's super lightweight and extremely flexible, not to mention really easy to setup and use out of the box (a single header include, a little bit of main/setup code, and 24 lines of test code later you have a unit test). I've combined it with binfmtc (run C++ programs as scripts) for rapid prototyping/TDD/learning templates to great success, including embedded software development. Due to it being able to output to XML, it also dovetailed in nicely with Jenkins (CI) and Sonar on successive projects of mine.
> 0 votes

---
Tags: c++, testing
---


# Question
Title: In a multiplayer game, should I store the list of character names on the Player class?
I am writing a multiplayer game that has account system and character creation system like standart MMORPGs. I have a question about name creating issue. I think that I can create a static variable on Player class that keeps created player names but it confused me. It will tell me name is valid or unvalid depends on the other players has this name.

Questions;

* Does implementation does make sense ?
* If i have 1000 players, is it means it consumes 1000 times of memory of this list? Or it just consume as like there is one?
* What is your suggestion for place that I can keep player name list? A new class?

# Answer
This is not a good idea.

The player class should be concerned with an individual player; the actions you will want to do with the set of all player names in the system exist at a much broader level than what the player class should be concerned with.

Further, a single static list in code means:

* It is difficult to segregate the names by region, so you could not neccessarily easily have a seperate pool of names for players in Asian countries versus those in European countries, if your game worlds were so divided.
* It is difficult to access that name list in a distributed fashion, since it exists in only one process's address space on one machine, which means that one process becomes a bottleneck for every other distributed process that would need to check, remove from, or insert into that list.
* It is difficult to access that list from a service that isn't an .exe compiled against the code library containing the player class (for example, a web service like a forum that wants to display player names).

Your `Player` class is a runtime representation of a single player for use in the simulation of your game. The list of currently-used names is data -- related, true, but not data that should be owned by `Player`. Store it in a database.
> 2 votes

# Answer
1) At the level you're working, yes. In the future you definitely want a database, but I think there's a lot of things you can do before needing one.

2) No. A static class variable is a single variable shared by all the instances of the class. You can access it as player1-\>list, player2-\>list or Player::list, and it's always the same variable.

3) A list is OK, but you may want to use a `set<string>` (or `unordered_set<string>` in C++11) for faster lookups.
> 0 votes

---
Tags: c++, mmo, rpg
---


title: Depth Map resolution shifting

text:
# Question
Title: Depth Map resolution shifting
the problem is with shadow mapping as you can see,

actually it works fine but in a certain condition that the Depth Map size must be equal to the size of rendering buffer, I use an infinite directional light

so if the window is 800x600 the depth map must be 800x600, and when i change the size of the shadow map to be 900x600 it starts to be shifted and when it's size be 1024x1024 it also shifts till it disappears

the GLSL shadow function

```
float calcShadow(sampler2D Dmap, vec4 coor){

vec4 sh = vec4((coor.xyz/coor.w),1);
sh.z *= 0.9;
return step(sh.z,texture2D(Dmap,sh.xy).r);
}

```

here's the result when it's the same size as the window

Colored result & Depth Map

and here's the shifted result, as you can notice the depth map is exactly as the previous one with the addition of white space to the right.

Colored result http://goo.gl/5lYIFV

Depth Map http://goo.gl/7320Dd

# Answer
> 1 votes
It looks like you are missing a call to glViewport before rendering to the shadow map. The viewport should be set whenever you render to a render target (or texture) of a different size.

---
Tags: opengl, shaders, fragment-shader, shadows, shadow-mapping
---


title: How does Flow Field pathfinding work?

text:
# Question
Title: How does Flow Field pathfinding work?
Supreme Commander 2 has something called *flow field* path finding. How does it work? Is there some article available I can read up on how it works?

# Answer
I wrote flow fields for sup com 2, and I wrote an article explaining the details. It can be found in the upcoming book "Game AI Pro: Collected Wisdom of Game AI Professionals".

Also, I recently did a video stream talking about flow fields for Planetary Annihilation. I show some debug views and explain how it works at a high level. http://youtu.be/5Qyl7h7D1Q8?t=24m24s

Hope this helps
> 36 votes

# Answer
I've been looking for this term as well, and this paper is the only major one I could find that references flow fields directly: http://www.aaai.org/Papers/AIIDE/2008/AIIDE08-031.pdf

This approach involves each pathfinding agent being influenced by a global vector field, and in turn influencing that field with their resulting path. You still need some basic object avoidance code to kick things off, so is only really applicable for swarms crossing paths, rather than individual agents.

However, the SupComm2 guys mention research from the University of Washington directly, and this is the most applicable paper that I could find from that institution: http://grail.cs.washington.edu/projects/crowd-flows/

This approach seems more promising but I need to read more about it.
> 20 votes

# Answer
The official specs of the pathfinding algorithm in Supreme Commander 2 refer to the **Crowd Continuum Study** at University of Washington.

There are several papers and demonstrations at that link.
> 8 votes

# Answer
I'll include the description of how to solve an eioknal equation here, because it's the messy bit to implementing flow field path finding. See Continuum Crowds for an example of how to use this solution for path finding. Basically, the idea is that you are computing the time a wavefront spreading out from initial points reaches every other point in a grid, e.g.:

(Image from Implementation Details of the Fast Marching Methods, which I highly recommend reading)

It's sorta like pathfinding starting from a set of goal points, and computing the amount of time T(x, y) it would take to reach the nearest goal point from any point on a grid if you were following the optimal path and moving at speed F(x, y) (the F(x,y) values you can chose and are part of the map, and something like terrain roughness could make them lower). This is nice because you are solving for every point on a map, so every agent with the same goal can use this same result, and you only have to do one run of the algorithm (per timestep) for all of them. To get these T(x, y) values, there are three options I know of: The Fast Marching Method, Fast Sweeping Method, and Fast Iterative Method.

The Fast Marching Method works fairly well for small grids, takes time O(nlog(n)), where n is the number of points in the grid, and is best described in the "Implementation Details of the Fast Marching Methods" link at the bottom of the wiki page. However, for larger grids (say in 3D), this log(n) factor becomes prohibitive, so that's where the Fast Sweeping Method and Fast Iterative Method come in. More importantly, the Fast Marching Method uses a binary heap, which means it's not straightforward to parallelize, and has poor cache coherency. The Fast Sweeping Method has the potential to perform better, yet is slowed down by any direction changes that could happen, say, in the case of a winding maze. The Fast Iterative Method is a pretty good compromise between these two, working pretty well in winding mazes, being somewhat amenable to parallelization, and having good cache coherency. It also is slower in smaller maps, however, so I'd probably recommend implementing the Fast Marching Method first, then if it's too slow working towards implementing the Fast Iterative Method in something like OpenCL using Scans.

I'll describe the Fast Marching Method in more detail here, as the part about how to solve the quadratic is equally applicable to the Fast Iterative Method. In short, the Fast Marching Method starts by setting all beginning nodes as frozen, with T(x, y)=0. Then every node adjacent (4 neighbor neighborhood in 2D and 6 neighbor neighborhood in 3D) to these nodes is marked as being in the "narrow band," and their T(x, y) is computed using a quadratic:

$$(T(x, y) - a)^2 + (T(x, y) - b)^2 = (1/F(x, y))^2$$

Where

$$a = Min(T(x + 1, y), T(x - 1, y))$$

$$b = Min(T(x, y + 1), T(x, y - 1))$$

only considering values for T(...) of neighboring frozen nodes. Thus, for example, if the node above and the node below aren't frozen, the (T(x, y) - b)^2 term drops out of the equation. This can be solved by hand, or with wolfram, and you use the greater of the two solutions. In 3D it's very similar. The reason for this quadratic is because it makes the solution look smoother than simply spreading out linearly from the goal, also for math consistency reasons I don't fully understand.

When implementing this there were times where this quadratic had no solution, however, so I asked about this on the scicomp stack exchange, and got a very good answer that's best explained there: basically in that case you just need to solve the quadratic differently by falling back to a "lower dimensional wavefront." You also need to do this if the solution you get is lower than any frozen node's T(x, y) values nearby - because then the quadratic solution is invalid because if you use it the wave is somehow travelling back in time.

You add each of these narrow band nodes to a binary heap, sorted by their newly computed T(x, y) values. Then the node at the top is removed, made a frozen node, and any new narrow band nodes are added to the heap. It's important to note that this means narrow band nodes can be added to the heap more than once, which can be addressed by simply ignoring any frozen nodes that are at the top of the heap - since we've already processed them with a more accurate T(x, y) value before.

This process is repeated until all nodes are set to frozen (or inaccessable), at which case you're done solving the eikonal equation. This is also cool because you can easliy make boundaries by either never allowing boundary nodes to be added to the "narrow band" so they never become frozen, or by giving them very low F(x, y) values so agents prefer to go around them. Just be warned that the falling back to a "lower dimensional wavefront" (as described in the scicomp stack exchange link above) is needed if your F(x, y) values change too quickly, as they would with arbitrary boundaries.

Finally, you need to be able to compute

$$\nabla{T}$$

which is a vector with an x and y component (I'll call them dx and dy) that describes the rate of change in their respective directions. These are defined as:

$$dx(x, y) = Average(T(x + 1, y) - T(x, y), T(x, y) - T(x - 1, y) )$$

$$dy(x, y) = Average(T(x, y + 1) - T(x, y), T(x, y) - T(x, y - 1))$$

which continuum crowds also has you normalize (divide each dx(x, y) and dy(x, y) by $$\sqrt{dx(x, y)^2 + dy(x, y)^2}$$ unless they're both zero). If a neighboring node doesn't exist (say if it's outside the boundary or within an obstacle), you can just use the other neighboring node's value and not compute any average, and if neither neighbor node exists it probably makes sense to use some default value like 0. This gives us vectors which point in the direction of the optimal path to the goal, and you can move units along these optimal paths by moving them in this direction at a velocity equal to F(x, y).

Since we're working with a discrete grid, however, all units will be between four points. To find the value of a function at any point we need to interpolate between the four surrounding values:

```
float interpolateBetweenValues(float x, float y, float[,] array)
{
    int topLeftX = (int)Math.Floor(x);
    int topLeftY = (int)Math.Floor(y);

    if (topLeftX < 0 || topLeftX + 1 >= array.GetLength(0) ||
        topLeftY < 0 || topLeftY + 1 >= array.GetLength(1))
        throw new Exception("Out of bounds");

    float xAmountRight = x - topLeftX;
    float xAmountLeft = 1.0f - xAmountRight;
    float yAmountBottom = y - topLeftY;
    float yAmountTop = 1.0f - yAmountBottom;

    float averagedXTop = array[topLeftX, topLeftY] * xAmountLeft + array[topLeftX + 1, topLeftY] * xAmountRight;
    float averagedXBottom = array[topLeftX, topLeftY+1] * xAmountLeft + array[topLeftX + 1, topLeftY+1] * xAmountRight;

    float averagedYTotal = averagedXTop * yAmountTop + averagedXBottom * yAmountBottom;

    return averagedYTotal;
}

```
> 8 votes

---
Tags: path-finding
---


# Question
Title: Picture rendered from above and below using an Orthographic camera do not match
I'm using an orthographic camera to render slices of a model (in order to voxelize it). I render each slice both from above and below in order to determine what is inside each slice.

The model I render is a simple 'T' shape constructed from two cubes. The cubes have the same dimensions and have the same Y (height) coordinate. Here's a render of it in Blender:

I render this model once directly from above and once directly from below. My expectation was that I would get exactly the same image (except for mirroring over the y-axis). However when I render using a very low resolution render target (25x25) the position (in pixels) of the 'T' is different when rendered from above as opposed to rendered from below. See figure 2 and 3. The pink blocks are not part of the original rendering but I've added them so you can easily count/see the differences.

**Rendered from above**

**Rendered from below**

This is probably due to what I've read about pixel and texel coordinates which might be biased to the top-left as seen from the camera. Since I'm using the same 'up' vector for both of my camera's my bias only shows on the x-axis. I've tried to change the position of the camera and it's look-at by, what I thought, should be half a pixel. I've tried both shifting a single camera and shifting both cameras and while I see some effect I am not able to get a pixel-by-pixel perfect copy from both camera's.

Here I initialize the camera and compute, what I believe to be, half pixel. boundsDimX and boundsDimZ is a slightly enlarged bounding box around the model which I also use as the width and height of the view volume of the orthographic camera.

```
Matrix projection = Matrix.CreateOrthographic(boundsDimX, boundsDimZ, 0.5f, sliceHeight + 0.5f);
Vector3 halfPixel = new Vector3(boundsDimX / (float)renderTarget.Width, 0,
    boundsDimY / (float)renderTarget.Height) * 0.5f;

```

This is the code where I set the camera position and camera look ats

```
  // Position camera
                if (downwards)
                {
                    float cameraHeight = bounds.Max.Y + 0.501f - (sliceHeight * i);
                    Vector3 cameraPosition = new Vector3
                    (
                        boundsCentre.X, // possibly adjust by half a pixel?
                        cameraHeight,
                        boundsCentre.Z
                    );
                    camera.Position = cameraPosition;
                    camera.LookAt = new Vector3(cameraPosition.X, cameraHeight - 1.0f, cameraPosition.Z);

                }
                else
                {
                    float cameraHeight = bounds.Max.Y - 0.501f - (sliceHeight * i);
                    Vector3 cameraPosition = new Vector3
                    (
                        boundsCentre.X,
                        cameraHeight,
                        boundsCentre.Z
                    );
                    camera.Position = cameraPosition;
                    camera.LookAt = new Vector3(cameraPosition.X, cameraHeight + 1.0f, cameraPosition.Z);
                }

```

**Main Question** Now you've seen all the problems and code you can guess it. My main question is. *How do I align both camera's so that they each render exactly the same image* (mirrored along the Y axis)?

# Answer
> 2 votes
*This is a different view on the problem presented, which might help to avoid rasterization differences issues altogether*

Did you consider keeping everything in place, but scaling the Y of the model (cubes) by '-1' along the section plane? Then you will have everything exactly the same except for the objects being flipped upside-down - meaning you will get their down sides for your goal. Of course you will need to '-1' the normals and polygons facing directions too.

---
Tags: xna, c#, directx, texel
---


title: Multiple joysticks event handling

text:
# Question
Title: Multiple joysticks event handling
I want to make a game which is totally same idea as *"Who pressed the button answers the question"*.

I have 2 joysticks and both are connected to a pc. My application will be Winforms and I will develop it on Visual studio 2012.

I've used SlimDX, Sharpx so far I've found nothing for multiple joysticks. My problem is not mesuring the time until a player presses a button, all I want to know is which joystick / gamepad have pressed a button first.

Could you give me ideas about how I can achieve this ?

# Answer
> 1 votes
Something like this could help?

```
public static Joystick[] GetSticks()
    {
        var sticks = new List<SlimDX.DirectInput.Joystick>();
        foreach (DeviceInstance device in Input.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly))
        {
            // create the device
            try
            {
                var stick = new SlimDX.DirectInput.Joystick(Input, device.InstanceGuid);
                stick.Acquire();

                foreach (DeviceObjectInstance deviceObject in stick.GetObjects())
                {
                    if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
                        stick.GetObjectPropertiesById((int)deviceObject.ObjectType).SetRange(-1000, 1000);
                }

                sticks.Add(stick);

                Console.WriteLine(stick.Information.InstanceName);
            }
            catch (DirectInputException)
            {
            }
        }
        return sticks.ToArray();
    }

```

Source: http://www.chiefdelphi.com/forums/showpost.php?s=c50dbec48842d636565cf8ad9dad5914&p=1183912&postcount=2

---
Tags: c#, sharpdx
---


# Question
Title: curve objects in unity3d to wrap around an invisible cylinder?
Is there a way to transform objects in unity3d so that they can become curved? Imagine that I wanted to create a rectangle that wraps around an invisible cylinder, or that I wanted take a sprite image and roll it up like a roll of paper. Do you know how this would be done?

# Answer
> 1 votes
Yes, this can be done. There's nothing built into Unity that will do this, but you can modify the plane mesh that displays your image.

For this you'll need to access the mesh vertices. Deforming you mesh to a cylinder is the process of moving all the vertices of the mesh so their new position gives the mesh a different shape. In this case, a cylinder. There's a few strategies for moving the vertices to look like a cylinder, you can find a few here. As I suggest there, mapping your cartesian coordinates to cylindrical coordinates is a pretty simple way of doing things. A similar example can be seen here, except with spherical coordinates.

You can see that it's not a simple process, but it's certainly possible.

An alternative strategy would be to create a mesh in an external application, then create an animation of the mesh rolling up, likely with a number of bone transformations. Then you can simply play that animation in Unity, with your sprite mapped as the texture. If you need more information about creating that kind of animation, ask on the appropriate forum for the 3D modeling application you're using. You might try Blender along with the Blender SE.

---
Tags: unity, unityscript
---


# Question
Title: What is wrong with my specular phong shading
I'm sorry if this should be placed on stackoverflow instead however seeing as this is graphics related I was hoping you guys could help me: I'm attempting to write a phong shader and currently working on the specular. I came acros the following formula: `base*pow(dot(V,R),shininess)` and attempted to implement it (V is the posion of the viewer and R the reflective vector). This gave the following result and code:

```
Vec3Df phongSpecular(const Vec3Df & vertexPos, Vec3Df & normal, const Vec3Df & lightPos, const Vec3Df & cameraPos, unsigned int index)
{
    Vec3Df relativeLightPos=(lightPos-vertexPos);
    relativeLightPos.normalize();
    Vec3Df relativeCameraPos= (cameraPos-vertexPos);
    relativeCameraPos.normalize();
    int DotOfNormalAndLight = Vec3Df::dotProduct(normal,relativeLightPos);
    Vec3Df reflective =(relativeLightPos-(2*DotOfNormalAndLight*normal))*-1;
    reflective.normalize();
    float phongyness= Vec3Df::dotProduct(reflective,relativeCameraPos);
    if (phongyness<0){
        phongyness=0;
    }
    float shininess= Shininess[index];
    float speculair = powf(phongyness,shininess);
    return Ks[index]*speculair;
}

```

I'm looking for something more like this:

# Answer
I have found the answer (and now I feel stupid)

```
int DotOfNormalAndLight = Vec3Df::dotProduct(normal,relativeLightPos);

```

should have been

```
float DotOfNormalAndLight = Vec3Df::dotProduct(normal,relativeLightPos);

```

the end result looks like this:
> 2 votes

---
Tags: opengl, shaders, graphics, vector, normals
---


# Question
Title: How can I find the right UV coordinates for interpolating a bezier curve?
I'll let this picture do the talking. I'm trying to create a mesh from a bezier curve and then add a texture to it. The problem here is that the interpolation points along the curve do not increase linearly, so points farther from the control point (near the endpoints) stretch and those in the bend contract, causing the texture to be uneven across the curve, which can be problematic when using a pattern like stripes on a road. How can I determine how far along the curve the vertices actually are so I can give a proper UV coordinate?

EDIT: Allow me to clarify that I'm not talking about the trapezoidal distortion of the roads. That I know is normal and I'm not concerned about. I've updated the image to show more clearly where my concerns are.

Interpolating over the curve I get 10 segments, but each of these 10 segments is not spaced at an equal point along the curve, so I have to account for this in assigning UV data to vertices or else the road texture will stretch/shrink depending on how far apart vertices are at that particular part of the curve.

# Answer
A line is a list of connected points. For each point you'll need to calculate the X-Texture coordinate of that point, the Y coordinate will always be 0 for the upper point and 1 for the lower point.

After you have defined how long one texture segment is you can do so by stepping through all the segments you have generated and noting how much distance you have covered:

```
float pos = 0;
float textureLength = 200;
Points[0].TexCoord = 0;
for(int i = 1; i < Points.size(); ++i)
{
    pos += DistanceBetween(Points[i].Position, Points[i-1].Position);
    Points[i].TexCoord = pos / textureLength;
}

```
> 4 votes

# Answer
I'd suggest calculating UV according to section size (i guess U value would be constant), you know the size of the section, now calculate how many times road's texture should repeat along each edge (different V for each side according to size) and when you start drawing next section just set minimum values of V coordinate to the result of calculations of previous section.

```
Vector2 SetupSection(Vertex[6] aVertexes, Vector2 vPrevVValues)
{
    //lets consider that polygons are 0,1,2 and 3,4,5
    //where vertexes 0, 4 and 5 are bottom vertexes and 1, 2 and 3 are top vertexes (or min/max)
    //now lets calculate distance
    float fLeftDistance = (aVertexes[0].Position - aVertexes[1].position).Length();
    float vValue = fLeftDistance / fSizeModifier; //some constant decided by you
    aVertexes[0].v = aVertexes[4].v = vPrevValues.x; //Set left bottom to previous values
    aVertexes[5].v = vPrevValues.y; //set right bot to previous values
    vPrevValues.x += fLeftDistance;
    aVertexes[1].v = vPrevValues.x;

    float fRightDistance = (aVertexes[5].Position - aVertexes[3].position).Length();
    float vValue = fLeftDistance / fSizeModifier;
    vPrevValues.y += vValue;
    aVertexes[2].v = aVertexes[3].v = vPrevValues.y;
    return vPrevValue;//return new V values
}

```
> 1 votes

---
Tags: textures, uv-mapping, beziers
---


title: How to create groups in libGdx?

text:
# Question
Title: How to create groups in libGdx?
Can any of you please demonstrate a simple example on how to use groups in libGdx ? so if i move the parent, then all the children will move with it and same goes for rotation and scaling.

I looked for tutorials and example online but it seems that the latest version of libGdx did some changes to the Stage class.

Thank you

# Answer
Here is exactly what i needed to have, this class allow to create 3 images and rotate them as they are a single object, thank you all for your inputs.

```
public class LearnGdx extends ApplicationAdapter {

    public static final int WIDTH = 800;
    public static final int HEIGHT = 480;

    private Stage stage;
    private Group group;

    private float rotSpeed = 5;

    @Override
    public void create() {

        // Create a stage
        stage = new Stage(new StretchViewport(WIDTH, HEIGHT));

        // Create a group and add it to the stage.
        group = new Group();
        stage.addActor(group);

        // Create images and add them to the group.
        final Texture region = new Texture(Gdx.files.internal("circle.png"));
        Image img = new Image(region);
        Image img2 = new Image(region);
        Image img3 = new Image(region);

        img2.setColor(new Color(1, 0, 0, 1));
        img3.setColor(new Color(0, 0, 1, 1));

        group.addActor(img2);
        group.addActor(img3);
        group.addActor(img);

        // Images are positioned relative to the group...
        img.setPosition(0, 0);
        img2.setPosition(img.getWidth()/2, 0);
        img3.setPosition(-img.getWidth()/2, 0);

        // Group is positioned relative to the stage...
        group.setPosition(WIDTH / 2 - img.getWidth() / 2,
            HEIGHT / 2 - img.getHeight() / 2);
        group.setOrigin(img.getWidth()/2,img.getHeight()/2);

    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();

        if (Gdx.input.isKeyPressed(Keys.LEFT)) {
            group.rotateBy(rotSpeed);
        }
        if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
            group.rotateBy(-rotSpeed);
        }
    }
}

```
> 5 votes

---
Tags: libgdx
---


title: Achieve anisotropic filtering

text:
# Question
Title: Achieve anisotropic filtering
I want to set anisotropic filtering to my scene. I use SharpDX (DirectX 11) and C#.

How do i set up anisotropic filtering in my shader?

Currently i try that in the shader:

```
Texture2D tex;
sampler textureSampler = sampler_state
{
  Texture = (tex);
  MipFilter = Anisotropic;
  MagFilter = Anisotropic;
  MinFilter = Anisotropic;
  MaxAnisotropy = 16;
};

float4 PShader(float4 position : SV_POSITION, float4 color:COLOR, float2 tex0 : TEXCOORD0) : SV_TARGET
{
  float4 textureColor;
  textureColor = tex.Sample(textureSampler, tex0) * color;

  return textureColor;
}

```

I get my object, textured, but it is not filtered anisotropic. I can write everything in the Parameters, even invalid things and i don't get any errors. The result is the same, objects without applied anisotropic filtering.

Do i have to set that in the shader? Can i do that also with SamplerState? I tested that but i didn't get a result too.

Some steps what i have to set would be helpful.

---

Edit:

Here the current result. You can see the blurred planes of the cube in the middle:

As comparison the same scene in OpenGL with 16x anisotropic filtering. The planes of the cube are not blurred:

---

Second Edit:

Based on the idea, that in OpenGL the anisotropic filtering is a texture environment variable, maybe i have set some settings in the texture wrong?

```
Texture2D texture = (Texture2D)Texture2D.FromFile("Test.png");
ShaderResourceView tSRV = new ShaderResourceView(device, texture);
device.ImmediateContext.PixelShader.SetShaderResource(0, tSRV);

```

# Answer
As already mentioned in the comments, you cannot specify your sampler states in the shader unless you use the effect framework.

To utilize sampler states without the effect framework specify their location with the `register` keyword:

```
sampler anisotropySampler : register(s0);
sampler pointSampler : register(s1);

```

Then initialize the slots with the following C# code:

```
var anisotropySampler = new SamplerState(device, new SamplerStateDescription() {
    AddressU = TextureAddressMode.Wrap,
    AddressV = TextureAddressMode.Wrap,
    AddressW = TextureAddressMode.Wrap,
    Filter = Filter.Anisotropic,
    MaximumAnisotropy = 16,
});
var pointSampler = new SamplerState(device, new SamplerStateDescription() {
    AddressU = TextureAddressMode.Clamp,
    AddressV = TextureAddressMode.Clamp,
    AddressW = TextureAddressMode.Clamp,
    Filter = Filter.MinMagMipPoint,
});
Context.PixelShader.SetSamplers(0, anisotropySampler, pointSampler);

```

Each pipeline stage has a total of 16 sampler slots available.
> 2 votes

---
Tags: c#, shaders, sharpdx
---


# Question
Title: How do I find a unit vector of another in Java?
I'm writing a Java formula based on this tutorial: 2-D elastic collisions without Trigonometry. I am in the section **"Elastic Collisions in 2 Dimensions"**. Part of step 1 says:

> Next, find the unit vector of n, which we will call un. This is done by dividing by the magnitude of n.

My below code represents the normal vector of 2 objects (I'm using a simple array to represent the normal vector).

```
int[] normal = new int[2];
normal[0] = ball2.x - ball1.x;
normal[1] = ball2.y - ball1.y;

```

I am unsure what the tutorial means by dividing the magnitude of *n* to get the *un*.

What is *un*? How can I calculate it with my Java array?

# Answer
> 1 votes
First off, using arrays is not the best way to represent Vector information in Java. Second, use floats. Take a look at LibGDX Vector2 class.

The magnitude of a vector is it's length, obtainable with the Pythagorean theorem:

```
a² = b² + c²

```

in your case, you can obtain it by:

```
float[] normal = new float[2];
normal[0] = ball2.x - ball1.x;
normal[1] = ball2.y - ball1.y;
float magnitude = (float)Math.Sqrt(normal[0]*normal[0] + normal[1] * normal[1]);
float[] un = new float[2];
un[0] = normal[0] / magnitude;
un[1] = normal[1] / magnitude;

```

let me reassure you that using Arrays is NOT good. With a properly Vector class it should be like:

```
Vector2 normal = new Vector2();
normal.set(ball2);
normal.sub(ball1);
Vector2 un = new Vector2();
un.set(normal);
un.normalize();

```

If you were going to a language where Operator overloading is possible:

```
Vector2 normal = ball2 - ball1;
Vector2 un = normal / normal.length();

```

---
Tags: java, vector
---


# Question
Title: (Phaser) Preload Future States in Create?
I'm a first time user of Phaser, been trying to make a simple point and click type game. I'm trying to keep things very modular, so I'm defining a list of levels (states) in a JSON, and then every level has its own JSON containing the objects within that level.

However, I'm encountering an issue in that, when changing states, I get a black flash while the assets for the next state load (this happens whether I iterate through the JSON list or define everything manually). From what I've read, all sprites should be loaded in the preload stage, however, by doing this I'm causing that tiny but noticeable black pause.

I know one way would be to simply load every asset at the start of the game, but that seems incredibly inefficient (wouldn't that fill up the memory immensely?). I would rather load a state's assets from the "parent" state. However, in my quick test (which maybe I did wrong) it seems that game.load doesn't work properly if done within the create stage? What is the best approach to doing this?

# Answer
> 6 votes
What you're doing is multi-part loading assets, which is extremely common and a very sensible approach. You cannot avoid the 'pause' or black screen though, because the assets have to come down the wire at some point, right?

So all you can do is make this process as attractive and seamless as possible. Either a nice preloader, or maybe showing the next part of a story as the assets load? At this stage it's a more conceptual issue than a technical one.

You absolutely can load assets outside of a preload function, and there's an example showing how to do it here: http://examples.phaser.io/\_site/view\_full.html?d=loader&f=load+events.js&t=load%20events

But you've still got to cater for what happens during this process, no matter when it's started.

---
Tags: loading, state, preload, phaser
---