title: 3-in-a-row or more logic

text:
# Question
Title: 3-in-a-row or more logic
This is a bit more difficult than it seems and the one other post on here isn't sufficient. You have a row of *n* items, and each item could be any one of 5 colors. You need to find if there are any runs of 3 or more items together of the same color and destroy them.

Yellow, Red, Blue, Green, Red, Red - destroy nothing

Red, Red, Red, Green, Yellow, Red - destroy the first set of 3 Red, but not the 6th red

Red, Purple, Red, Red, Red, Red - destroy only the set of 4 Red

You can't simply check each item to see if the item previous to it has the same color, and destroy them when that happens twice in a row (meaning 3 matching items), because then you are not accounting for the fact that there could be 4 or more in a row. Are there any robust algorithms out there for this?

# Answer
> 4 votes
This is a very simple programming problem.

Here's a straight forward solution.

For every piece

1. check if previous two pieces are same color
2. if true, destroy those three pieces.
3. for every piece after that, if current color == destroyed color, destroy it. If not, break out of the loop.

If it's possible to have more than one set of three at once in a single row (e.g. 3 reds then 3 blues), you'll have to run the loop multiple times until it doesn't destroy anything.

# Answer
> 6 votes
I think this can be done amazingly easy with regular expressions (provided you can provide the gameboard as string).

Once you have the board in stringform, use the following regex:

```
(\w)         //capture any letter
(\1{2,})     //capture that letter again twice or more.

```

The beauty of this is that it works on any number of items, and any amount of different items/colours.

# Answer
> 2 votes
Use two nested loops. The outer one will loop over the array and will be treated as the beginning position for a possible run. The inner will look for the end of the run by starting at the current beginning position and iterating as far as it can on the same color.

```
for (int i = 0; i < n;)
    int j = i+1;
    for (; j < n; ++j)
        if (color[j] != color[i])
            break;
    // at this point, there is a run of size j - i from element i to j - 1
    if (j - i >= 3)
        // mark elements for destruction
    // start looking for more runs at the end of the current run
    i = j;

```

This should find all the runs of 3 or more. I wrote "mark elements for destruction" rather than "destroy elements" because it's simpler to find multiple runs this way, since you don't have to worry about the loop indices changing due to destroying a bunch of elements in the middle of iteration. You can go back through in a second pass and actually destroy them.

# Answer
> 1 votes
While I basically agree with Nathan's answer, I wanted to emphasize that (a) another reason to find all the matches at once is for presentation purposes: it just *looks* better to blow them all up together — and in the more-than-one-dimensional case, it can be relevant because not all matches will stay matches after partial destruction (think of a plus shape on a 2d match-3), and (b) if this is like most match-3s, you'll probably need an outer-outer loop for handling the 'nested' matches that appear (imagine a situation like RGGGRR). What's more, in the 1d case you can actually get by with a single loop through the interior and some careful tests. My structure would look something like this:

```
bool bMatchesFound;
matchList.clear();
do {
  bMatchesFound = false;
  eColor matchColor = gameBoard[0].color;
  int startPos = 0;
  for ( int curPos=1; curPos < gameBoard.len(); curPos++ ) {
    if ( gameBoard[curPos].color != matchColor ) {
      // we've ended a run; now check to see if it was long enough
      if ( curPos-startPos >= 3 ) {
        // It was - go ahead and add it to our list of matches
        matchList.add(Match(startPos, curPos-1, matchColor));
        bMatchesFound = true;
      }
      // now, regardless, make sure we start a new match-run here
      startPos = curPos;
      matchColor = gameBoard[curPos].color;
    }
  }
  // Finally, check for a match at the end - if our 'last' startPos
  // was far enough back.
  if ( startPos <= gameBoard.len()-3 ) {
    matchList.add(Match(startPos, gameBoard.len()-1, matchColor);
    bMatchesFound = true;
  }
  // 'destroy' all our matches (with suitable pyrotechnics)
  destroyMatches(matchList);
  // and keep doing this until we run out of matches
} while ( bMatchesFound );

```

---
Tags: algorithm, logic
---


# Question
Title: Online MMO collision detection for players & walls
Let's assume the following:

* I have a server which stores the player's position (float x, float y, float z)
* Client sends the server it's updated position ever 250ms or so.
* Server has bounding boxes for all buildings & players ( Let's say each wall has it's own AABB or OBB)
* For broad-phase collision detection, I use spatial hashing based on the bounding boxes.
* Client does full-on triangle level collisions locally.

My question: \- How can I quick calculate if a player has passed through a wall on the server only using AABBs or OBBs. Or, is there no way to do that without going to triangle-level collision detection. Maybe some other data structure? Any help would be appreciated.

# Answer
> 1 votes
As many other answers indicated, you really should not let the client handle crucial data such as collision detection or positioning. If you let the client determine where it is going and if it can go there, you are making your game an absolute sitting duck for ill-intentioned players and hackers.

I highly suggest you redesign your client-server relations so the client only sends input information and receives data about the world and other objects in it, leaving all the processing to the server.

To minimize the amount of data sent back and forth, the client should send only input messages such as "Player started/ended pressing W", "Player rotated the camera by X,Y,Z degrees" (the server needs to know this if moving the camera during movement will change locomotion's direction), etc. The server will then receive such data and process player's position and whatnot, accounting for collision and whatnot. If player is enabled to move (because there were no collisions with walls), both client and server will update the character's position within the world. If a collision comes to occur, the server will send a "HALT!" message and send the last valid position, and the client will pull the character back to such position. This saves the server from having to discretely send position data at given intervals.

Such method is, obviously, very costly serverside and is prone to position flickering clientside when the player is experiencing lag or high latency (which is not very bad on passive MMOs such as WoW, but it becomes a problem on very action-filled games such as Team Fortress 2, GunZ and Combat Arms). At least it will solve your presented problems and make the game a bit less hackable.

**About your question per se**: it depends on how the world is modelled. If the only non-passable geometry in the world is comprised of perfectly rectangular walls and nothing else, then you can get away with just OBB collision detections. However, if there are things such as mountains or round buildings, then you'll have to use per-triangle collisions and use some broadphase algorithm to only do such costly detections when absolutely necessary. A tip: you don't have to use the actual models for collision detection. You can make invisible meshes -with lower poly counts and simplified geomtery if compared to the actual models- to serve as bounding meshes and use their polygons on the per-triangle collisions.

# Answer
> 0 votes
Usually the situation is simply that if a player has cheated, you don't want them in the game. So in an MMO you can just disconnect them - no need for repositioning etc. Or if you're feeling generous you just send a message to put them at their previously legal position.

Beyond that, there's nothing specific to MMOs about how you do collision detection, and there are plenty of resources on how to do collision with bounding boxes.

If you're finding that you have obstacles so small that 2 positions sent from the player might make it seem like they passed through the obstacle, then you need to increase the position sending rate. No amount of calculation based on individual triangles can overcoming the fundamental problem of not having enough data about the trajectory. Just send more updates.

(PS. It's usually unwise to implement collisions between players and other players because many will use this to cause trouble by blocking players from their intended destination and perhaps denying them the ability to move entirely. So be careful what you do there.)

---
Tags: c++, java, collision-detection, mmo, server
---


# Question
Title: Efficiently storing game states history for physics?
I would like to store the history of a box2d simulation. Currently I can't find any built-in mechanism for that.

I need to store the states of all non static objects in the last second, mainly for network latency correction.

I think I will use a multi dimensional array for all the rigid bodies positions and forces.

Is there a better way to achieve what I'm trying to do?

# Answer
As far as my personal experience spans, I think you are really better off saving crucial data on data structures or arrays/matrices.

I suggest you don't store all data eagerly, though. You should only store data of objects that moved or had some change to it's resulting force on given frame. This will save you from storing data of objects that are standing still and not participating in any active collisions.

If you are in a scenario with a low density of objects movements and/or collisions over time, you can even do crazy things such as Braid's time rewinding thing, since storing past states (or past state changes) wouldn't be too costly.
> 3 votes

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


title: Pathfiding for groups of agents

text:
# Question
Title: Pathfiding for groups of agents
How can we refine this path search method to make group movement more elegant? I'm trying to make a RTS-style game, using a 2d tiled gameworld. I have implemented an A\* pathfinding algorithm which works well enough for single units. I've also make some functionality to make agents walk around other agents they stumble across on their way.

Here is some of my code:

```
def move(self, agent, clickbox, nogolist):
    impassable = []
    impassable.extend(nogolist)
    mapinfo1 = MapInfo(self.map_layout.finalsize,self.map_layout.finalsize,impassable)
    graph, self.nodes = self.make_graph(mapinfo1)
    paths = AStarGrid(graph)
    for c in self.map_layout.all_map_objects:
        if clickbox.box.collidepoint(c.checkpoint):
            path = []
            if len(agent.travel_list) > 1:
                v = agent.travel_list[1]
                start = self.nodes[v[0]][v[1]]
            elif len(agent.travel_list) == 1:
                start = self.nodes[agent.grid_pos[0]][agent.grid_pos[1]]
            end = self.nodes[c.gridnumber[0]][c.gridnumber[1]]
            path = paths.search(start, end)
            try:
                agent.target = self.convert_path(path)
                agent.travel_list = self.waypoints((agent.grid_pos[0],agent.grid_pos[1]), path)
            except:
                print 'road error'

```

When one or more agents are selected and the player right-clicks somewhere, self.move gets called on each agent individually, they are at this point still ignorant of other agents positions. The next part is where I try to have agents not walk over each other, or just stop if 'travel\_list' only contains one more step, and another agent occupies it.

```
if not len(self.traveling_agents) == 0:
    for a, b in combinations(self.agent_list, 2):
                self.resolve(a, b, self.nogolist)
                self.resolve(b, a, self.nogolist)

def resolve(self, a, b, nogolist):
    try:
        if len(a.travel_list) > 1 and b.travel_list[0] == a.travel_list[-1]:
            a.travel_list = a.travel_list[:-1]
            a.target = a.target[:-1]
            if a.travel_list[1] == b.travel_list[0]:
                self.traveling_agents.remove(a)
        elif len(a.travel_list) > 1 and b.travel_list[0] == a.travel_list[1]:
            path = []
            go = a.travel_list[0]
            goal = a.travel_list[-1]
            impassable = []
            impassable.append(b.travel_list[0])
            impassable.extend(nogolist)
            mapinfo1 = MapInfo(self.map_layout.finalsize,self.map_layout.finalsize,impassable)
            graph, self.nodes = self.make_graph(mapinfo1)
            paths = AStarGrid(graph)
            start = self.nodes[go[0]][go[1]]
            end = self.nodes[goal[0]][goal[1]]
            path = paths.search(start, end)
            a.target = self.convert_path(path)
            a.travel_list = self.waypoints((go[0],go[1]), path)
            del impassable
    except: a.stop()

```

This works reasonably well for solo agents encountering other stationary solo agents. But when moving in a group towards a common target, this method falls way short of what would be desired. What can we do to achieve smoother group movement like what is seen in some of those old school RTS games?

For some additional insight on my code, check my previous entry on implementing the A-star search algorithm: https://stackoverflow.com/questions/14390458/how-to-structure-an-adjacency-list-for-this-a-program/

# Answer
> 4 votes
I suggest you implement some flocking behavior principles on the movement method. If you don't know about flocking algorithms, here are some useful links and tutorials:

http://harry.me/blog/2011/02/17/neat-algorithms-flocking/

http://www.lalena.com/AI/Flock/

The trick would be the following:

1- The movement and its direction each frame will be controlled by a movement vector.

2- The A\* pathfinder will return an array of waypoints the entity needs to go thru so it will end up at the desired location without running into walls and whatnot.

3- This vector is the resulting sum of other vectors generated by the flocking algorithm. The some common vectors are *cohesion*, *separation* and *alignment* along with a vector pointing to the current waypoint (*heading*).

This is not a silver bullet, though. The original flocking theory doesn't account for walls or obstacles. Neither implementing pathfinding nor combining it with flocking is as trivial as it might seem.

---
Tags: path-finding, python, pygame
---


# Question
Title: How can i scale up a bounding box in Xna?
In Xna a spritebatch can be passed a value for scale. I have A bounding box Rectangle that i have a border drawn around my sprite using the bounding box rect.

Now my question Scale can make the sprite go up just fine,but how can i get the bounding box rect to scale up with the scale propertie?

# Answer
> 1 votes
Just adjust the size of the bounding box to factor in the scale.

i.e.

`Rectangle boundingBox = new Rectangle(texture.Width * scaleX, texture.Height * scaleY)`

`texture` refers to the `Texture2D` instance of your image. `scaleX` and `scaleY` are the horizontal and vertical scaling components respectively, with the trivial case of `scaleX = scaleY` when you scale uniformly.

**Edit:** if the origin of the image is not the default (top-left corner), you should also adjust your rectangle by the origin point.

---
Tags: xna, xna-4.0
---


# Question
Title: Detect multitouch (two fingers touch) on a sprite to apply pinch zoom behaviour
I am using andengine, want to move, zoom and rotate multiple sprites individually on a scene. I have achieved "move" but for pinch zoom i am unable to get the event to two fingers' touch. Below is the code:

`public class Main extends SimpleBaseGameActivity` {

```
private Camera camera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private ITextureRegion mFaceTextureRegion;
private ITextureRegion mFaceTextureRegion2;
Sprite face2;

private static final int CAMERA_WIDTH = 800;
private static final int CAMERA_HEIGHT = 480;

@Override
public EngineOptions onCreateEngineOptions() {
    camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
    EngineOptions engineOptions = new EngineOptions(true,
            ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
                    CAMERA_WIDTH, CAMERA_HEIGHT), camera);

    return engineOptions;
}

@Override
protected void onCreateResources() {
    BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

    this.mBitmapTextureAtlas = new BitmapTextureAtlas(
            this.getTextureManager(), 1024, 1600, TextureOptions.NEAREST);
BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas,
    // this, "ui_ball_1.png", 0, 0, 1, 1),
    // this.getVertexBufferObjectManager());
    this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory
            .createFromAsset(this.mBitmapTextureAtlas, this,
                    "ui_ball_1.png", 0, 0);
    this.mFaceTextureRegion2 = BitmapTextureAtlasTextureRegionFactory
            .createFromAsset(this.mBitmapTextureAtlas, this,
                    "ui_ball_1.png", 0, 0);
    this.mBitmapTextureAtlas.load();
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);

}

@Override
protected Scene onCreateScene() {

    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene();
    scene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f));

    final float centerX = (CAMERA_WIDTH - this.mFaceTextureRegion
            .getWidth()) / 2;
    final float centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion
            .getHeight()) / 2;

    final Sprite face = new Sprite(centerX, centerY,
            this.mFaceTextureRegion, this.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
                final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
            this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2,
                    pSceneTouchEvent.getY() - this.getHeight() / 2);
            return true;
        }
    };
    face.setScale(2);
    scene.attachChild(face);
    scene.registerTouchArea(face);

     face2 = new Sprite(200, 200, this.mFaceTextureRegion2,
            this.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
                final float pTouchAreaLocalX, final float pTouchAreaLocalY) {

            switch(pSceneTouchEvent.getAction()){
            case TouchEvent.ACTION_DOWN:

                int count = pSceneTouchEvent.getMotionEvent().getPointerCount() ;

                for(int i= 0; i <count; i++)
                {
                    int id = pSceneTouchEvent.getMotionEvent().getPointerId(i);
                }
                    break;
            case TouchEvent.ACTION_MOVE:

                        this.setPosition(pSceneTouchEvent.getX() -this.getWidth() / 2, pSceneTouchEvent.getY()-this.getHeight() / 2);

                    break;

            case TouchEvent.ACTION_UP:

                    break;

            }
            return true;
            }
        };

    face2.setScale(2);
    scene.attachChild(face2);
    scene.registerTouchArea(face2);

    scene.setTouchAreaBindingOnActionDownEnabled(true);
    return scene;
}

```

}

This line

```
int count = pSceneTouchEvent.getMotionEvent().getPointerCount() ;

```

should set **2** to the **count** variable if i touch the sprite with to fingers, then i can apply zooming functionality (setScale method) on the sprite by getting the distance between the coordinates of two fingers. Can anyone help me? **why it does not detect two fingers? and without this how can i zoom the sprite on pinch of two fingers**?

I am very new to game development, any help would be appreciated. Thanks in advance.

# Answer
add this code in `onCreateEngineOptions()`

```
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera);
        engineOptions.getTouchOptions().setNeedsMultiTouch(true);

        if(MultiTouch.isSupported(this)) {
            if(MultiTouch.isSupportedDistinct(this)) {
                Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
        }

```
> 1 votes

# Answer
I think first you have to look example provided by the AndEngine that is about pinch zoom functionality. Only this example is capable to provide enough guidance to achieve zoom in/out facility.

http://code.google.com/p/andengineexamples/source/browse/src/org/anddev/andengine/examples/PinchZoomExample.java

Also you have to add another extension for multi-touch support to you project.

https://github.com/nicolasgramlich

Above link contain information about all the andengine extension, you have to pick that you need.
> 0 votes

---
Tags: sprites, andengine, multitouch
---


# Question
Title: How to create texture coordinates for a spritesheet with lwjgl
Using lwjgl and slick-util I've been trying to use certain pieces of a spritesheet as textures. lwjgl uses glTexCoord2f(); to map coordinates to individual vertices, and the coordinates it takes in are normalized (between 1 and 0), so I've been using this code to make the coordinates only use a small piece of the full Texture:

```
glTexCoord2f(0 / 128, 0 / 128); glVertex2f(0, 0);
glTexCoord2f(0 / 128, 8 / 128); glVertex2f(0, 32);
glTexCoord2f(8 / 128, 8 / 128); glVertex2f(32, 32);
glTexCoord2f(8 / 128, 0 / 128); glVertex2f(32, 0);

```

but whenever I used normalized coordinates that are a fraction of the images size I just get a solid square that had 50% alpha.

My question is: what am I doing that's making the texture coordinates screw up? Is there a better way to go about this?

Any help is appreciated, thanks in advance!

# Answer
> 2 votes
You are dividing an integer with an integer: `8 / 128`, which results zero. Change it to floating point division: `8.0f / 128.0f`.

# Answer
> 1 votes
3Texture coordinates for a sprite sheet can be obtained simply by using the number of sprites wide and the number of sprites high. It's a simple modulus operation using that information. Something like the following will return the coordinates for a textured quad:

```
public static Vector2f[] calculateUVMapping(int texture, int atlasWidth, int atlasHeight) {
    int textureIndex = texture;

    int u = textureIndex % atlasWidth;
    int v = textureIndex / atlasHeight;

    float xOffset = 1f / atlasWidth;
    float yOffset = 1f / atlasHeight;

    float uOffset = (u * xOffset);
    float vOffset = (v * yOffset);

    Vector2f[] UVList = new Vector2f[4];

    UVList[0] = new Vector2f(uOffset, vOffset); // 0,0
    UVList[1] = new Vector2f(uOffset, vOffset + yOffset); // 0,1
    UVList[2] = new Vector2f(uOffset + xOffset, vOffset + yOffset); // 1,1
    UVList[3] = new Vector2f(uOffset + xOffset, vOffset); // 1,0

    return UVList;
}

```

Where `texture` is the index of the sprite you want, `atlasWidth` is the number of evenly sized sprites in the entire texture width and `atlasHeight` is the number of evenly sized sprites in the entire texture height.

Then you can see the coordinates labeled in the comments, it will return an array of coordinates like: \[(0,0),(0,1),(1,0),(1,1)\].

`texture` counts the index from left to right, top to bottom. So for example if I wanted to get the 6th sprite in a atlas that was 5 sprites wide and 10 sprites tall, I would use `calculateUVMapping(6,5,10);` That sprite would be the one in the second column of the second row (because we start at `0`).

---
Tags: java, lwjgl, spritesheet
---


# Question
Title: Unity3D GUILayout Window Wont Show Components
I am fairly new to Unity, but picking things up quick. This is actually one of the first problems I have come across that has me stumped.

I am trying to print a good amount of components onto my GUI **on top** of my window.

Although, I can only see half of only one component at the upper left hand side of my window, in which the label says "Name". I can actually only see Na and half of the m.

(If I do NOT use the window, and just paint my components out on my OnGUI everything will paint just fine and looks exactly how I want)

To me, this sounded like some sort of Rect(); issue or something along the lines of the width and height not being set properly...Although they are.

Ill provide all the code that has any relation to the GUI. (There is only one object this script is attached to and it inherits from MonoBehavior)

You will notice that the Rects() or any Width/Hieght will be set to some high number, it was just to make sure it wasnt that line of code screwing up my window.

```
public GUISkin mySkin;
public Rect windowRect = new Rect();

void OnGUI() {
    GUI.skin = mySkin;
    DisplayBox();
}

private void DisplayBox() {
     windowRect = GUILayout.Window(0, windowRect, DoMyWindow, "", GUILayout.Width(800));
}
void DoMyWindow(int windowID) {
    DisplayName();
    DisplayPointsLeft();
    DisplayAttributes();
    DisplayVitals();
    DisplaySkills();
    DisplayCreateButton();
    DisplayResetButton();
}

```

These functions in the DoMyWindow just call GUI.Component statements to paint the gui.

Like I said above, if I dont use the window everything works perfect.

Also, you'll notice that the windowRect has no params. Its public and they are altered to extremely high numbers in the inspector. Still no result

What am I doing wrong?

# Answer
> 1 votes
Figured it out.

Changed

```
windowRect = GUILayout.Window(0, windowRect, DoMyWindow, "", GUILayout.Width(800));

```

to

```
windowRect = GUILayout.Window(0, windowRect, DoMyWindow, "", "window");

```

Hope this helps someone later on.

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


# Question
Title: Having Your Own Copyrighted App Automatically After Publishing
I have a question regarding for the game app and in business. You see, I decided to publish an app to Google Play. When I published it, does this app automatically declared that this app is copyrighted or copyright protected by the publisher and creator like me itself or not? If not, does it have to seek something or required to register this app for copyright authentication via online or at office or not?

# Answer
The moment you create a creative work, you automatically have an exclusive copyright on it. This is guaranteed by various international copyright treates (like the Berne Convention) which are recognized by almost all countries worldwide.

In some jurisdictions you can register a copyright for a work (in the USA, you can do so at the United States Copyright Office), but this is optional and not necessarily required to enforce your rights in court when you have other prove that you created the work.

An explicit copyright notice ("Copyright ©2013 John Doe, all rights reserved") is not required either. It is just used as a friendly reminder to people that you are the copyright owner and that you care about your copyright. But such a notice is not required to enforce it, should someone violate it.

When you publish something on google play, you give google a non-exclusive license to distribute your software (otherwise they wouldn't be allowed to publish it). Non-exclusive means that you retain the copyright. You can still publish it yourself, license it to other entities and sue entities which distribute it without your permission.
> 3 votes

---
Tags: legal, copyright, business, appstore, google-play
---


# Question
Title: How do I properly use particle simulation in Unity?
So I'm using Unity's simulate function to pre-render particles. It seems that simulate is not quite working as to what I expect. It's most likely a setting that I missed. But I just really cannot find the issue.

This is from inside the editor, I clicked on the particle object and just let it run. This is what I'd like.

This is after I've run the game a little bit, then hit pause. This is what is currently happening, for some reason the particles get bigger.

Here is the script that I've attached.

```
public float initTime;
public ParticleEmitter partEmitter;
// Use this for initialization
void Start () {
    for (float i = 0.1f; i < initTime; i = i + 0.1f) {
        partEmitter.Simulate(i);
    }
}

```

I've run this scene in both Unity 3.5 and in Unity 4.0. Same thing happens in both versions.I'm pretty sure that it's something to do with the script. But I've tried many different pieces of code and they are all similar and do the same thing.

# Answer
The function documentation states:

```
function Simulate (deltaTime : float) : void

```

That is, the function parameter is a **time delta**, a step in time. It is not a certain moment in time.

Physical simulations work based on discrete steps in time. And the stability of many simulations (or rather the error within a simulation) is directly related to the size of a time step you take.

In your code, you're taking increasingly large steps in time. While single particles might put up with that for a while, given a sufficiently large step they might start to become unstable.

Most likely your problem will be resolved by taking a number of fixed time steps of a relatively small size.

```
public float initTime;
public ParticleEmitter partEmitter;
// Use this for initialization
public float deltaTime = 0.1f;
void Start () {
    for (float i = 0.0f; i < initTime; i += deltaTime) {
        partEmitter.Simulate(deltaTime);
    }
}

```

I have taken your 0.1f here (a tenth of a second), but this might have to be even somewhat lower.
> 1 votes

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


# Question
Title: How can I test on a device I don't have?
I received a report that my application fails to run on a specific device (smartphone).

However, not only I don't have access to that device, but they're also quite rare, and I'm not going to buy one just to fix this problem.

Unfortunately, it is imperative that I support that device, as it is a requirement to get published on a store I need to publish on.

Do you guys have any ideas on what can you do when you need to test on a device you don't and can't have?

# Answer
> 8 votes
I wrote a tip/trick on CodeProject that discusses this very problem.

Samsung are essentially providing free access to actual devices via the web over here, I'm not sure if the same thing is provided by any other vendors though.

# Answer
> 1 votes
If this is an android phone then you can run an emulator, with the same screen size and stuff as the device you want to test on. It will not be perfect but it will let you see if the screen-size is the problem (which is could be) and you can change other setting in making the emulator.

http://developer.android.com/tools/devices/emulator.html

That might help you. If it is not android there may be other emulators out there for iOS and Windows ect...

---
Tags: testing
---


# Question
Title: 3d transformation of game world keeping gameplay 2d - COCOS2D 2.0
I want to rotate the game world, may be loading another .tmx file for another dimensions when user want to switch dimension.

The effect what I am looking for is something like the 'side' transition in Fez.

What I have thought of till now:

1. rotating `CCCamera` will be mandatory.
**Question**: How will I have the other part of the level in place while the camera rotates/rotating?
2. I can load a `CCSprite` and rotate it accordingly to the 3rd dimension. phew..!!
**Question**: When the camera and world is rotated, will the player controls work properly.. I think not...?
3. I think a better option would be to checkout with COCOS3D... there I could implement 3d world... right?
**Question**: Not sure how well 2d dynamics will work there as I want to user Box2d as physics engine..

Could anyone provide suggestions?

# Answer
Take a look at this example code. In it, the author is manipulating a Wavefront OBJ (3D) using Cocos2d. It's a bit overkill for what you're doing, but if you spend some time with it, you ought to be able to manipulate a 3D cube with whatever you want drawn on a surface of the cube (e.g., your level).

A much simpler solution would be to go with one of the existing scene transitions built in to Cocos2d. Take a look at CCTransitionFlipX. It's not exactly what you're asking for, but it's very similar and might be satisfactory for you. Here's a demonstration of the scene transitions from github.

To some extent, you're trying to fit a square peg in a round hole. (Or maybe I should've said, you're trying to fit a 3D cube in a 2D circle). Cocos2D is not really intended as a 3D platform, although because of the limitations of Cocos3D, you're not the first to attempt to try workarounds in Cocos2D. I think it's worth seriously considering switching engines to one designed for 3D (like Cocos3D, as you mentioned). Once you have one 3D element, you're bound to want more.

You asked, "How will I have the other part of the level in place while the camera rotates/rotating?" This is a fairly broad question. Obviously you will have to do some (or all) of the loading of the next level before you can render it to a surface of a 3D object and render it to the scene.

Finally, it is indeed possible to use Box2D with the Cocos3D engine. Here's a link to a demo that implements Box2D in Cocos3D. Here's another. There aren't a ton of examples or discussion on how to do this, so you're going to be struggling with some issues to make this work, but you might find this page helpful, where someone shared a few of their lessons attempting to combine the two.

Hope this helps.
> 3 votes

---
Tags: ios, game-mechanics, cocos2d-iphone
---


title: Subclasses of GameInfo and Input in UDK

text:
# Question
Title: Subclasses of GameInfo and Input in UDK
We have two main subclasses of GameInfo for the two game types we have. I'm wondering if it's possible to get one of these to read a different .ini file because we'd like to move a few of the controls to different buttons for that mode.

It looks to me like it's just going to read Input.ini for this, regardless of the game type.

# Answer
> 3 votes
You could create a subclass of PlayerInput with its own section with keybinds in the Input.ini.

If the controls are different based solely on the map/GameInfo, you can make a subclass of your PlayerController, set its `InputClass` to your new PlayerInput subclass in defaultproperties, then in your GameInfo you can set `PlayerControllerClass` to your new PlayerController type. So that GameInfo will spawn that PlayerController with that PlayerInput type.

If instead you want to swap it at runtime, you can skip creating the PlayerController subclass. You'll have to find and remove the old PlayerInput from you PlayerController's `Interactions` array, set your `PlayerInput` to `none`, change your `InputClass`. After that, you can call InitInputSystem() and it'll reinitialize your input with the new class.

---
Tags: udk
---


# Question
Title: NGUI UIInput - Reset value of password field
How do I reset the value of a NGUI UIInput control that marked `Is Password`. If I set `.text` to "" I still see a bunch of \********** rather than the `.defaultText`.

Basically if the user types the wrong password during login, I want to clear the field and have is display the default text again.

## Update

If I click into the field and back out, the default text shows, but until I do that I get the \**********.

Code:

```
// Show the Create dialog
public void ShowCreate() {
    panelWait.gameObject.SetActive(false);
    panelLogin.gameObject.SetActive(false);
    panelCreate.gameObject.SetActive(true);

    username = loginUsername.text;
    createUsername.text = username;
    createPasswordA.text = "";
    createPasswordB.text = "";
}

```

Image:

# Answer
> 1 votes
Normally setting the `text` member to `""` should clear the `UIInput`. However, for this to take effect, the widget does need to have the focus (`selected` needs to be `true`). If your widget does not immediately clear, you can set its focus manually.

In your case that would be:

```
createPasswordA.selected = true;
createPasswordB.selected = true;
createUsername.selected = true;

```

That should do the trick.

---
Tags: unity
---


# Question
Title: OpenGL, fetching the names of all uniform blocks in your program
I want to auto-bind uniform blocks with certain named values to certain binding points when I compile a shader. For example, I have some basic, default fixed binding points that are always used for certain things like:

```
0 Camera
1 Model
2 Material
3 Lights

```

At the moment I'm binding manually by finding the index of a named block with glGetUniformBlockIndex, and then binding it with glUniformBlockBinding. What I'd like to do is fetch the set of all block names in my shader program. When I iterate with glGetActiveUniformsiv, I get a list of all uniforms, which excludes block names.

Is there any way to do this without testing and failing each of my above names to see if it's an active block with glGetUniformBlockIndex? There's no glGetActiveUniformBlocksiv, is there...

# Answer
This is pretty easy; just the program introspection API to fetch the indices. First, ask how many uniform blocks there are:

```
GLint numBlocks;
glGetProgramiv(prog, GL_ACTIVE_UNIFORM_BLOCKS, &numBlocks);

```

All of your uniform block indices are on the half-open range \[0, `numBlocks`). So iterate through them and get their names.

```
std::vector<std::string> nameList;
nameList.reserve(numBlocks);
for(int blockIx = 0; blockIx < numBlocks; ++blockIx)
{
    GLint nameLen;
    glGetActiveUniformBlockiv(prog, blockIx, GL_UNIFORM_BLOCK_NAME_LENGTH, &nameLen);

    std::vector<GLchar> name; //Yes, not std::string. There's a reason for that.
    name.resize(nameLen);
    glGetActiveUniformBlockName(prog, blockIx, nameLen, NULL, &name[0]);

    nameList.push_back(std::string());
    nameList.back().assign(name.begin(), name.end() - 1); //Remove the null terminator.
}

```

BTW, if you're doing this because you think it's faster, stop. First, performance is irrelevant since this is one-time setup code. Second, you're doing this for maybe 4-8 blocks at most. It's not going to affect actual performance in any way. So really, there's no reason to not just get the indices by name if that's what you're ultimately doing. The introspection API is for when you *don't know* what is there.
> 8 votes

---
Tags: opengl, shaders
---


title: From maya to c++ and opengl

text:
# Question
Title: From maya to c++ and opengl
I want to load an object created with Maya in c++ with opengl, how could I do this?

Thank you.

# Answer
> 4 votes
Maya creates objects in a proprietary file format, and the approach to convert these objects in a way that can be read in C++ is very open-ended and left for the user to decide.

Since you don't give much detail, I think using the ASSIMP library is the most straightforward solution. Maya supports export to OBJ (and I think 3DS, I'm not sure though), which this library can use.

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


# Question
Title: How to achieve light that changes color mid-way?
I thought of creating light sources, and some colored windows. Now, the windows are semi-transparent. How could I make it so that when the light (say, pure white) hits the glass and continues through it, but changes the color to the same color as the glass it passed?

I know the effect described here can be faked by using area lights on the "colored" side of the window, but what if I just wanted to have one white point light?

# Answer
There are a huge number of ways of doing this. These will require the use of a shader and I am presuming that you are already doing per-pixel lighting. The following are some suggestions, however finding the technique that's right for you might take a lot more research.

## Quick and Dirty

You can specify bounding boxes which define interior areas. If the light is outside the boxes, but the geometry (which is not in shadow) is inside the box, then the light must have been affected by passing through a window (this is also true if the geometry is outside the box and the light is inside). The only issue here is how to pass the box information to the shader and how state the effect on the light.

Another option is to specify windows as objects lying on planes. First test to see if the geometry and the light are on opposite sides of the plane and then if the way between them intersects the plane at a point within the boundaries of the window. This would be more accurate than the first method and it would be easier to have windows into the same interiors with different colors of glass.

Keep getting more detailed with the geometric representation of the windows and you will get more accurate results, but the computation will also get heavier.

These techniques would work reasonably well for a corridor shooter, but not so well for a dynamic or open world as a lot of tweaking would probably be required to get it looking right without too many artifacts. Also, these techniques could quickly become a little intense, so moving to a deferred shading pipeline would be advised.

## Shadow Maps

Another option is to do something similar to shadow mapping.

In shadow mapping you generate some bitmap image of the world affected by a light. Each pixel, while still a color, is actually the distance of the nearest piece of non-transparent geometry (you use the four bytes for 1 float instead of 4 colours). If you calculate the distance from the light to a piece of geometry and it's further than the corresponding value in the shadow map then your piece of geometry is in shadow (you generally use the ray between the geometry and the light to index the map).

If you apply this idea to your problem then what you would do is store a map of the distance from the light of the nearest piece of transparent geometry, and then also make a second map of the color of the light after passing through that geometry (simply the color of the geometry if the light is white).

If your piece of geometry is further away than the distance in this map, then use the map color, if it's not then use the original light color.

The function for calculating the color for each pixel in the map should roughly be; lightColor - invertedWindowColor. So for a pure white light and a pure red window which absorbs none of the red spectrum we get; (255,255,255) - (0,255,255) = (255,0,0). So the color of light on the other side is pure red. For a more complex transparent object, such as a stained glass window, you might want to have a texture lookup to get the material color.

If you are looking for something similar then check out Reflective Shadow Maps.

This technique offers a great amount of fidelity and would possibly be the best if you wish to use complex transparent geometry such as stained glass windows.

## Attempting a General Solution

It has recently become popular to encode lighting information in a voxel representation (they're not just for geometry). The latest crytek engine uses this kind of stratagy for advanced lighting (light propagation volumes).

Here is the general idea:

* Create a map of evenly spaced cubes which encompasses your scene (consider using z-order curves).
* Find a way of storing incident lighting information for each voxel (spherical harmonic representations are useful here).
* Find the voxel containing a light and represent that light in the voxel.
    + Propagate the light outwards through the adjacent voxels (kind of like minecraft water)
    + Calculate how the geometry in each voxel will affect the light passing through it (absorb, reflect, transmit)
    + repeat until the light has faded

There are many ways of building this voxel information, but the list above gives a general idea. For example; you can start by generating shadow maps/volumes and then projecting that information into the voxel map so you can quickly make the map of direct lighting. Then you start the propagation from the voxels along the edge of the affected area. Keep in mine that, in this case, you will want to ignore whether geometry is transparent or not when generating the shadow map/volume.

In the final pass of a deferred renderer, when calculating the illumination of a point of geometry you simply use the geometry position to index your voxel map to find out what the incident lighting is like at that point in space. Then you can build a screen map of incident lighting cpu side, or possibly do this with cuda.
> 14 votes

---
Tags: opengl, lighting, color
---


# Question
Title: How (update,set, apply) dynamically color on a model of a XNA project?
I encounter a problem for set a background color on my model instantiated. I can change the texture but not change color. Is there a parameter for change the color ? Or change the opacity ? I am looking for a way to highlight a model.

thank you so much

Here is my code used: Everything works except the two last line. I searched but can not find name parameter for color and opacity

//Does not work

**effect.Parameters\["Color"\].SetValue(new Vector3(0,1,0)); effect.Parameters\["Opacity"\].SetValue(0.5f);**

```
        void DrawModelHardwareInstancing(Model model, Matrix[] modelBones,
                                             Matrix[] instances, Matrix view, Matrix projection)
            {
                 .......

                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (ModelMeshPart meshPart in mesh.MeshParts)
                    {
                        // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer.
                        Game.GraphicsDevice.SetVertexBuffers(
                            new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0),
                            new VertexBufferBinding(instanceVertexBuffer, 0, 1)
                        );

                        Game.GraphicsDevice.Indices = meshPart.IndexBuffer;

                        // Set up the instance rendering effect.
                        Effect effect = meshPart.Effect;
                        //effect.CurrentTechnique = effect.Techniques["HardwareInstancing"];
                        effect.Parameters["World"].SetValue(modelBones[mesh.ParentBone.Index]);

                        //Work perfect
                        effect.Parameters["View"].SetValue(view);
                        effect.Parameters["Projection"].SetValue(projection);
                        effect.Parameters["Texture"].SetValue(textureInstancedModel);
                        /* ***************************** */
                        //Does not work
                        effect.Parameters["Color"].SetValue(new Vector3(0,1,0));
                        effect.Parameters["Opacity"].SetValue(0.5f);
                        /* ***************************** */

                        // Draw all the instance copies in a single call.
                        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                        {
                            pass.Apply();

                            Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                                                   meshPart.NumVertices, meshPart.StartIndex,
                                                                   meshPart.PrimitiveCount, instances.Length);
                        }
                    }
               ........
}

```

# Answer
> 1 votes
Changing color to a texture with an effect file can be done in this way:

# HLSL CODE

And then a simple test game:

```
VertexBuffer bufferVertex;
IndexBuffer bufferIndex;
Effect effect;
Matrix View, Projection;

protected override void LoadContent()
{

    effect = Content.Load<Effect>("Color");
    Projection = Matrix.CreateOrthographic(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, -10000f, 10000f);

    View =
    Matrix.CreateScale(1.0f) *
    Matrix.CreateRotationY(MathHelper.ToRadians(225)) *
    Matrix.CreateRotationX(MathHelper.ToRadians(30)) *
    Matrix.CreateTranslation(0, 0, 0);

    VertexPositionTexture[] vertices = new VertexPositionTexture[4];

    vertices[0] = new VertexPositionTexture(new Vector3(-128, 0, -128), new Vector2(0, 1));
    vertices[1] = new VertexPositionTexture(new Vector3(128, 0, -128), new Vector2(1, 1));
    vertices[2] = new VertexPositionTexture(new Vector3(-128, 0, 128), new Vector2(0, 0));
    vertices[3] = new VertexPositionTexture(new Vector3(128, 0, 128), new Vector2(1, 0));

    bufferVertex = new VertexBuffer(GraphicsDevice, VertexPositionTexture.VertexDeclaration, 4, BufferUsage.WriteOnly);
    bufferVertex.SetData(vertices);

    int[] indexs = new int[6] { 0, 1, 2, 2, 1, 3 };

    bufferIndex = new IndexBuffer(GraphicsDevice, IndexElementSize.ThirtyTwoBits, 6, BufferUsage.WriteOnly);
    bufferIndex.SetData(indexs);
}

```

Drawing

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

    effect.CurrentTechnique = effect.Techniques["Color"];
    effect.Parameters["Projection"].SetValue(Projection);
    effect.Parameters["View"].SetValue(View);
    effect.Parameters["World"].SetValue(Matrix.Identity);

    effect.Parameters["xTexture"].SetValue(Content.Load<Texture2D>("grass"));
    effect.Parameters["xAmbient"].SetValue(new Color(255, 255, 255).ToVector4());
    effect.Parameters["xColor"].SetValue(Color.Black.ToVector4());

    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
        pass.Apply();
    }

    GraphicsDevice.Indices = bufferIndex;
    GraphicsDevice.SetVertexBuffer(bufferVertex);
    GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);

    base.Draw(gameTime);
}

```

Example Default:

```
effect.Parameters["xAmbient"].SetValue(new Color(255, 255, 255).ToVector4());
effect.Parameters["xColor"].SetValue(new Color(0, 0, 0).ToVector4());

```

Example Red:

```
effect.Parameters["xAmbient"].SetValue(new Color(255, 0, 0, 0).ToVector4());
effect.Parameters["xColor"].SetValue(new Color(255, 0, 0, 0).ToVector4());

```

Hope that this can be applied anywhere else.

# Answer
> 2 votes
This is not really dynamically coloring but you can alter the lighting effects to achieve the same thing. The AmbientLightColor effect should work.

```
effect.AmbientLightColor = new Color(r, b, g);

```

Also there is an effect.alpha that you use for transparency iirc which takes a float between 0-1.

---
Tags: xna, c#, color, effect, instancing
---


# Question
Title: Different iPhone screen resolutions and game graphics
We are developing a 2D game for iPhone using cocos2d-x. The artists are drawing the raster graphic for a resoluion of 640x960. For older iPhone devices, those that have a resolution of 320x480, should we provide a completely new set of graphics, to be adapted to the smaller resolution? I was thinking of simply scaling the whole scene of a factor of 2. That would save us the time to write a specific set of graphic elements for the smaller resolution. What is the best practices? How do you guys handle the different screen resolution w.r.t. the graphic part of the game?

# Answer
It really depends on your art style. Does the game look fine scaled down halfway? Would making new, lower-res artwork push you over the current OTA download size? If so, then keep the larger graphics.

There are not a lot of people with 3GSs and 3rd gen iPod touches out there (the only currently supported non-retina small devices), and with iOS 6 the 3rd gen touch isn't going to be supported any more either.
> 4 votes

# Answer
you should use two sets of graphics, this might help you reduce memory usage too as its already built into the framework of cocos2d.

You need to add a suffix on your images, apple uses the ”@2x” suffix, but cocos2d doesn't use that extension because of some incompatibilities. Instead, cocos2d has its own suffix: ”-hd”.

You'll need to enable retina mode though:

```
    // Director Initialization
[director setOpenGLView:glView];

// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director enableRetinaDisplay:YES] )
    CCLOG(@"Retina Display Not supported");

```

You'll also need to create hd fonts.

More info can be found here:

http://www.cocos2d-iphone.org/wiki/doku.php/prog\_guide:how\_to\_develop\_retinadisplay\_games\_in\_cocos2d
> 2 votes

# Answer
Well, it depends on your artists and how they are designing, if you use Adobe Illustrator, which is vector based, that means you can scale to whatever size you need. My process is to draw the image I want out on paper, scan it in, make a version in of the drawing in Adobe Illustrator (using the drawing as a template), then rasterize in Adobe Photoshop and add any final touches.

If there are any designers, who think they can add or help me improve my process, I would really appreciate a comment or a message.
> 2 votes

# Answer
I handle the resolution of images like this

```
float spriteheight = ((size.height/10)/(spritename->getContentSize().height));
float spritewidth = ((size.width/7)/(spritename->getContentSize().width));
spritename->setScaleY(spriteheight);
spritename->setScaleX(spritewidth);

```

the 10 and 7 depends on how big or small your image is, the higher the number makes your image smaller and the lowest makes them bigger.

hope this helps your problem
> -1 votes

---
Tags: iphone, cocos2d-x, multiple-graphics-devices
---


# Question
Title: How can you extract orientation from a transformation matrix?
I have a 4x4 transformation matrix M, and I want to find out the shape of a sphere when transformed by M. (Sphere is at the origin and has radius 1.)

I know I can find the center by just multiplying M by (0,0,0,1).

However, the radius becomes a problem as M can squash and rotate the sphere. How can I find out the new radius(es) of the resulting ellipsoid? Is there any way to find out the orientation?

More specifically, I need to know the size of the bounding sphere which would enclose the transformed sphere. In other words, what is the maximum of |M\*V - M\*(0,0,0,1)|, where V is a unit vector (a point on the original sphere).

# Answer
Mathematically, the quantity you're asking about is called the operator norm. Unfortunately, there's no simple formula for it. If it's a fully general affine transformation - for instance, if it could have an arbitrary combination of rotations and nonuniform scales, in any order - then I'm afraid there's nothing for it but to use singular value decomposition. If you apply SVD to your matrix then the largest singular value will be the maximum radius of the resulting ellipsoid. The other singular values will also be its other two radii, and the SVD procedure can also extract the orientation of the axes for you.

Implementing SVD is not for the faint of heart, as it involves finding eigenvalues. If all you want is the singular values themselves, they are the square roots of the eigenvalues of M^T * M. So if you have a 3x3 eigenvalue solver handy, or you don't mind writing one, you can use that. If you want to extract the orientations of the axes as well, then it gets more involved as you have to find eigenvectors too. On that Wikipedia article there is a list of links to libraries for doing SVD, one of which you may be able to use in your project.

If the form of your matrix is restricted in such a way that nonuniform scale happens at most once and is the first transform applied, i.e. is rightmost when you're using column vectors, then you can simplify this to just look at the lengths of the transformed axis vectors. In that case alone - i.e. a single nonuniform scale followed by any sequence of rotations, reflections, and uniform scales - looking at just the axis vectors will give you the right answer.
> 6 votes

# Answer
Maybe extract scale factors from the matrix and then use max value of its components. Using SRT (Scale-Rotation-Translation) matrix you can do this like that:

```
glm::mat4 m = ...;
// Extract col vectors of the matrix
glm::vec3 col1(m[0][0], m[0][1], m[0][2]);
glm::vec3 col2(m[1][0], m[1][1], m[1][2]);
glm::vec3 col3(m[2][0], m[2][1], m[2][2]);
//Extract the scaling factors
glm::vec3 scaling;
scaling.x = glm::length(col1);
scaling.y = glm::length(col2);
scaling.z = glm::length(col3);

float scaleFactor = MAX(scaling.x, MAX(scaling.y, scaling.z));

```

(based on http://wklej.org/id/950061/ \- the name is decomposeTRS and not decomposeSRT because I use names besed on order which matrices are multiplied in OpenGL).

Now you can multiply original sphere radius by scaleFactor and you have your bounding sphere.
> 2 votes

---
Tags: mathematics, matrix, transformation, linear-algebra
---


# Question
Title: Smart terrain generation to avoid unconnected tiles
To make this clear from the get go;

I'm not looking for HOW To randomly generate a terrain (I know I can use Perlins noise for that).

I'm looking for an algorithm that can help with the terrain generation.

Example;

Me and my friend are working on a flash game to be use as advertisement for an upcoming game (And to see if theres actually interest for the base game).

And I've been working on randomly making terrains, however! When i generate the map, i have no idea how to make it so it connects properly.

The map is isometric and tilebased and after its been generated we're going to litter chest/traps and other gameplay elements on the map. However, theres no reason to put an item on a piece of that map thats not connected to the rest of the map.. Or worse yet, spawn a player on a tile thats unconnected to anything.

Does anyone know of a algorithm that helps with stuff like this?

Thanks in advance people.

~Etarnalazure

*EDIT*

What I'm looking for is an algorithm that makes sure theres no unconnected tiles, thus no items or players may by accident get seperated from the rest of the walk-able tiles.

Hopefully this clears up what i mean.

# Answer
It sounds like you already have most of a terrain generator up and running. If your only concern is not leaving any walkable terrain isolated from other walkable terrain one thing you could do is run a blob finder over the entire map.

With one pass over the map grid you should be able to put together a collection of "blobs" which are separate walkable areas on your map. From there it should be fairly trivial to take each blob and make sure it connects with the rest by making a bridge/connection to one or more adjacent blobs and not stopping until there is only a single blob remaining (you can merge existing blobs without going over the entire map again).

If you need to spawn the player now, all you have to do is make sure that where you spawn them is walkable and you will be able to say for certain that they can get to any walkable square on the map.
> 3 votes

# Answer
Sounds like you're actually looking for a maze-generation algorithm instead of purely random terrain. Since most such algorithms work by "blazing a trail" from a starting point, there will be no islands.
> 2 votes

# Answer
If the core issue is really detecting if a bunch of stuff is connected, the way to address that would be with a pathfinding algorithm like A\*.

I did a quick Google search and came up with this A\* AS3 API.
> -1 votes

---
Tags: algorithm, actionscript-3, isometric
---


title: Terrain detection on racing game

text:
# Question
Title: Terrain detection on racing game
Hi I don't speak English very well so ill try to do my best :P

I'm doing my first top-down racing game for LibGDX, now I need to create tracks, the tracks aren't very large, I prefer doing this with a set of tiles with different types of curves, because I want to do a level editor. So I need to check whether the car is on the track or not. I thought that these alternatives are good but I need help by choosing the best one

* An big array. Doing an array of tiles, saving whether in that position there is a track, looks very memory consupting
* A set of polygons. And then checking if the car is inside them. Looks very CPU consupting
* An Black-White image of the track. I've seen a recomendation here about that, but looks similar to an array

Do you know another way to do this?

# Answer
> 0 votes
I'd have to say the array. Creating a black and white image, then processing it based on color can really limit gameplay. It also creates a lot of lag(assuming you're using java's robot), Polygons may work, but wouldn't that be like a more complicated version of an array? I see no real advantage to polygons. UNLESS... You have really weird and irregularly shaped bounds, such as triangles and hexagons used together.

---
Tags: java, libgdx, racing
---


# Question
Title: How to toggle something using key releases
I'm making an application using lwjgl and I'm having troubles with toggling using the same key. What I want is for the boolean to be toggled when I release the key. I have a method that returns the toggle state and checks for any changes at the same time, but this is proving kind of difficult and overly complex. Is there any way I can make this easier? If not, could someone tell me how to go about toggling with the same key?

Any help is appreciated, thanks in advance!

# Answer
> 1 votes
I figured it out myself, here's the code:

```
public class Input{
    private static boolean escDownOnLast;
    private static boolean escToggled;

    public static boolean isToggledOn(){
        if(Keyboard.isKeyDown(Keyboard.KEY_R)){
            escDownOnLast = true;
        }else if(!Keyboard.isKeyDown(Keyboard.KEY_R) && escDownOnLast && !escToggled){
            escDownOnLast = false;
            escToggled = true;
            return escToggled;
        }else if(!Keyboard.isKeyDown(Keyboard.KEY_R) && escDownOnLast && escToggled){
            escDownOnLast = false;
            escToggled = false;
            return escToggled;
        }
        return escToggled;
    }
}

```

---
Tags: lwjgl
---


# Question
Title: How can I move an object over a drawn tile map in HTML 5 without constant buffering?
I've been messing around with HTML5 for quite some time now but this is something that I guess I haven't figured out how to handle well yet. I'm sure there's an extremely easy solution and I just haven't opened my eyes to it but anyway.

The problem is thus: I have an HTML5 canvas on which I've loaded image tiles using a function (called once on page load) which sets up an image object called `imageObj`, and on `imageObj.onload`, it draws the image that I want it to draw at the specific coordinates.

Now, I generally always run my main canvas game code in a `setTimeout` that runs at 30 frames per second. I have a separate function which checks what keys have been pressed and stores them in an array (to account for multiple key presses), and if arrow keys are pressed, then global variables that store the player's x and y position are incremented/decremented accordingly.

Now, in the `setTimeout` loop, here is where i draw a small rectangle with the x and y coordinates as that of the player x-and-y variables. However here is where I have the problem.

I do not refresh my canvas in the sense, I do not clear the screen or put a new black background covering the screen at the beginning of each frame, because then I would have to reload the tilemap and that's incredibly slow on my localhost, and would be even more so online. Furthermore, since I do not clear the screen, the rectangle of the player is leaving a trail of rectangles behind it (i.e, all previous instances of its position have a rectangle in its place)

**How do I handle this? How do I manage dynamic objects over the tile map and refreshing the canvas without having to constantly reload the tile map?** (or reloading the tile map in some smart way. I believe there are certain methods such as drawing the next frame beforehand or as such; I'm not too sure)

Edit: I'd rather not use any third party apis or libraries or game engines, bit of a purist that way. Also, just occurred to me, what if I had 2 canvases back to back? One with the tile map and the other containing the objects?

# Answer
> 4 votes
You can solve this problem by layering multiple `<canvas>` elements over each other. When you erase on one canvas, the canvas below will not be affected and be visible through the pixel you erased and thus are now transparent.

But... why do you have to reaload your tile image from the hard drive to draw a new screen? Why can't you keep the image in memory? That seems like a design flaw to me.

# Answer
> 0 votes
What you should do is not to refresh the whole canvas and all tiles, because as you reported, it will be slow, but only redraw tiles behind player (which normally is a small area unless player is half screen size).

Every time a actor (eg: player, enemy) is moved on the tilemap, call a function that will invalidate region where the actor was. That region will be repainted later by main drawing function (by calling the tile drawing function for specific tiles). note : if tilemap drawing function is really slow (even for a few tiles) you can also store a copy of full, original tiles rendering in another canvas. to redraw tiles to a specific region on main canvas, use that hidden, duplicate canvas.

For more info about this technique search `canvas dirty rectangle` on google for some code and tutorials.

Note : this technique is not new and have been used by lots of 2D games (eg: DOS) when drawing is slow (eg : no hardware acceleration). it is also how macromedia flash works.

---
Tags: html5, tiles, movement, maps
---


title: D3D/DXGI handle fullscreen transition

text:
# Question
Title: D3D/DXGI handle fullscreen transition
I have a D3D11 application, and I want to add proper fullscreen suport. Now I can let DXGI switch my window to fullscreen for me, and I'm under the impression that DXGI will take care of everything needed to make the swap chain flip front and backbuffer instead of blitting them.

However, letting DXGI perform the swich seems unreliable with a multi monitor setup - secondary screens stay entirely black after the switch a great deal of the time, with no apparent reason or pattern to it.

It can take a few times switching back and forth before I get the fullscreen window *and* the rest of the desktop being shown on the other screens.

Apparently I'm not alone with this, Battlefield 3 and WoW seem to have similar issues for a lot of people.

Now, the actual question: I guess since even those AAA game dev companies can't get this to work, my biggest hope would be to somehow perform the switch to fullscreen myself.

Is there anything I can do to elevate my window/swapchain into proper, buffer-flipping fullscreen mode?

# Answer
> 3 votes
To my knowledge, the onlything that works is:

```
 DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);

```

at the start of your application and:

```
DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);

```

before quitting. For the transitions, proceed as usual. I have tried `InvalidateRect(NULL, NULL, true)` just after switching to fullscreen to no avail. Hope this helps.

# Answer
> 1 votes
You're indeed not the only one facing this issue. First thing to check: make sure you're using the latest/beta/top-notch drivers for the video card you're using.

Now, I'd say that there's only a *small* chance that you can get this working better than the automatic DXGI implementation. This kind of issue is highly dependent on the adapter vendor, driver version, and monitor configuration. So by fixing it on one machine you may end up breaking it on more.

I advise against returning to the dark ages of DirectX 9 where you had to do everything by hand. A better idea would be to try fixing the automatic switching. Some trails to follow:

* Read the (sparse) documentation carefully.
* If you're not doing it already, try to respond to the `WM_SIZE` event that you receive upon switching from/to full-screen, as described here. If you do so, make sure that you are properly releasing all references to the back buffer before calling `ResizeBuffers`, as described there. Failing to do so might cause this kind of weird semi-issues.
* Try to start directly in full-screen, and to create your swap chain with one of the enumerated display modes. If this works all the time, this might mean that you're not using one of the enumerated display mode when handling `WM_SIZE` (or not entirely, things such as the refresh rate can be important).
* Try mucking around with the swap effect and the buffer count of your swap chain description. You should probably be using `DXGI_SWAP_EFFECT_SEQUENTIAL` and a `BufferCount` \>= 2. Maybe your driver has poor support for more "exotic" options.

---
Tags: c++, directx, directx11, windows, winapi
---


# Question
Title: My game works on the emulator and the PSVita, but crashes on Android
I made a game on PSM, ported from a previous iOS/Android game. I test it on the emulator and PSVita and runs fine. However, as I test it on a PlayStation Certified Android device, it crashes on load. I'm getting a `FileLoadException` on the following line:

```
shaderProgram = new ShaderProgram("/Application/shaders/Render.cgx");

```

This is my vertex shader:

```
void main( float4 in spritePosition  : POSITION,
           float2 in textureCoords : TEXCOORD0,
           float4 out gl_Position: POSITION,
           float2 out textureVarying: TEXCOORD0,
           float4 out colorVarying : COLOR0,
           uniform float4x4 projectionMatrix,
           uniform float4 color)
{
    gl_Position = mul(spritePosition, projectionMatrix);
    textureVarying = textureCoords;

    colorVarying = color;
}

```

and my fragment shader:

```
void main( float4 in colorVarying : COLOR0,
           float2 in textureVarying: TEXCOORD0,
           float4 out gl_FragColor: COLOR,
           uniform sampler2D spriteTexture: TEXUNIT0)
{
    float4 colorPremultiplied = float4(colorVarying.xyz * colorVarying.w, colorVarying.w);
    gl_FragColor = tex2D(spriteTexture, textureVarying) * colorPremultiplied;
}

```

What could be causing this problem?

# Answer
> 3 votes
The answer is in the documentation, in "API Overview/Graphics Overview":

> Shader descriptions have the following restrictions in comparison with standard Cg language.
>
> * Variables and functions with the same names as GLSL and Cg reserved words cannot be used.

It turns that the emulator, the PSVita and Android devices all have very different rendering engines, and the shader language used by PSM somewhat allows shader compilation for all targets using a variant of Cg.

* The emulator uses DirectX, which uses HLSL. In this case, variable semantics come from the names after the colons in the function declarations, such as `COLOR0`, and `TEXUNIT0` (which are aptly called *variable semantics*). You can name your variables whatever you like as long as you set the semantics correctly.
* I don't know what the PSVita uses, but it also seems to work with variable semantics.
* However, Android devices use GLES, which uses GLSL. In this case, variable semantics are determined by the variable name, such as `gl_Position` and `gl_FragColor` instead of the declared semantics.

Most likely runtime shader compilation happens in two steps: first the pseudo-Cg code is translated into the target platform's supported shader language; and then the resulting code is compiled by the actual platform.

In Android, I guess the translation for this sample shader goes from this (pseudo-Cg):

```
void main(  float4 in variable1 : POSITION
            float4 out variable2 : POSITION)
{
    variable2 = something;
}

```

to this (GLSL):

```
attribute vec4 variable1;

void main()
{
    vec4 variable2 = something; // Make variable2 a local variable
    gl_Position = variable2; // And assign it to gl_Position at the very end
}

```

Notice that the variable names are kept untouched from the original code. So if my shader uses a reserved variable name like this (pseudo-Cg):

```
void main(  float4 in variable1 : POSITION
            float4 out gl_Position : POSITION)
{
    gl_Position = something;
}

```

The shader code will get translated like this (GLSL):

```
attribute vec4 variable1;

void main()
{
    vec4 gl_Position = something; // <-- ERROR! gl_Position is reserved, you can't define it!
    gl_Position = gl_Position;
}

```

Which will not compile.

So simply changing the offending variable names to some non-reserved name fixes this problem.

Just posting this in case somebody else runs into a similar problem.

---
Tags: android, glsl, cg, psm
---


title: How do I create multiple 2D spotlights?

text:
# Question
Title: How do I create multiple 2D spotlights?
I'm looking to create a 2D "spotlight" effect that allows a spotlight on multiple entities. I.e., as if several sprites were holding torches. For a single entity (one spotlight), I use a technique where I overlay a gradient sprite and have the centerpoint chase that entity. This technique works fine for a single spotlight. Here's a screenshot to illustrate what I'm talking about:

### Single Spotlight - Works

The problem I run into is that this technique does not extend to multiple entities. If I overlay another spotlight image I run into several problems. Here's a simulated screenshot:

### Multiple Spotlights = Problems

The most obvious problem is the visible corners. This could be solved by making the spotlight image gigantic to cover the whole level, but that doesn't feel right. The second and more intractable problem is that I'm effectively multiplying the darkness with this technique. So each sprite added has the effect of darkening everybody else. Clearly I'm approaching this problem incorrectly.

Any ideas?

---

### Continuing Efforts

There's been some discussion of blending options in the comments. Here's my current thinking. In my single spotlight example above, I use an image file that looks something like this: (I've replaced the transparency with the color green to make it easier to illustrate)

As discussed above, the problem is that alpha blending this image with another image is not going to produce the desired effect. Instead it will produce this:

That doesn't strike me as a blending options issue. The problem, it seems to me, is that that sort of image has the transparency mask and image (a black square) built in, when they should be separated.

So instead of a black image with a cut-out transparency built-in, I ought to be using transparency masks that are utilized at run time against the black square. When doing that, I still can't use a traditional white and black transparency mask or it'll run into the same problem. Here's an example, this time the white and black represent white and black:

The solution, it seems, would be to apply a transparency mask that itself utilizes transparency. Something like this: (green = transparent)

That way, multiple transparency masks could be alpha blended together and THEN used as a transparency mask against the black square. Here's an example of two of the transparency masks alpha blended together:

Anyway, that's the approach I'm working on implementing. I'll post results if this works. What I don't know (at present) is if I can use a transparency mask that itself has transparency.

# Answer
Conceptually, the solution to multiple spotlights consists of:

1. Start with a completely black array to hold lighting values for each pixel in the scene.
    * Zero will represent an area of the image with no light whatsoever.
    * 100% will represent an area which is completely saturated with daylight.
    * If you want to get fancy, you could have a value higher than 100% (say, 200%) represent an area of the image which is oversaturated, and blurs everything into a blinding white blob of pixels. Worry about this later, and simply cap values between 0-100% for the time being.
2. For each light source either within the screen, or close enough to the edge that its halo would add to the light, add the light values from that light source to your array of light values for the scene pixels.
3. Use the resulting light-value-array to modify the pixels for your scene such that:
    * Pixels lit by 0% light are black.
    * Pixels lit by 100% light are at their normal colour.
    * Other pixels are a colour part-way between.
    * *You seem to already know how to do this step, judging by your screenshots.*

The trick is understanding that alpha-blending can do one or more of these steps. Alpha-blending just refers to using an alpha map/image to modify the pixels of an image or texture in a simple way. It also usually means that it's going to be a fast set of functions, or implemented with special hardware commands, to make it fast. You can do it with regular arrays, and normal language commands, but using the special alpha/blending library functions is probably better. ...And won't have bugs. Sometimes this means making the pixels partially transparent, but for your case, this will mean:

* Adding alpha values to each pixel, to build up the light-value-array from #1.
* Using the light-value-array from #1 to resolve the final colours for pixels from step #3.

I'd start looking up the documentation for your alpha-blending functions to see what functionality they provide for combining pixels of various kinds. I suspect they will have functions for each of the steps you'll need to perform, but they might be under names which are not obvious.
> 3 votes

---
Tags: 2d, sprites, camera, lighting
---


title: Is basic SDL hardware accelerated?

text:
# Question
Title: Is basic SDL hardware accelerated?
I'm going over some SDL tutorials aimed at creating 2D games.

However, when I create a basic SDL program \- is it hardware accelerated?

Or is hardware acceleration only relevant when it comes to 3D animations? Can a GPU help when it comes to pure 2D graphics?

# Answer
> 7 votes
No. SDL's drawing primitives do not match modern hardware well. I've been told that projects like SDL\_gfx seek to offer an accelerated but simple 2D drawing API, though the docs indicate otherwise (it looks likw SDL extensiona). I believe the prerelease SDL 2.0 code has hardware accelerated 2D.

Building your own over OpenGL or Direct3D is another option, easier than you might think, and is what most native-codec"real" 2D games do these days. If you understand the hadware, making a fast 2D renderer is not terribly hard or time consuming.

SFML HAS A hardware accelerated graphics module, and in my non-objective opinion is a far better, more modern, easier to use API than SDL anyway. It also allows shaders and such in its 2D API, unlike SDL. I'd recommend the prerelease 2.0 version, as I ran into some WONTFIX bugs in SFML 1 a few years ago that are fixed for 2.

Doing 2D well, like doing 3D well, requires understanding how modern hardware works and batching together objects with the same render state and layer. SDL 1.x dates back to the days of old Windows DIB/GDI interfaces and X.org drawing, which no longer work well on modern hardware, as the old 2D rendering parts of graphics chips are long gone. Everything today is triangles and shaders. Even line rendering is typically done by drawing a thin triangle or quad (pair of tris), and blitting or clearing a rectangle is done by drawing a quad (the APIs hide that, but the hardware often has no dedicated line rendering hardware).

APIs like SDL's are faster in software these days. It's still *way* faster to properly use the hardware, but doing so is very different than using SDL 1.x.

---
Tags: c++, graphics, sdl, gpu, hardware-acceleration
---


# Question
Title: Tile Based Engine: Storing Tiles and Levels
I've worked with tile-based engines before (a few years ago when I was pretty green). Now that I know a bit more, I want to revisit tile-based engines but I want to approach it correctly. I want to know two things: what is the best way to store the tiles, and what is the best way to store the levels?

For the first question: The tiles should be stored in sets, like a 10x10 grid of 40x40 tiles stored in a 400x400 image. Right? So when it's displayed, do you just place the entire image on the screen and only show the part of the image you want? And in that case, wouldn't it create a significant amount of overhead for a bunch of unused image? Or do multiple copies of the same image use the same cache?

For the second question: Should the levels be stored as two dimensional arrays? Serialized in a database? Or what?

# Answer
It's really not a huge deal - as long as you do it one way and keep it consistent. There's a lot of ways you COULD do this; but I guess the simplest way is to just keep a few basic data structures and serialize it down. This will be fastest way to get your game going, and if you keep it flexible, you can always add more information and refactor as you go.

Consider:

Create a map class or structure and store some specific details like name, description and the like. Keep a list (depends on your language) of all map layers available to that map. Those layers then can contain a two dimensional array of 'MapTile's. The map tile can store data about a specific map tile. This is a simple and yet very flexible approach.

There's nothing really fancy about it - if you come to an important issue that is more specific, be sure to ask!
> 0 votes

---
Tags: tiles, data
---


# Question
Title: Specular Maps, understanding cryengine hints
i am reading the cryengine documentation, but i don't understand the following hint. Is there any reference to know the logic behind it?

"Create proper specular maps for the objects, and then store in diffuse alpha and enable the material to use gloss in the diffuse alpha. A good specular map can fake a lot of detail. Sometimes, you don't even need a normal map for the object. Do not just increase the contrast/levels on the diffuse map. This is a waste of memory."

# Answer
Often times textures are broken down int many different "maps", which provide different information about the object and how it should look. At the bare minimum, three colors are passed in, and the 4th component alpha may or may not be used. In addition to that, color maps that represent normals to be used when calculating specular highlights and/or bump mapping is often provided in a separate texture. Rather than generate a totally separate map, this hint is simply providing a less detailed, but more efficient way to pass specular highlight information to the shading pipeline.

This hint is indicating that you can save memory by integrating your specular map information into the 4th component of your diffuse color. When your vertex data gets to the pixel shader, without any additional computations performed you will have a 4 component color vector available to you. The 4th component (typically used for alpha) can be used for other information, and in this situation is recommended to be used for specular highlights instead of alpha.
> 1 votes

---
Tags: directx, cryengine
---


# Question
Title: Persistent game where you program your own bot(s)
I'm looking for an online game with a persistent world where you are allowed to code (and add) your own 'players' (it can be in any language / script).

A sort of RTS but for bots.

Does that even exist?

# Answer
Yes, there is. It's called Robocode, and you basically program your own bot in Java, and fight with other people. You can battle against other AI bots, or play multiplayer over the Internet.

Here's the link to their homepage: http://robocode.sourceforge.net/.
> 8 votes

# Answer
Since recently Heroes of Newerth has the ability to program bots: https://plus.google.com/u/0/112989499300264805049/posts/idAYrvc9Awn
> 3 votes

# Answer
There is also the Ai Sandbox, which is by the creators of AiGameDev (http://aigamedev.com/) Here is the link: http://aisandbox.com/

It isn't actually released yet though, but I for one am quite excited about it :)
> 1 votes

# Answer
Carnage Heart on the Playstation 1 was a similar example: http://en.wikipedia.org/wiki/Carnage\_Heart

Not online nor in a persistent world, but it did have an interesting flowchart-based programming model and was quite impressive for it's time.
> 1 votes

---
Tags: multiplayer, mmo, rts, bot
---


title: Is OpenGL 1.1 really slow?

text:
# Question
Title: Is OpenGL 1.1 really slow?
If anyone ever played minecraft and realized no matter what computer you have it normally doesn't give over 100 FPS? While looking at decompiled code from it I noticed it renders with OpenGL 1.1 calls. I knew people said it was slow but do you think that is the problem? I'm not asking anything about minecraft I'm asking if OpenGL 1.1 is capable of this horribly low FPS.

# Answer
> 5 votes
There are many reasons why a game may be limited to a specific framerate, and only one of them is relative performance of the API version. Let's look at two of the most simple examples.

vsync can limit framerate to the refresh rate of your monitor. If you have a 100hz monitor and if vsync is enabled, you'll never run faster than 100fps.

The game may have an artificial FPS cap to prevent it from running too fast; i.e. it may not run the next frame until 10 or more milliseconds have passed since the previous one.

To test the performance of OpenGL 1.1 you can dig out a copy of the original Quake and benchmark it - that used GL 1.1 (actually 1.0 with the texture objects extension) and it's capable of running much faster than 100fps in it's benchmark mode. Also note that it's artificially limited to 72fps when running normally.

Having said all that, it is true that GL 1.1 is not the fastest path available, it can begin to bog down a little as more passes and higher polygon counts ramp up, and higher GL\_VERSIONs can offer faster, cleaner ways of doing things that must otherwise be handled with a complex and heavy setup, or brute-forced on the CPU, in GL 1.1; but "not the fastest" is not the same thing as "horribly slow" - there are a whole world of intermediate stages between the two.

---
Tags: opengl, lwjgl, minecraft-modding
---


title: C++ Using clock() with IsKeyDown

text:
# Question
Title: C++ Using clock() with IsKeyDown
I am trying to replicate the game *Asteroids* as a class project. I am having trouble measuring the time elapsed while the "W" key is pressed.

This code is supposed to increase the force applied to the spaceship to increase the movement speed incrementally. This is supposed to let the space ship rotate while moving along a 'line' and then force while be slowly applied to the new direction the ship is angled.

I have tried to research this over many hours and I still don't understand the concept. It seems there are a few ways to go about this but neither attempts have been successful.This is for school submission for the first project of the first year, so obviously my code is very basic and not making use optimal use of classes/structs however I would still like to achieve this movement I have been seeking so that I can understand the concept for use in future projects.

I have tried the use of current/previous variables for speed but haven't been able to come up with an equation to accomodate that. I have also attempted the use of a timestep but have been told that is not the correct approach. Any help would be appreciated. You can view the bulk of my program at https://gist.github.com/Rifuli/4762704

# Answer
> 1 votes
All that is doing is measuring the time taken for the processor to move from the first statement in your code to the third instruction. It isn't measuring the amount of time the key is pressed at all.

To measure the time that the key is pressed, you need to measure the time when the key is first pressed (and only when first pressed, not each time through the loop if the key is down), and subtract that from the current time.

However, there's no need for you to do this to implement asteroids. To accelerate while the key is held down you only need to apply a constant force on each iteration, ie. `fPlayerSpeed += fPlayerAccel`. This will make the speed increase over time, as expected.

The one complication is that if `fPlayerAccel` is measured in units per second, then you need to scale that accordingly, not by how long the key has been pressed, but by how long has elapsed since the last frame of logic. To do this you need to call `clock()` each frame, and compare the result each time to the result you got in the previous frame, and work out what fraction of a second has elapsed. Then you can multiply `fPlayerAccel` by that value before adding it to the speed.

There are other ways to approach game loops that some recommend, and which can make the game a bit more complex to write in general but which make the physics simpler and more consistent. It's worth reading about them and trying to understand what the pros and cons of each method are.

---
Tags: c++, physics, movement, timer
---


# Question
Title: The saturate function is not working in my pixel shader
I wrote a pixel shader for my game and when I tried to compile it an error occurred:

```
ID3DXEffectCompiler::CompileEffect: There was an error compiling expression

```

When I removed all the saturate functions from the shader it compiled without problems. Strangely the saturate function works for all techniques in this effect file but one.

This code worked for me:

```
float4 PixelShader(VertexToPixel PSIn) : COLOR0
{
    return xAmbientColor * xAmbientIntensity;
}

```

And this didn't work:

```
float4 PixelShader(VertexToPixel PSIn) : COLOR0
{
    return saturate(xAmbientColor * xAmbientIntensity);
}

```

-EDIT-

When I added some diffuse lighting the saturate function worked perfectly for the diffuse lighting calculation while it still didn't work for ambient lighting. This is really strange and I hope you can help me with this problem.

# Answer
I solved my problem:

```
float4 PixelShader(VertexToPixel PSIN) : COLOR
{
  //calculation of ambientColor and diffuseColor without using saturate
  return saturate(diffuseColor + ambientColor);
}

```

I don't know why, but this worked in my case. I hope I helped someone who is having the same problem. I think XNA can't handle saturate for calculations using only effect parameters.
> 0 votes

# Answer
The result must be store in a separate variable before return like

float4 c = saturate(xAmbientColor * xAmbientIntensity);

return c;
> 0 votes

---
Tags: xna, hlsl, fragment-shader
---


title: Saving roguelike game state?

text:
# Question
Title: Saving roguelike game state?
I'm working on a basic roguelike using HTML5 and jQuery, and I've come across a problem.

The way the game currently stands, the system only saves the game state every time the user moves between floors - to minimize overhead. The peril of this is that, if the user gets in trouble, they can simply close the window and return to their game at the beginning of the current floor. This drastically reduces the difficulty of the game (and almost defeats the purpose of a roguelike) - but it's unreasonable to save the game state with every single player movement or attack.

I've researched ways to save the game state on browser window close, but I'm not happy with them. My question is this: assuming "saving a game state" means a moderately heavy ajax/post request, how do I thwart this cheating behavior? Is there a known methodology to quantify incremental/procedural changes to a 2d map, as opposed to saving the entire map state? Please note, I'm not asking for "the most efficient way" - I'm looking for existing methodologies to rectify my inexperience.

# Answer
> 8 votes
The obvious solution is to send every player command to the server as it's made and have the server log them; that way, if the game is aborted for any reason, the logged commands can be replayed to restore the game to the point where it left off.

Of course, when a proper save is made, the old command log can be thrown away (although you could also save it to allow replays of old games; if you do that, you may want to include timestamps in the log for real time replay). You may also want to automatically make a full save after *n* commands have been made since the last save (where, say, *n* = 1000) to avoid excessively long replays if the player stays on the same level too long before closing or crashing the game.

If your game involves random numbers (and, being a roguelike, it probably does), you'll also need to make sure that they can be recreated correctly during a replay. One solution is to include every random number in the replay log; another is to use a deterministic pseudorandom number generator and save the seed when the game is saved.

Note that all of these methods can be exploited by tampering with the client, but that's really inevitable whenever you have game logic on the client. As a cheat-proof alternative, you could run the actual game on the server and just have the client send all player commands to the server and receive display updates back. For a roguelike, this may well be feasible. Obviously, this would also solve your state saving problem (although you might still want to implement some form of command logging on the server, both for replay functionality and to allow recovery from server crashes). The downside is that doing this would make off-line play impossible (unless, of course, you also make the server-side code available for players to run locally if they want).

# Answer
> 2 votes
See https://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser for a more generic asking of the same question.

Also consider saving full game on floor changes, and incremental deltas on each move. Then you can replay the game up to the point of last move.

Assuming there is some use of random number generators, you can generate and re-seed the random number generator at the start of each new floor, and then save it along with the floor. Then you can reseed on load, and should be able to replay the moves with the same sequence up to the last one done.

# Answer
> 2 votes
Approaches to, not incremental saves, but finding time for a full save:

* `onunload`, as previously mentioned. I have found this to be reliable (but using `localStorage`, not network, which may change things).
* Save when your window loses focus.
* Save periodically: when the last save has not been in *n* minutes and the user has not made any input in *m* seconds.

---
Tags: javascript, savegame, roguelikes
---


# Question
Title: UV mapping doesn't work without duplicating vertices, but duplicating will reduce performance, right? Is there another solution?
**Situation:** I've been trying to gradually get a lower and lower level of understanding of how games work, and lately I've been following Rastertek's DirectX 11 tutorials. Of course, I started branching off on my own and experimenting, like a good little programmer.

I noticed that the tutorial had a set of 3 vertices for each triangle, even if that meant duplicating vertices that were there anyway. So a cube would have 12 triangles * 3 vertices/triangle = 36 vertices, when it only needed 8. This seems like it could reduce performance by quite a bit in more complicated models.

However, when I tried setting the indices to reuse vertices, I ran into problems because the normal and UV coords are assigned to each vertex. I averaged the normal vectors, which resulted in smoothing the lighting where it probably shouldn't have been smooth, and UV coords...well...right now they overwrite each other as they're importing, which results in crazy things, like so: https://i.stack.imgur.com/Rr6aB.jpg

**My thoughts:** Right now, I see one reasonable solution. When UV mapping in Blender, I had to create "seams", which the model was unwrapped around and blah blah, I'm sure you know what that is. Anyway, I could duplicate the vertices on these seams only, which would solve both performance and texturing quite nicely.

This wouldn't require much change in the code I currently have, but Blender's exporting algorithms don't seem to cooperate with this approach. At least not with the .obj format. Getting this approach to work correctly looks entirely possible, but also annoyingly difficult.

**Finally, the question:** So now I'm here, typing to you people. Am I on the right track? Or is there an entirely different approach I haven't thought of yet? What is the normal way of doing this?

Of course the other question is, will duplicating vertices like that really have a significant impact on performance? My very premise could be mistaken.

# Answer
> 5 votes
Performance shouldn't be affected at all, it'll just take up a small amount of extra memory. The hardware draws triangles independently, the only difference between the two is that the one without duplicates will just be reading multiple times from the same memory address while the one with duplicates will read from separate memory addresses.

While it may seem like a waste, it's necessary because those vertices are unique. There's more in a vertex than just the position. Two vertices with the same position but different texture coordinates/normals are not the same vertex.

---
Tags: c++, graphics
---