# Question
Title: Would I perform one pass per effect in Deferred Shading?
I'm implementing deferred shading the first time. Doing so I came up with a conceptual question.

First I render the geometry in a framebuffer with muptiple rendering targets for depth, normals, and so on. Say that I want to apply several post effects, I think I have two options now. I could either render a quad with the depth, normals, ... texture to the screen buffer once applying all effects in that pass. Or I could perform one render pass to another framebuffer for each effect and lastly combine those effect in a pass to the screen buffer.

Would both ideas work and if so what is the common approach?

# Answer
> 2 votes
You need at least two passes for deferred shading, the first to fill the G-Buffer and the second for the lights. After that you need at least another pass for effects, you would probably render the light result to another framebuffer and then render the effects on this framebuffer. You can use this third pass for all the effects, if you write a single shader to apply those effects (though you lose some flexibility, and some effects may require all the previous effects to be fully applied before they can be used.) I suppose you can do it on the second pass, along with the lights, but I'm not sure how the blending of the effects would work.

I believe you need at least 3 passes for the effects, but I would leave the option for more passes for different effects, maybe you can group your effects into shaders that make sense together, that would save you a few passes but still be flexible and readable.

---
Tags: opengl, glsl, pipeline, post-processing, deferred-shading
---


# Question
Title: Android OpenGL ES RENDERMODE_WHEN_DIRTY implementation
I am trying to understand `RENDERMODE_WHEN_DIRTY` so that I could save battery life wherever possible.. I made this sample application so that GlSurfaceView is updated with random color only when the random number `temp` is greater than 50... If the value of `temp` is less than 50, I want it to retain the last random color.. But in this code sample, it is not retaining it but making the screen go black forever!

Basically I want to know if my implementation of `RENDERMODE_WHEN_DIRTY` correct...

```
package com.blob.blob;

import java.util.Random;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.util.Log;

public class OpenGLActivity extends Activity implements Renderer
{
    GLSurfaceView glView;
    Random rand ;
    @Override
    public void onCreate(Bundle s)
    {
        super.onCreate(s);
        glView = new GLSurfaceView(this);
        glView.setRenderer(this);
        glView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        rand = new Random();
        setContentView(glView);

    }

    public void onDrawFrame(GL10 gl)
    {
        int temp = rand.nextInt(100);

        if(temp > 50)
        {
        glView.requestRender();

        gl.glClearColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat(), 1);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        }

    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {

        Log.d("OpenglTest", "Surface Changed");
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        Log.d("OpenglTest", "Surface Created");
    }

    public void onPause()
    {

        super.onPause();
        glView.onPause();

    }

    public void onResume()
    {
        super.onResume();
        glView.onResume();
    }
}

```

# Answer
> 6 votes
`RENDERMODE_WHEN_DIRTY` means "do not call `onDrawFrame()` unless something explicitly requests rendering with `requestRender()`". Your code snippet is calling `requestRender()` from within `onDrawFrame()`, so nothing will ever happen.

The idea behind `requestRender()` is that nothing is drawn until some other thread has decided that rendering needs to happen. The SurfaceView docs note that it "may be called from any thread", which is necessary for this method to have any value, because the renderer thread is just sitting there waiting for somebody to wake it up.

---
Tags: android, opengl-es
---


# Question
Title: OpenGL 2.0 Android Scrolling Horizontally and Vertically
I am new to OpenGL2.0 in Android. How can I scroll the `GLSurfaceView` both horizontally and vertically?

# Answer
Turns Out that the vertex shader in the Android OpenGL example is wrong. Its correct in the docs but if you download the example it has wrong shader code. As suggested by tim in the following link:

Android OpenGL weirdness with the setLookAtM method
> 0 votes

# Answer
In the Android Developers Training site, you already have a way to do this:

http://developer.android.com/training/graphics/opengl/projection.html

You just need to modify this line:

```
// Set the camera position (View matrix)
Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

```

to add the ScrollX and ScrollY respectively.
> 1 votes

---
Tags: android, opengl-es2, side-scroller
---


# Question
Title: cocos2d-x v2.1 CCSpeed, CCRepeatForever, and CCAnimation jerky at high speed
I worked to port Tim Roadley's cocos2d-iphone example from (Box2D Driven Cocos2D Animation) to cocos2d-x to learn cocos2d-x for a project. It is all relatively simple to do, but I am suffering from one obstinate problem. When the ball speeds up, the animation gets very jerky. This problem does not exist in Tim's cocos2d example.

From my investigation and close watching of the animation, it skips frames at the end of the animation sequence when the speed is high (above 4 or 5 in my code).

Here is Tim's original code and some context:

```
// LOAD ANIMATION FRAMES FROM SPRITESHEET
NSMutableArray *rollFrames = [NSMutableArray array];
for(int i = 1; i <= 120; ++i) {
    [rollFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"Ball%i.png", i]]];
}

// CREATE ANIMATION ACTION
speedAction = [CCSpeed actionWithAction:
              [CCRepeatForever actionWithAction:
              [CCAnimate actionWithAnimation:
              [CCAnimation animationWithFrames:rollFrames delay:0.1]]] speed:3.5];

// CREATE BALL SPRITE
ball = [TRBox2D spriteWithSpriteFrameName:@"Ball1.png"];
[ball setPosition:ccp((screenSize.width/2), (screenSize.height/2))];
original = ball.position;  // used to determine ball trajectory
[ball runAction:speedAction];
[ball setTag:isTheBall];  // used so we can pick out this sprite during the physics loop
[ball setScale:0.7];

```

Here is my translation, again with some context:

```
// LOAD ANIMATION FRAMES FROM SPRITESHEET
CCArray *spriteFrames = CCArray::create();
for (int i = 1; i <= 120; i++) {
    std::stringstream spriteName;
    spriteName << "Ball" << i << ".png";

    CCSpriteFrame *spriteFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(spriteName.str().c_str());
    spriteFrames->addObject(spriteFrame);
}

CCAnimation *animation = CCAnimation::createWithSpriteFrames(spriteFrames, 0.1);
CCAnimate *animate = CCAnimate::create(animation);
CCRepeatForever *repeat = CCRepeatForever::create(animate);
speedAction = CCSpeed::create(repeat, 3.5f);

spriteFrames->release();

// CREATE BALL SPRITE
ball = (PhysicsSprite *)PhysicsSprite::createWithSpriteFrameName("Ball1.png");
CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
ball->setPosition(ccp((screenSize.width/2), (screenSize.height/2)));
original = ball->getPosition();

ball->runAction(speedAction);

ball->setTag(1);
ball->setScale(0.7f);

```

Tim's example uses COCOS2D\_VERSION==0x00010001 (v1.0.1) I am using COCOS2D\_VERSION==0x00020100 (v2.1.0)

I dug through the CCSpeed, CCRepeatForever, and CCAnimate. The major difference I find is in CCActionInterval.cpp where CCAnimate was changed to use "new animation format that supports delays per frame" (commit d0ab4515a4736bdf31aaed6394d95f8ea02beea1). If I revert this change to the previous "animation format" which does not support delays per frame, the sprite animates flawlessly at higher speeds.

Now to my question, am I mis-interpreting how the animation actions are intended to work in cocos2d-x 2.1? Have I missed something that is causing my jerky animation? It does not seem like changing some of the core code is the right answer, though bugs do exist.

# Answer
Here is the subclass that I used to avoid the issue of jerky-ness with a CCSpeed, CCRepeatForever, and CCAnimate as described above.

```
// SHAnimate.h
#include "cocos2d.h"
#include "cocos-ext.h"

USING_NS_CC;

class CC_DLL SHAnimate : public CCAnimate {
public:

    virtual void update(float t);

    static SHAnimate* create(CCAnimation *pAnimation);
};

// SHAnimate.cpp
#include "SHAnimate.h"

SHAnimate* SHAnimate::create(CCAnimation *pAnimation){
    SHAnimate *pAnimate = new SHAnimate();
    pAnimate->initWithAnimation(pAnimation);
    pAnimate->autorelease();

    return pAnimate;
}

void SHAnimate::update(float t) {
    CCArray *frames = this->getAnimation()->getFrames();
    int numberOfFrames = frames->count();
    int idx = t * numberOfFrames;

    if (idx >= numberOfFrames) {
        idx = numberOfFrames - 1;
    }

    CCAnimationFrame *frame = static_cast<CCAnimationFrame *>(frames->objectAtIndex(idx));
    CCSprite *sprite = static_cast<CCSprite *>(getTarget());
    if (!sprite->isFrameDisplayed(frame->getSpriteFrame())) {
        sprite->setDisplayFrame(frame->getSpriteFrame());
    }
}

```

This class is used in place of CCAnimate as follows:

```
CCAnimation *animation = CCAnimation::createWithSpriteFrames(spriteFrames, 0.1);
CCAnimate *animate = CCAnimate::create(animation);
CCRepeatForever *repeat = CCRepeatForever::create(animate);
speedAction = CCSpeed::create(repeat, 3.5f);

```

replaced with

```
CCAnimation *animation = CCAnimation::createWithSpriteFrames(spriteFrames, 0.1);
SHAnimate *animate = SHAnimate::create(animation);
CCRepeatForever *repeat = CCRepeatForever::create(animate);
speedAction = CCSpeed::create(repeat, 3.5f);

```
> 1 votes

---
Tags: cocos2d-x
---


# Question
Title: Should be GameKit used together with GameCenter?
As far as I understand, GameKit provides Bluetooth-maches, while GameCenter allows to play matches through internet. So it looks like the best scenario is to use both of them? Is this reasonable?

# Answer
I know this answer is a little late, but...

Game Kit is the name of the framework that you use to add support for Game Center in your game. Game Kit is the developers interface to Game Center.

You can read more about this here: http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/GameKit\_Guide/Introduction/Introduction.html
> 1 votes

---
Tags: ios, game-center
---


# Question
Title: Formula for three competing heroes, each has one they can beat and one they're beaten by
I am trying to design a game for a project I have, The main idea is:

3 Types of heroes
3 Stats per hero

There are no levels involved so the differences must be located on stats.

Fight logic - The logic of fight is that type1hero has good chances winning type2hero, type2hero has good chances type3hero and type3hero has good chances winning type1hero.

For over a week I am trying to find a stats based formula that will allow me to fix this but I can't, I was meddling with numbers yesterday and it was decent but I can't extract the formula out of it.

Could you please guide me or give me hints on how should I start creating formulas on a Non lvl game that fulfills the fight logic?

# Answer
Your game is a nontransitive game. You can implement it with 3 stats **R**, **P** and **S**, using the rock-paper-scissors logic. Call these stats whatever you want, but I'll stick with the RPS logic.

Now suppose you have two heroes, with stats R1/P1/S1 and R2/P2/S2. We need to compute how much damage they will do to each other.

You want rocks to deal damage to scissors. That means hero 1 deals « rock » damage to hero 2 if `R1 > 0` and if `S2 > 0`. One formula that works is simply `min(R1, S2)`.

Which immediately gives us the damage formulas:

```
Damage(hero1 on hero2) = min(R1, S2) + min(S1, P2) + min(P1, R2)
Damage(hero2 on hero1) = min(R2, S1) + min(S2, P1) + min(P2, R1)

```

Let's see what happens with a real example:

```
    Hero1  Hero2
R    120     50
S     30    130
P     15     30

```

Given the stats, hero 1 is clearly a « rock » type and hero 2 is clearly a « scissor » type. Here are the results:

```
Damage(hero1 on hero2) = min(120, 130) + min(30, 30) + min(15, 50)
                       = 120 + 30 + 15
                       = 165
Damage(hero2 on hero1) = min(50, 30) + min(130, 15) + min(30, 120)
                       = 30 + 15 + 30
                       = 75

```

Final results: `165` versus `75`. Hero 1 wins, as expected.

There are many shortcomings with these formulas, but I hope they give you an idea of how to implement intransitive combat rules.
> 38 votes

# Answer
Each hero trains up in Melee Combat (M), Dodge (D), and Wizardry (W).

Dodging evades melee combat very well, and magical attacks less well.

Each round, a hero deals damage equal to (M-D) + (W - 0.5D) (M and W are from the attacker's stats, D is from the defender's stats.)

So a Warrior might have the stats:

M: 100, D: 20, W: 0

A Rogue could have the stats:

M: 30, D: 80, W: 30

And a Wizard might have stats like:

M: 10, D: 10, W: 80

Warrior vs. Rogue, the warrior deals 20 DPS, while the rogue deals 30 DPS. Advantage Rogue! Rogue vs. Wizard, the rogue deals 20 DPS, while the wizard deals 40 DPS. Advantage Wizard! Wizard vs. Warrior, the wizard deals 70 DPS, while the warrior deals 90 DPS. Advantage Warrior!
> 1 votes

---
Tags: game-mechanics, mathematics
---


title: Saving Scores Using Cookies

text:
# Question
Title: Saving Scores Using Cookies
I've recently created a small galiga like game recently using JavaScript and HTML5. I've run into a bit of trouble saving cookies, the cookie saves, but then resets itself when the page is refreshed, my code:

```
function saveScore() {
 var date = new Date();
  date.setMonth(date.getMonth()+5);
  var expires = "; expires=" + date.toGMTString();
  document.cookie = "score=" + lvl + expires + "; path=/";
}

function loadScore() {

  var cookiearray = document.cookie.split(';');
  for (var i = 0; i < cookiearray.length; i++) {
    var name = cookiearray[i].split('=')[0];
    var value = cookiearray[i].split('=')[1];
    if (name == "score") {
      alert("Prior score found. Loading score...");
      lvl = value;
    }
  }
}

```

**EDIT:** It appears as though I made an error outside of the given code, and reset the level to zero, I fixed this, and everything works well, I apologize for any confusion caused.

# Answer
> 3 votes
```
ddocument.cookie = "score=" + lvl + expires + "; path=/";

```

One d too much in document. Is that typo also in your real code?

When I might suggest an alternative solution: Why don't you use HTML5 localStorage? As long as you don't have any server-sided programming which needs persistent data, it's a much superior solution.

When you already require that the users browser supports canvas you don't have to worry about browser support for localStorage. Almost every browser which supports canvas also supports localstorage.

---
Tags: javascript, html5, data, savegame
---


# Question
Title: How do I achieve one touch one shot for WP7 game?
I want to be able to have a sprite shoot in a game for WP7. What I have at the moment is that as long as the shoot button is held down the sprite constantly shoots. How do I sort it that only one bullet is shot from touching the button and not a stream of bullets is released? I want for the player to be able to shoot another bullet, they must tap the button again. This was taken from a DreamInCode tutorial on how to make an asteroids clone for PC.

```
foreach (TouchLocation location in TouchPanel.GetState())
        {

            if (shootKeyBounds.Contains((int)location.Position.X,
                                         (int)location.Position.Y))
            {
                FireBullet();

            }

        }

```

The fire bullet method

```
private void FireBullet()
    {
        Sprite newBullet = new Sprite(bullet.Texture);

        Vector2 velocity = new Vector2(
            (float)Math.Cos(ship.Rotation - (float)MathHelper.PiOver2),
            (float)Math.Sin(ship.Rotation - (float)MathHelper.PiOver2));

        velocity.Normalize();
        velocity *= 6.0f;

        newBullet.Velocity = velocity;

        newBullet.Position = ship.Position + newBullet.Velocity;
        newBullet.Create();

        bullets.Add(newBullet);
    }

```

# Answer
> 2 votes
You can check if the touch is a new press by using TouchLocation.State -property. Example:

```
foreach(TouchLocation location in TouchPanel.GetState())
{
    // Check if touch is a new press and if touch is inside shootKeyBounds
    if(location.State == TouchLocationState.Pressed &&
         shootKeyBounds.Contains((int)location.Position.X, (int)location.Position.Y)))
    {
        this.FireBullet();
    }
}

```

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.touch.touchlocationstate.aspx

# Answer
> 1 votes
Once you have handled a touch by firing a bullet you need to record that you have already reacted to that touch and that you shouldn't on subsequent updates.

Each touch location has a unique Id field that is maintained for as long as the touch remains active, even across frames. A simple approach would be to maintain a list of all the touch Ids you have already handled, and ignore those touches when performing your update.

```
// member variable to track handled touches
private List<int> handledTouches = new List<int>();

// modify your update to ignore touches already handled
foreach (TouchLocation location in TouchPanel.GetState())
{
  if(!handledTouches.Contains(location.Id) && shootKeyBounds.Contains((int)location.Position.X, (int)location.Position.Y)
  {
    FireBullet();
    handledTouches.Add(location.Id);
  }
}

```

Obviously you can improve the performance of this example and could remove touch Ids from the list of those tracked when the TouchLocation state is released, but the basic idea of tracking which touches you have handled and ignoring them on subsequent updates is the same.

You could also limit firing a bullet to the initial touch location by simply checking that the touch state is TouchLocationState.Pressed, which should only be true for the first frame in which the touch is active. I haven't used that method myself.

---
Tags: c#, xna-4.0, windows-phone-7, touch
---


# Question
Title: Initializing a blank texture in OpenGL without artifacts
I'm generating a texture atlas in OpenGL, where I want to create a blank texture and copy my sprites to it.

The texture is generated like this:

```
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
  GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
  GL_CLAMP_TO_EDGE);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
  GL_UNSIGNED_BYTE, NULL);

```

While the sprites are copied like this:

```
GLenum format;
if (sprite.hasAlpha)
{
    format = GL_RGBA;
}
else
{
    format = GL_RGB;
}

glTexSubImage2D(
    GL_TEXTURE_2D, 0,
    sprite.x, sprite.y,
    sprite.width, sprite.height,
    format, GL_UNSIGNED_BYTE,
    sprite.data);

```

The issue is I keep getting artifacts in the texture not covered by a sprite:

Here I'm supposed to only have two slugs, one sword in the stone, one light grey tile, and one dark grey tile.

I tried creating a `width * height * sizeof(GLuint)` GLuint array filled with zeros and passing it to the `glTexImage2D` call, but that didn't seem to do anything.

# Answer
Going on Jimmy's comment, I realized my first attempt at passing a blank data array to `glTexImage2D` didn't work because I used `width * height * sizeof(GLuint)` as the size when I should have been using `width * height * 4`, where 4 represents the four values in an RGBA colour.
> 1 votes

---
Tags: opengl, textures
---


title: Drawing isometric walls

text:
# Question
Title: Drawing isometric walls
I'm having some trouble with isometric walls.

I'm drawing isometric floor tiles using the back to front rendering method, and it works fine. I also keep my floor tiles lined up properly in a nice grid. The code (and this seems to be pretty much standard for isometric floor drawing) is as follows:

```
for(int x = 0; x < 6; x++){
    for(int y  = 3; y >=0 ; y--){

        int xCo = (y+x)*(tileWidth/2);
        int yCo = (x-y)*(tileHeight/2);
        tile.draw(g, xCo, yCo);
    }
}

```

This makes a nice little floor grid. See here.

Unfortunately, when I use the same logic for walls, it all goes right to hell.

```
for(int x = 0; x < 6; x++){
    for(int y  = 3; y >= 0 ; y--){

        int xCo = (y+x)*(wallWidth()/2);
        int yCo = (x-y)*(wallHeight()/2);
        walls.draw(g, xCo, yCo);
    }
}

```

I'm using a placeholder as my wall tile (it's a placeholder from google image search, but it should work all the same), and this is the result I get.

The rendering order for my walls is clearly correct, nearer walls render on top of farther away walls, which is what I want, but the positioning is also painfully incorrect, and I don't know exactly how I ought to correct that short of using pixel values.

For reference, I did do a trial using hardcoded pixel vals, because I found that from one wall's right corner to the next wall's right corner, the change was exactly (200, -100) pixels. When I made my rendering loop account for that

```
int xCo = (x+y)*200;
int yCo = (y-x)*-100;

```

it worked fine, but that is not a viable solution because it doesn't allow for any versatility.

So, looking for suggestions on how to make my isometric walls line up. What am I doing wrong?

Thanks!

# Answer
> 6 votes
You can't simply use the same drawing code for walls as for floors because walls and floors are not in the same plane: floors are flat (horizontal) while walls are vertical. So you have to draw them slightly differently.

Your x and y coordinates in the floor case mean something like "left/right" and "forward/backward" in terms of the placement of the tiles. For bricks, left and right still make sense, but we want to replace forward/backward with up and down to reflect the vertical direction. So our "y" gets a new meaning.

Now, in Maths, the y axis usually points upwards while in 2D computer graphics it points down. You can take your pick - the code below assumes that it points upwards so that `y = 0` means "at the floor level".

So let's start thinking about order. The example brick you posted is for a wall that would be a the (upper) left end of a floor. Because of the black parts of the brick (the depth of the wall), we have to make sure that we draw the bricks that are further right first so that the black depth on the left side will be covered by bricks that are closer. The same argument applies for the black on the top part of the wall, we have to draw the lower bricks first.

If we stick with the x- and y-directions as discussed before (x goes from left to right, y goes from bottom to top), this means that we have to run both our for-loops in negative directions:

```
    for (int y = 3; y >= 0; y--) {
        for (int x = 5; x >= 0; x--) {
            ...
        }
    }

```

The main question is now how much we have to offset the drawing of each brick with respect to the other bricks. Let's do that one direction at a time, starting with the x direction.

Let's imagine just two bricks next to each other:

The left of the two has the black depth part visible but the right one shouldn't show it. Thus we cannot simply offset the right image by the full width of the PNG. In fact, assuming that the bricks line up with your floor tiles, the width of the actual front part of the wall should be the same as half the width of a tile.

```
int xCo = x * tileWidth / 2;

```

The black wall depth on the left should not be ignored, because we probably want to offset each brick a little bit to the left so that the x-coordinate of the front corner of the wall lines up with the floor tiles, not the x-coordinate of the back corner.

Now, the y-coordinate of each brick is a bit trickier because it does not only depend on the brick row, it also depends on the x-coordinate: the further right the higher up we should draw. But let's ignore the x-direction for a moment and try to simply draw a column of bricks:

Again, the delta between the y-coordinates of the two bricks is not the full height of the PNG. Unlike in the left/right case where we assumed that bricks line up with tiles which allowed us to use `tileWidth` as the delta-x, bricks can have arbitrary heights. But we can still compute the actual brick height from the image height because we know that the depth on the left side and the depth on the top have to line up.

If we look at the little transparent triangle in the upper right corner of the brick PNG, we notice that the ratio of its width and height must be the same as the ratio of a floor tile's width and height. That allows us to compute an yoffset from the xoffset computed above, and to use that to infer the actual height of the brick:

```
int yoffset = xoffset * tileHeight / tileWidth;
int wallHeight = wallHeight() - tileHeight / 2 - yoffset;

```

Note that this only works under the assumption that there's no empty space at the border of the PNG and it might still fail due to rounding errors. So you might add a `Math.ceil()` (or simply `+ 1`) here if necessary.

So for simple columns, we're good to go now: we can simply multiply our `y` variable with the above `wallHeight`. But as noted before, the x-position of a brick also influences the y pixel coordinate. If we look at the first picture again with the two bricks next to each other, how much did we have to move the right brick up to line up with the left brick? Well, this one is actually easy, because it's the same as with floor tiles: half the height of a tile!

So we're all set. If we put everything together, we end up with a bit of code like this:

```
int xoffset = wallWidth() - tileWidth / 2;
int yoffset = xoffset * tileHeight / tileWidth;
int wallHeight = wallHeight() - tileHeight / 2 - yoffset;

for (int y = 3; y >= 0; y--) {
    for (int x = 5; x >= 0; x--) {

        int xCo = x * tileWidth / 2;
        int yCo = y * wallHeight - x * tileHeight / 2;

        walls.draw(g, xCo - xoffset, yCo - yoffset);
    }
}

```

(I'm assuming that wallWidth() and wallHeight() return the width and height of the brick PNG.)

Note that the three constants at before the for loops can be moved out of the actual drawing code - they only depend on image properties and other constants and don't have to be re-computed every time we draw the wall.

---
Tags: java, mathematics, isometric
---


# Question
Title: How best to handle ID3D11InputLayout in rendering code?
I'm looking for an elegant way to handle input layouts in my directx11 code.

The problem I have that I have an Effect class and a Element class. The effect class encapsulates shaders and similar settings, and the Element class contains something that can be drawn (3d model, lanscape etc)

My drawing code sets the device shaders etc using the effect specified and then calls the draw function of the Element to draw the actual geometry contained in it.

The problem is this - I need to create an D3D11InputLayout somewhere. This really belongs in the Element class as it's no business of the rest of the system how that element chooses to represent it's vertex layout. But in order to create the object the API requires the vertex shader bytecode for the vertex shader that will be used to draw the object. In directx9 it was easy, there was no dependency so my element could contain it's own input layout structures and set them without the effect being involved.

But the Element shouldn't really have to know anything about the effect that it's being drawn with, that's just render settings, and the Element is there to provide geometry.

So I don't really know where to store and how to select the InputLayout for each draw call. I mean, I've made something work but it seems very ugly.

This makes me thing I've either missed something obvious, or else my design of having all the render settings in an Effect, the Geometry in an Element, and a 3rd party that draws it all is just flawed.

Just wondering how anyone else handles their input layouts in directx11 in a elegant way?

# Answer
The way I handle this is that I have a VertexFormat.h file in which I have a bunch of input layouts of different types (VertexPositionNormal, VertexNormalUV...) wrapped in structs for easy creation/destruction. It works pretty well even though it's ugly IMO. It's very easy to add a new vertex format to the file if you have a shader that uses a layout that is not currently supported. Then I have a VertexFormatManager that creates/destroys those layouts when I need them. So when I need to create one, I feed the shader byte code and a vertexformat ID to the manager and it creates it for me and stores it in a pool so that you only ever have one of each layout. Then you need to create your geometry. To do this, I have a Create method on my geometry class that takes an ID for a vertex format. In the create function it queries the vertex format manager with the given ID. The manager returns an integer that serves as a bitfield with a flag set for every type of element the input layout contains. So I could have something like this:

```
int bitfield = VertexFormatManager::QueryFormat( formatID );
if (bitfield & VertexFormat::NORMAL)
{
    // do somethings
}
if (bitfield & VertexFormat::UV)
{
    // do somethings
}
...

```

Each input layout element is created into a separate ID3D11Buffer. That allows me to build a mesh given any type of vertex format. Say you want to render a cube with a texture, it needs vertex positions and uv coords. You feed it the VertexPositionUV (as an example) format ID, and the query return a bitfield contain set bits for the POSITION and UV flags. That create two ID3D11Buffers: one for the positions, one for the uv coords. Then you attach both of these to the pipeline before drawing. The advantage of doing this is that if you want to do something like shadow maps, you can render a mesh with only its vertex position buffer set.

I'm not sure much of this is very clear, I'm at work and I'll try and do a proper write up later tonight. In the mean time, I asked this question a while ago and got this answer . It's good, but I find that the way I'm doing it now makes more sense, especially in the case of DX11.
> 3 votes

# Answer
Thanks for the answers on this, they are very helpful. I'll add an answer to my own question because I've moved on a bit from there.

In the end I realized that perhaps wanting to entirely separate the shaders from the drawable items was a mistake. They are fundamentally coupled in "real life" so it's perhaps not an issue that they are in the design.

For example a water shader will only work with an element that wants to draw water. Only that will be able to provide the data it needs. A shader that draws animated models will only work with an animated model element. I can't suddenly decide to use a water shader with an animated model. It simply can't work.

Trying to make an abstract shader class that can load any shader and work with any drawable element is a mistake. It doesn't reflect how they can be used in reality.

So instead I've made shader classes AnimatedModelShader, WaterShader, LandscapeShader. Each of these might well have options that cause it to load different physical shader files but they will always have the same basic interface by necessity because a landscape shader will always need the same kind of data input.

So the shader is now responsible for creating it's own input layout and it *tells* the element using it how to layout it's vertices by having a public typedef called vertexType that the element uses if it wishes to use that shader.

Not at all my original design but as it turns out, the desire to separate the two concepts wasn't very useful anyway.
> 6 votes

# Answer
I do something similar to dotminic - I have a routine that I pass an array of D3D11\_INPUT\_ELEMENT\_DESC to, which then constructs a fake vertex shader with a matching input signature, compiles it, creates a layout from it, finally Releasing the fake shader.

Yes, it's ugly, and yes, it means needing to be a mite more careful than I otherwise would be if I did it the proper way, but they're tradeoffs I'm currently prepared to accept in exchange for a cleaner separation.
> 3 votes

# Answer
Looks to me like you really shouldn't need to worry. After glancing across the MSDN documentation for CreateInputLayout, I came across this:

> Once an input-layout object is created from a shader signature, the input-layout object **can be reused with any other shader** that has an identical input signature (semantics included). This can simplify the creation of input-layout objects when you are working with many shaders with identical inputs. **(Bingo)** If a data type in the input-layout declaration does not match the data type in a shader-input signature, CreateInputLayout will generate a warning during compilation. The warning is simply to call attention to the fact that the data may be reinterpreted when read from a register. You may either disregard this warning (if reinterpretation is intentional) or make the data types match in both declarations to eliminate the warning.

http://msdn.microsoft.com/en-gb/library/windows/desktop/ff476512(v=vs.85).aspx

The makes it quite clear that you should be able to treat your input layouts in almost exactly the same way as your old DX9 vertex declarations. Providing shader bytecode the first time you create each of them just allows DX11 to validate them. And apparently the worst that will happen if you avoid or fail this step is a runtime warning which seems safe to ignore.

So DX11 isn't "creating a dependency" between your input layouts and your shaders... it's offering free validation! :D
> 2 votes

---
Tags: directx11
---


title: How to deal with "level design creep?"

text:
# Question
Title: How to deal with "level design creep?"
Level Design Creep is what I've started to call what happens when you build a series of levels and notice that every level is a little bit better looking or designed than the last, or when working together with several people with different skill levels. Left alone, as the player goes through the game the level quality would go up and down according to the order the levels were built. It seems like we're spending more time on this than we should be.

Besides cutting out the really good and really bad levels, is there a way I can plan for or manage the production so that the detail doesn't "creep up," and we have to revisit the same work over and over?

# Answer
> 40 votes
This happens in almost every game -- as the artists become comfortable working with the tools, and as improved tools become available during production, the later levels to be constructed are almost always built to a higher level of quality in a shorter amount of time.

To cope, you want to do **all** of the following three things:

1. Assume that you'll have to revamp the first few levels built by each artist and level designer. For a game with one artist/designer team which is making ten levels, budget to do extra work on the first two levels toward the end of production, to bring them up to meet the quality level of the later-produced levels. If you have more teams which are working independently, then you'll need to revamp more levels.
2. In addition to the above, plan for each team's first few levels to take longer to build than the later ones. My experience has been that budgeting for 2-3 times the normal production time for the first two levels from each level designer/artist is in the right ballpark.
* The idea here is that allowing extra time for the first few levels lets the designers/artists go through the whole learning process within the confines of just one or two levels, so you only have to revise those few levels at the end, instead of having to revise everything because they were still discovering new techniques while building their later levels.
3. Bearing in mind that even when following the two recommendations above, the first few levels you build are still very likely to have a slightly lower quality level than the others, so don't let your team build your game's first level first. The first level you build should be somewhere in the middle of the game. Having a slight dip in your general "level quality bar" can be catastrophic if it's the first thing the player sees. Much better to put it midway through the game, so the player won't hit it until he's invested in the game.

---
Tags: level-design, project-management, planning, time-management
---


# Question
Title: Disable autorotation if Android has it disabled
I'm making a game for Android in Unity. I wanted the game to handle screen rotations, so I set "Default Orientation" to "Auto Rotation. This works well, except for one issue:

If you disable auto-rotation in the device's settings, the game ignores this and keeps autorotation.

How would I go about making it disable autorotate when the Android device is set to disable autorotate?

# Answer
I haven't tried it yet, but this might help.

Read the orientation using the platform SDK as Sundeep mentioned:

```
android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0)

```

and use the returned value to enable or disable the orientation by changing `Screen.orientation` to `ScreenOrientation.AutoRotation` or any other value as you wish.
> 0 votes

# Answer
I haven't worked with unity anytime, but a quick search turned out you can get the Android API in Unity. If it is not, take this as a way to ponder.

Try this in the activity

```
android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0)

```

If it returns 1, rotation is ON. 0 means rotation is OFF.

You can use the method `putInt()` if you want to change the setting.

Do not forget to set the permission:

```
android.permission.WRITE_SETTINGS

```
> 1 votes

---
Tags: android, unity, mobile, screen
---


title: How do I scale down pixel art?

text:
# Question
Title: How do I scale down pixel art?
There are plenty of algorithms to scale **up** pixel art. (I prefer hqx, personally.) But are there any notable algorithms to scale it **down**? My game is designed to run at a resolution of `1280x720`, but if it is played at a lower resolution I still want it to look good.

Most pixel art discussions center around `320x200` or `640x480` and upscaling for use in console emulators, but I wonder how modern 2D games like the Monkey Island Remake could look good on lower resolutions?

Of course ignoring the option of having multiple versions of assets (i.e. mipmapping).

# Answer
> 15 votes
I'm currently making a game that has to run on a wide variety of display sizes and aspect ratios, and it hasn't been a very easy process. In addition, if you're making things in pixel art, and you want to keep the pixel art feeling while supporting many resolutions, you're walking into a world of pain, so be prepared.

In my opinion, there are several things you can do (some are exclusive, but others are not)

1. Define a minimum resolution, and only upscale (everything) in integer terms with nearest neighbor. That way you can keep the pixel art feeling. I don't think downscaling is a good idea, as you will lose detail, and the entire purpose of using carefully crafted pixel art will be defeated. If your minimum supported resolution is too small for your sprites, either change your minimum supported resolution, or redraw all assets to support this minimum resolution.
2. When you encounter a resolution, or aspect ratio that is not enough to cover the entire screen, extend your game (show more tiles), while keeping the assets intact. You should make your game so it is still playable with the minimum resolution/aspect ratio though.
3. If extending the game is not possible, fill the non-game sections of the screen with black; either stripes at the top and bottom, left and right, or a black frame. This is what the iPad does when running iPhone apps in magnified mode. This is also widely used in emulators.
4. Give up on keeping true to the pixel grid. But you then have to stop using pixel arty assets with sharp corners. Then upscale/downscale using bilinear (or optimally bicubic, if your platform supports it) filtering. This is the best choice for maximizing screen usage, while keeping the user experience similar across all supported resolutions.

For my game, I ended up doing option number 4, and I'm quite surprised at how good it looks on devices ranging from 320 pixels on the vertical (an old Android 2.3) up to 1536 pixels on the vertical (a 2012 iPad with retina display). The original assets are meant for 600 pixels on the vertical (originally for 800x600 display on a Windows PC). Although for subsequent games, I think that a better logical vertical resolution is 720 pixels.

The game uses a virtual 600-pixel high virtual resolution, scaled to the device native resolution with bilinear filtering. This means that all in-code Y-coordinates go from 0 (top of the screen) to 600 (bottom of the screen).

For the horizontal size, I suppose the maximum width is 1080 pixels, which is more than enough to cover even the widest 16:9 aspect ratios. My x-coordinates are centered, so x=0 is the center of the screen, and x-coordinates go from -540 on the left to 540 on the right. I make sure everything fits between -400 and 400 to support the narrowest displays (4:3)

However, if I had to keep the pixel art feeling, I'd certainly use options 1 and 2. Meaning that I'd only scale in integer terms to keep the blocky feeling of pixel art, and design the game so the amount of visible tiles is not fixed and can adapt to any screen resolution/aspect ratio.

So, in order to (not) answer your question. I think that downscaling pixel art is a very bad idea, so you should not do it. There are other ways to support different screen resolutions that will provide better results than simply butchering your carefully created art.

# Answer
> 8 votes
Consider actually generating the scaled down versions at development time, and including them directly in the game as a resource. Do this with Photoshop or whatever tool you find creates what you like. Then have the game dynamically select the right art set appropriate to the current resolution.

Here are a couple of reasons you might do this...

**Saves Processing Work**

If you did rescale programmatically at runtime, your software will probably create and cache the artwork anyway. So why not just include the scaled down versions in the art asset bundle? I suppose if it made the download bigger than you'd like it might matter, but you'll save on some CPU load, disk writes, etc.

**Greater Artistic Control**

If you rescale the art yourself, you will have greater control over the final appearance. That might not make a difference if you are scaling down a small amount, but when you get to much lower resolutions, you may wish to have better artistic control over the final appearance. For example if a specific character's eyes needed to be emphasized, you might actually draw the lower resolution versions with the eyes not scaled down as much to retain the effect -- something that programmatic scaling can't do.

**Dynamic Scaling Isn't Perfect**

You may make distinctive artistic decisions that do not work with dynamic scaling. For example, suppose you want to put a border, outline or highlight around an image. When viewed at higher resolution, this may look fine, but the scaled down version may muddy or entirely lose the effect. But if hand done you can specifically apply the effect to each size yourself and guarantee you retain the impact.

**Other Thoughts**

You could also do a hybrid approach, with a set of resolution-specific resources that are used where found, and a generic set that is dynamically scaled if no resolution-specific version is found. This is a bit like how the Android platform works. Some info on this at http://developer.android.com/guide/practices/screens\_support.html

# Answer
> 0 votes
Resizing down is easier than resizing up because you're choosing information to throw away rather than having to invent new (and possibly incorrect) information to fill in the gaps. With that in mind, you probably don't need anything special here and most standard resampling algorithms from the realm of image processing should work fairly well for scaling down an image: bilinear, Gaussian, Lanczos, etc.

Lanczos in particular might be an interesting choice as it sharpens the image, possibly preserving detail that would otherwise be lost when combining several pixels into one. Obviously this comes at the cost of potentially introducing unwanted artefacts.

Some visual comparisons here: https://gis.stackexchange.com/questions/10931/what-is-lanczos-resampling-useful-for-in-a-spatial-context

---
Tags: graphics, graphics-programming, pixel
---


title: Armature in Unity3d distorted

text:
# Question
Title: Armature in Unity3d distorted
On the left is a base mesh with armature in Blender. I imported this model and armature into Unity3d.

The result is on the right. The arms are clearly distorted, and I can't seem to fix it by rearranging the bone assignments.. It looks fine in Blender. Why is it doing this?

# Answer
> 3 votes
Are you sure the Blender screenshot was taken with the armature relaxed (ALT-R to relax the armature). Also make sure you're not in pose mode but rather in object mode when looking at your mesh's position in Blender, to see how it will look when imported in Unity. Finally, apply all transforms to object before exporting to Unity (CTRL-A, then Aplpy Scale, Apply Translation, Apply Rotation).

==Update as per #1 comment:==

Ok, it's embarassing, but at the moment I'm having difficulties watching the YouTube video you link to. At any rate, here's how I've imported blender animations in Unity and it worked fine:

Create your animations in Blender. Do them at the bone level, don't do anything like "baking" bones animation into mesh. Just animate the bones, and then you have your mesh deformed by the bones. If you want to do "multiple animations" (i.e. have like a walk animation and a run animation for your character, which than later on you want to split inside Unity) make sure you leave at least 10 frames between each chunk. If you leave just one or two, due to Unity's way of importing your animations (I think Unity doesn't just import animations "as-is" but does some compression/interpolation on them as well) you'll have one animation "leaking" into the other. Example: You have a 40 frames walk animation and a 30 frames death animation. If, in Blender you make them at frames 1-40 and then 41-71, when you go in Unity and you tell it to split your animation into to, one from 1-40 and another one from 41 to 71, when you play your first animation, you'll notice that the walk end with the first frames of the second (death) animation. If, instead you make your animations in Blender at 1-40 and then 55-85, you'll be fine importing them in Unity.

Now export mesh and bones from Blender (make sure to have them all checked), preferably in fbx format. .blend file should work as well, but I honestly never tried it for animations. Then import your fbx into Unity, tell it you have x animations, and set the proper start and end frames for each one. Then you have the "Animation" view (I hope I'm not mistaking on the name, it's the one you access from the "Window" menu) where you can select each animation and hit play to see it run. You can then also chose to loop it, ping-pong loop it etc.

That's how I've done it, and I managed to create a biped which walks, shoots, etc, separate the animations, all worked fine. Hope it helps.

---
Tags: 3d, unity, animation, blender, skeletal-animation
---


# Question
Title: Optimizing models & improving performance
I've created a map editor for a game I've been developing. The maps (planets) are made using a form of meta ball editing. Basically, in the end the Marching Cubes algorithm is used to get my final model.

Here's an example:

In the game however, when planets are or a largish size, as you would expect, I start having quite a lot of lag. So what I was wondering, is are there any good libraries out there that could be used to remove clusters or triangles that are basically flat and turn them into a single triangle?

I'm not after simply reducing the count, I want the same amount of detail, but to merge triangles where their normal is practically the same.

Also curious, as to how you would go about having more/less detail as you approach/leave areas of a planet. Obviously chunks isn't the easiest method when the world's a sphere.

The project is in C#.

# Answer
> 8 votes
What you are looking for is called a mesh simplification/decimation algorithm. There are several of them out there, you'd just have to implement the one you choose in C# if no C# implementation exists.

Here are a few that Google turned up:

From a quick search, the only C# implementation that I found was part of Managed DirectX (predecessor to XNA), it had a `SimplificationMesh` class.

# Answer
> 3 votes
You can follow Robert's suggestions.

If you're looking for a sharp implementation, you could try to wrap some of the modules of the CGAL library (that's C++ based) using C++/CLI (the C++ managed dialect). I suggest CGAL since it's quite one of the best libs for this kind of jobs.

For a more in-depth understanding and/or a from-scratch implementation (shouldn't take you more than a week), you can consult the seminal papers of Hoppe (Microsoft Research) and that of Greg Turk on mesh decimation via edge collapses (heuristic based approaches for progressive mesh simplification/multiresolution applications/LOD):

*Additionally*, a fairly interesting and more mathematical approach was built using *lifting schemes* and second generation wavelet analysis and synthesis. In essence, that means that if you have a subdivision scheme on your hands (say the Butterfly scheme), you can find a converse decimation operator (from many to fewer points). If you already have a "nice" surface in terms of how the triangle faces are distributed and of the density of regular points (those with valence 6), then you can apply the decimation operator to do the job.

If you want to achieve multiresolution representation, the steps are crudely summarized as follows:

1. decimate the mesh M\_{i+1} to a mesh M\_{i}
2. subdivide M\_{i} and record the differences between S\*M\_{i} and M\_{i+1} as the so called *wavelet coefficients*
3. a well chosen subdivision scheme is expected to *predict* the positions of the removed points (via edge collapse/decimation,etc.) quite well - hence one can threshold the differences/wavelet coefficients and discard small values

In the end, you get a coarse resolution M\_{0} and a hierarchy of *detail* vectors which you usually store. Considering that most of those coefficients were discarded, you get a storage space optimization. You can, of course, apply some floating point numerical compression (quantization, Huffman and/or entropy encoding, what not) - but that's not the point of your question. The advantage is that the coarsest level mesh, M\_{0} only requires the storage of a few hundred points, whereas the initial mesh could've been millions of vertices large. You get the intermediate levels through subdivision and correction via your non-zero wavelet coefficients. Again, considering that many of the differences are expected to be small, you automatically gain the edge since you store less information than within the original mesh and get the intermediate LODs at the expense of your CPU (which is much better than pushing that info over a socket, for example).

Some wavelet multiresolution bibliography:

---
Tags: models, optimization
---


# Question
Title: Is a programmer liable for copyright infringement in other people's mods to his games?
If a programmer (**P**) releases a game, and a modder (**M**) releases a game modification which includes copyrighted content, can **P** be held liable for the copyright infringement in the mod?

# Answer
I'm going to start off by being That Guy and noting that this site is the wrong place for this question. It's a potentially non-trivial legal issue whose precise answer, under various circumstances, will likely depend on details of local law and legal precedent, as well as on the relative abilities of the lawyers on each side to twist said law and precedents to their advantage and the attitude and preconceptions of whoever happens to be chosen to adjudicate the case. In short, **if you want a real answer, ask a lawyer.**

That said, out of the cases mentioned in your question before it was shortened, the M = P case is the easy one *if* that fact can be proven. Note that, again depending on jurisdiction, even just reasonable cause for suspicion might be enough to obtain a subpoena or a search warrant to acquire confirming evidence, e.g. from ISP logs (as noted in another answer) or even directly from P's computers, which might contain revealing traces of their activities as M.

The case where M's identity is known (and M ≠ P) is also *usually* simple for P, since any plaintiff's attention will probably be mostly focused on M, and since P typically has a fairly good defense against any accusations by pointing to M and saying "he did it, I had nothing to do with it!" That said, as I'll note below, that defense isn't necessarily ironclad, if the plaintiff does decide that they want to go after P as well (e.g. because M is out of their reach, or too poor to pay for any damages even if found guilty, or just because they can).

Now, on to the meat of the answer: If P *does* get sued, either alongside M or because M could not be identified, it will likely be for **contributory infringement**. Basically, the claim would be that P knowingly aided and encouraged M's infringement, and materially benefited from it, by making the game moddable in the first place and continuing to sell it after becoming aware of M's mod's popularity.

It should be noted that, under most circumstances, that would be a rather tenuous claim. Making games moddable is standard industry practice, and, indeed, it shouldn't be hard to find expert witnesses to testify that making a game *unmoddable* is often difficult or impossible. As long as P's original product was a playable and salable game in itself (and did not, for instance, feature blank sprites and textures with "PLACEHOLDER" written on them) it would typically also be hard to argue deliberate intent to encourage infringement.

As for profiting from the sales driven by M's mod, that might depend on just *how* popular the mod actually became, but in most jurisdictions there should be either case or statute law — such as, notably, the "Betamax case" *(Sony v. Universal)* in the U.S. — exempting makers of products used by individuals to infringe copyright from contributory liability, as long as the product also has "substantial non-infringing uses" (to quote the Betamax decision). Indeed, if such an exemption did *not* exist, what would prevent the plaintiffs from just going directly after, say, Intel and Microsoft for making computers that could run the game that could host the infringing mod?

Of course, the situation could be different if it really could be demonstrated that an overwhelming fraction of all sales of P's game were driven by M's mod, and that P should have been aware of this. At least, someone could then argue that P should have patched the game (or at least any subsequently sold copies of it) to not run M's infringing mod (and to communicate this to prospective buyers). Of course, such efforts would likely be ultimately futile (as M could just patch the mod to compensate), but it *could* be argued that, if P hadn't even made any such effort after explicitly being made aware of M's mod and its popularity (and illegality), that could constitute evidence of willful encouragement.

For an example of similar arguments, see e.g. the recent Megaupload case (which, of course, has not actually proceeded to trial, but at least illustrates the kind of arguments that could be made).
> 8 votes

# Answer
> "If M, how ? It's easy for him to avoid any kind of punishment as "the mod" is free and therefore there are no business entities and hence M can simply leave no information about himself."

It doesn't matter whether it is non-commercial/free or not. Copyright always applies if something is being distributed. M only wouldn't be guilty if he wouldn't have distributed it at all (e.g. wouldn't have uploaded that to that public server), as long as the mod is kept in private it doesn't matter.

It's unprobable that P could get in trouble because he wasn't the one distributing that mod, whether he profited from it or not doesn't matter. In the case of P = M it first would have to be proved that P = M or at least a relation between P and M.

It would have been a different point if the mod was on P's server, because in that case he would have to make sure that CC isn't uploaded there and/or that it isn't he is not responsible for the content.
> 6 votes

# Answer
*Note: This answer is in response to an earlier version of the question, which asked both whether P is liable in general and whether if P = M allows P to profit from copyright infringement"*

As I understand it, the primary question is "If a modder breaks the law, is the creator of the base game liable?" The answer to this is generally no. The other answers have covered this pretty well.

However, you make some assumptions (If M, how? It's easy for him to avoid any kind of punishment as "the mod" is free and therefore there are no business entities and hence M can simply leave no information about himself.). I would disagree with these assumptions. As recent events with file-sharers have found out, if you are on the internet, you are not truly anonymous. Your ISP can and will be subpoena'ed for your information. Regardless of whether the modder is anonymous or not, it is undeniable that he is infringing.

This leads us to the final point "In the case when P = M, and we've established that the modder is guilty(but hard to find), does this mean that P can make money without being caught?" You are basically asking, "**If P breaks the law, but do not get caught, does that mean he can make a profit off copyright infringement?**"

**This is a nonquestion.** Of course, if you break the law and don't get caught, you can make a profit. This is how crime works. But let us consider what happens when you do get caught (I am not a lawyer, and my answer is based on information such as http://itlaw.wikia.com/wiki/Copyright\_infringement#Willful\_infringement)

1. Copyright infringement becomes a felony when it is both for-profit and willful. If M is caught (via subpoenas, investigators, etc.), it becomes obvious that M = P, and the legal argument that he was infringing willfully becomes that much more convincing.

Willful Infringement carries not only a higher limit on the statutory damages you will be sued for (and if you are making a lot of profit, do not expect that the suit will be just for statutory damages) it also raises the level of felony the infringement constitutes.
> 6 votes

# Answer
Valve does this kind of thing very well. Like I believe they do, you can basically state, "If someone modifies our game, that is outside our control and therefor not our responsibility"
> 4 votes

# Answer
Hypothetically, if you're both **P** and **M**, then this is copyright infringement. If the **P** side of you makes tons of money with this, the copyright holder might get angry about it. In this case I hope that you were *really* anonymous while publishing this mod. IANAL, but the simple fact that you're the only one making a profit might be charged against you.

Conlusion: **this is a dangerous move**. Forewarned is forearmed.
> 2 votes

---
Tags: legal, modding, copyright
---


# Question
Title: How to make model's arms + weapon follow cursor?
0 Just like the title says. I currently have my controlling movement working just how I want it to. Now in order to proceed with shooting I first should focus on how the model should look like to determine how my script should act when firing. Currently I am using Unity's Constructor model, but now I need to create my own model just to get the arm movements to follow how I want it to. I have an idea how to make the arms follow the cursor, by adjusting the X and Y axis rotation to follow the position of the cursor, taking on screen coordinates then using Atan to find the right angle. First I have no idea how to make a model, so I guess I need to figure that out first, but how can I make it move like the constructor model from Unity. I have heard of rigging, but still not sure what that is. I have played with C4D when in high school which I noticed while modeling it help provide a human like effect when controlling joints. I am planning on using Blender so if anyone had 3D modeling humanoids video with rigging or skeletal joint or something. Not an artist at all, but I need a model I suppose.

This is a 2.5D platform game, 3D environment with 2D physics.

# Answer
> 1 votes
What I suggest is to have a right where the arms and weapon bones all follow the same inverse kinematic target. This ars-and-weapons IK target is in turn parented to the global ik target. For example if you're using Blender use some "Empty" objects for the IK targets.

Then in unity just have the arms-and-weapon IK target point towards the mouse when needed. This way your over-all IK target will be controlled by the player controller (and move yoru whose character around) and furthermore, when the mouse cursor moves, the arms-and-weakpon IK target will keep pointing towards them while at the same time also having the transformations for the global IK applied to it (ie if the character is moving forwards and the mouse is somewhere to the right, the character will keep advancing but his arms and weapon will keep facing the cursor).

You might also want to add some transform constrains on the transformation of the arms-and-weapon IK target (or the bone it ifluences) such that the player's arms don't gen in non-humanly-possible postures.

---
Tags: models, skeletal-animation
---


# Question
Title: Function calls between classes and driver program in text based game
I'm making a text based game in C++, but I've hit a snag. I have three classes, plus the driver program. One class is for the player, one for monsters, and one for battle related functions.

My question is, what would be the best way to split up the functions between the classes? Right now I have the variables and functions that create and store all data for the player character (typical RPG style stats, the player menu for commands like move, inventory, etc.), the inventory, and the structs I use to create weapons and armor in the player class. I have a similar class for creating monsters.

I originally intended to put all of the functions related to fighting in the battle class, but then it occurred to me that I'll need all of the data of the player and monsters for the fight function. So, I wrote the main fight function in the driver program, where I create the player and monster objects, and therefore have access to the private member variables of each. However, since I have the "move" command in the player menu (which is in the player class), and it calls a random encounter function, and I want the fight function to be called if a random encounter happens (but the fight function is declared in the driver program), I'm stuck.

So, what I need is advice on what the best practice would be for where to declare the fight function.

# Answer
> 1 votes
It's really hard to answer that question, because, sadly, there are no general answers to design questions. It doesn't really matter if it's C++ or any other language supporting OOP. If you want to get some general knowledge, you should get a book about OOP design (*OO Analysis and Design* from Head First Series is rather nice).

General tips for creating designs is usually to follow basic principles such as:

* **DRY** \- Don't Repeat Yourself - pretty straightforward. Reuse everything!
* **SRP** \- Single Responsibility Principle - an object should be responsible for **one** task
* **KISS** \- Keep It Simple, Stupid - don't overcomplicate.

If your code follows basic principles of OOP (such as hermetization) and these rules, it becomes more of an art to create a good model.

Anyway, a tip from myself: static languages such as C++ aren't really well suited to make logic in them. Given that nowadays PCs are a lot faster and you don't need ASM or Pure-C optimizations everywhere, script languages can really help you develop your game logic faster with more ease. I'm a great fan of Lua, but there aren't much problems with embedding Javascript (Google V8) or Python (Boost.Python) in your C++ application.

# Answer
> 0 votes
There are a few different things that could be commented on here, but I'll stick to one for now. Now, I am not a professional game programmer, but it sounds like having the battle functions in a class separate from the driver is good logic. To make this work, it seems to me all you would have to do is pass the player and monster objects to the "battle class" as parameters. Objects can be passed as function parameters just like variables are. look into that and see if it helps you resolve any of your issues.

---
Tags: c++
---


title: Increasing height increases width

text:
# Question
Title: Increasing height increases width
I have a game, where the user presses a button to spend money and increase the **height** of a Movie Clip. I use the following: `height ++`.

The problem: When I test this out, it seems the width increases, too. The actual thickness, you could say. How can I solve this?

# Answer
I fixed it by selecting the **line** in my movie clip and changing the **scaling** property to **none**.
> 2 votes

---
Tags: flash, actionscript-3, actionscript
---


# Question
Title: Mouse position to world position for Camera
I am working on a case where when the mouse is moved upwards, the camera must also move upwards.

I understand that for mouse picking we perform ray casting along a plane. I think my case is little different, the camera movements(x,y,z) must be linked with mouse movement(x,y) in all directions.

I am using the OGRE 3D engine.

# Answer
Ogre3D itself cannot handle that situation as it is a pure rendering engine, hence you need some input library. The standard solution for Ogre applications is using OIS which even comes bundled with Ogre.

What you then need to do is to create an OIS::MouseListener (e.g. by letting your main application class inherit from it) that will deal with your mouse move events and react accordingly, in your case rotate the camera.

```
bool YourClassInheritingMouseListener::mouseMoved(const OIS::MouseEvent &evt)
{
    m_pCamera->yaw(Degree(evt.state.X.rel * -0.1f));
    m_pCamera->pitch(Degree(evt.state.Y.rel * -0.1f));

    return true;
}

```

For a more complete example have a look at the BasicOgreFramework I created which handles mouse movements to rotate the camera as well as keyboard input to move the camera.
> 1 votes

# Answer
I faced similiar issue. I then understood that we need to unproject the mouse co-ord to local co-ord. For doing this follow below :

1. Form a mouse ray depening on your screen size.

```
mouseray = camera->getCameraToViewportRay(screenPos.x/width,screenPos.y/height);

```
2. Create a plane which must be parallel to camera and at any position.

```
plane = plane(camera->getDerivedDirection(),vector3(0,0,0));

```
3. check weather the mouse ray hits the plane on which camera is projected.

```
std::pair<bool,dist> interectionResult  = mouseray.intersects(plane)
if(interectionResult.first)
    WORLDPOS = interectionResult.second;

```

I think this will help you.
> 1 votes

---
Tags: ogre
---


# Question
Title: Project rendering onto a polygon in the scene
I have a function that renders a simple OpenGL scene. I want to display this scene on a polygon within another scene, without the function having to know about it. For example, to display the scene on the red polygon indicated:

I can set up the projection and modelview matrices to render to a small rectangle on the screen, but that doesn't work in a case like the image shown, where the target polygon is transformed and is no longer a rectangle on the screen. Is it possible to render to a non-rectangular target like this? The target is defined by four vertices, and I'm just not sure how to put those into the matrices.

I am aware of VBO/FBO functions that can render the sub-scene to a texture, which could then be mapped onto the polygon. However, this would be a bit more work as I'd have to add support for these functions to LuaGL, and I get the feeling it'd be slower than simply altering the display matrices - if it can even be done that way.

# Answer
You can use the stencil buffer to clip an arbitrary shape out. However, *you still need to compute the orientation of that red polygon*, and figure out what pixels it occupies, so you still have to use an FBO in order to get that stencil buffer each frame.

1) Render the small red polygon (to an FBO still) and create a stencil buffer from the pixels it covered

2) Orient the camera as you like and render the scene with that stencil buffer you just created active

## Using an FBO (recommended, easier, more flexible, "standard" way to do this kind of thing)

The way you would do this is:

1) Create an FBO with a texture2D as a backing

2) Render the scene (to the texture)

3) Now render your scene to the screen FBO, and render the texture you just created to the polygon you want it to display on

This is how you get "mirrors" to appear in games too.
> 2 votes

# Answer
You can use glReadPixels to read pixels from the frame buffer - explanation page
Hope this helps!
> 0 votes

# Answer
Doesn't LuaGL support any buffers? These can be normal renderbuffers, if FBO are unavailable. Anyway, adding hooks for these functions shouldn't be hard.

It can be done using proper matrix calculations, but it would be non-linear projection and would require really complex calculations. In every game it's simpler to just render to memory and then back on the screen; this also has the benefit of easy applying of post-effects.
> 0 votes

---
Tags: opengl, matrix, projection
---


title: Saving data in games?

text:
# Question
Title: Saving data in games?
I'm soon going to make a game for the iPhone as a school project.

My idea was to make a **TLOZ** remake, with Tiled Maps.

However, I'm not quite sure how save the data.
In **TLOZ** you have a lot of sub-quests, treasures, items, and much more.
I want the user to only be able to open a treasure once.

Therefore I have to save this information somehow.
However, I'm not sure how to assign the data to that certain object, for example that treasure that Link has opened.

I thought about making id's for every object, but I'll have multiple maps, and it doesn't seem like the right solution.

Are there any standards for this?

Or does anyone have another idea?

# Answer
> 5 votes
I would also go for the ID solution. You should give every object in your whole world (not just on the current map) a unique ID. A 32 Bit int should be sufficient. Further every object can store a state value, also a 32 Bit int value. You can squeeze a lot of information into 32 Bit, e.g. you can make 32 flags out of it to store 32 bool values. Or you can use the higher bits for flags and the lower bits to hold a numeric value. For something as simple as a treasure, you only need to store a bool, where a value of 1 means opened and a value of 0 means closed. The you have a game save object with two methods:

```
- (void)storeState:(uint32_t)state forObject:(uint32_t)objectID;

- (uint32_t)loadStateForObject:(uint32_t)objectID;

```

If you call store and there is no state stored for this object ID, the object ID is added to a list among with its state. If there already is a stored state, it is updated to the new state. The load method searches the list for the object ID (for fast access, consider a hashtable, so you don't have to perform a linear search or a sorted array, so you can perform a binary search) and returns the stored state or 0, in case no state has been stored (0 should always represent the default state for all objects).

When you now open a map screen, you initialize all the objects on that screen. The objects all perform a `loadState()` call to the current game save object to find out, what their initial state should be. For treasures, if it is 0, they display as closed and if it is 1, they display as opened. What is inside the treasure is usually hardcoded in the level data, unless you want to make it random, but if it is random, you don't have to store that in the state either, it will be randomly chosen when the treasure is opened. You may also make it partially random (e.g. the treasure must contain rubies, bombs, etc. and the amount must be at least between X and at most Y). Depends on how (un)predicable you want the game to be. I think the original TLOZ is rather predictable.

If the user now opens a treasure, the treasure updates its state in the game save object, indicating that it has already been opened. So next time the user enters the map screen, the treasure displays opened.

Whenever the game is stored to disk, the game save objects simply writes all known objectIDs and their states in the list to a file. This can be a simple list of two consecutive 32 Bit values like

```
<id1><state1><id2><state2>...

```

If a saved game is loaded, the game save object reads this list again and initializes its internal structure with it (the hashtable or sorted array). To indicate the length of the list, you may either store an additional int value in front, that tells the code how the long the list will be or you can terminate the list, e.g. by adding a final entry of objectID `0` to it, where `0` is reserved value (no real object in your game has this ID) and thus indicates the end of the list.

Of course not every aspect of your game may be savable that way, so a save game file may contain more information before or after the object state list. E.g. you may want to store how much rubies/bombs your character currently has, which other special item he posses, and so on. On the other hand, you could store all this to the list as well, using special reserved objectIDs. E.g. real objects start with objectIDs from 1000 upwards. If 0 is reserved, this gives 999 special object IDs. objectID 1 could store the amount of rubies, objectID 2 the amount of bombs, objectID 3 the kind of sword the player owns (in that case different values will indicate different swords; IIRC you could only have one sword at a time in TLOZ).

I admit that this is a very simply approach, but simple is usually good (think of the KISS principle). It should also be no problem to make this whole think very performant. Choosing the right data structure, adding to the list, searching the list and reading/writing the list from/to disk should be very fast, even on the slowest iPhone it should happen in no time. E.g. you can store everything in a `NSMutableDictionary`, keys are of type `NSNumber` with the objectIDs and values are `NSNumber` with the state information. Such a dictionary cannot be stored to disk directly (only dictionaries whose keys are `NSString` can be stored to disk with a couple of simple function calls), but iterating over a `NSDictionary` is really trivial. Just add all those 32 Bit values to a `NSMutableData` and this one can be saved to disk with a single method call. Loading is the other way round, read the whole file into a `NSData` (single method call again), iterate over the list and keep adding the keys and values to a `NSMutableDictionary`. Should be piece of cake.

I guess the original save format was somewhat similar to such a list, yet as the NES only had a 8-Bit CPU, I guess the values where only 8 Bit (that's why you could not have more than 255 rubies) and the objectIDs probably 16 Bit (16 Bit doesn't fit into the registers of a 8 Bit CPU, but just like 32 Bit CPUs can handle 64 Bit values, 8 Bit CPUs can handle 16 Bit values, it's just slower as multiple operations are required for everything that only requires a single operation for 8 Bit values).

## UPDATE

Since I think this is a cool project, I wrote some sample code to give you starting point, in case you decide to go that route. This would go into `SaveGame.h`:

```
#import <Foundation/Foundation.h>

@interface SaveGame : NSObject {
    @private
        NSString * _filePath;
        NSMutableDictionary * _objectStates;
}

@property (readonly) NSString * filePath;

- (id)initWithFilePath:(NSString *)aPath;

- (uint32_t)stateForObjectID:(uint32_t)objID;

- (void)setState:(uint32_t)state forObjectID:(uint32_t)objID;

- (BOOL)saveToFile;

- (BOOL)loadFromFile;

@end

// Special Object IDs
enum {
    HeartContainerCountObjectID = 1,
    // Value is the number of heart containers

    EnergyLevelObjectID = 2,
    // Value is the current energy level as "half heart count", so 1 is half a
    // heart, 2 is one full heart, 3 is one and a half heart, ec.

    RubyCountObjectID = 3,
    // Value is the number of rubies

    BombCountObjectID = 4,
    // Value is the number of bombs

    KeyCountObjectID = 5,
    // Value is the number of keys

    SwordObjectID = 6,
    // Values defined below

    ShieldObjectID = 7,
    // Values defined below

    BoomerangObjectID = 7,
    // Values defined below

    RaftObjectID = 8,
    // Boolean value, 1 player has raft, 0 player hasn't

    StepladderObjcetID = 9,
    // Boolean value, 1 player has stepladder, 0 player hasn't

    // ...and so on...
};

// Values for SwordObjectID
enum {
    WoodenSwordObjectState  = 0, // Default
    WhiteSwordObjectState   = 1,
    MagicalSwordObjectState = 2
};

// Values for ShieldObjectID
enum {
    WoodenShieldObjectState  = 0, // Default
    MagicalShieldObjectState = 1
};

// Values for BoomerangObjectID
enum {
    NoBoomerangObjectState      = 0, // Default
    WoodenBoomerangObjectState  = 1,
    MagicalBoomerangObjectState = 2
};

// ... and so on ...

```

And this into `SaveGame.m`:

```
#import "SaveGame.h"

@implementation SaveGame

@synthesize filePath = _filePath;

- (void)dealloc
{
    [_filePath release];
    [_objectStates release];
    [super dealloc];
}

- (id)initWithFilePath:(NSString *)aPath
{
    if (!aPath) {
        [self release];
        return nil;
    }

    self = [super init];
    if (!self) return nil;

    // aPath might be a NSMutableString, so `retain` is not safe.
    // It's better to copy it. If `aPath` is a `NSString`,
    // `copy` in fact only retains the object instead copying it.
    _filePath = [aPath copy];
    if (!_filePath) {
        [self release];
        return nil;
    }

    _objectStates = [[NSMutableDictionary alloc] init];
    if (!_objectStates) {
        [self release];
        return nil;
    }

    return self;
}

- (uint32_t)stateForObjectID:(uint32_t)objectID
{
    NSNumber * stateNum;

    stateNum = _objectStates[@(objectID)];
    return (uint32_t)[stateNum integerValue];
}

- (void)setState:(uint32_t)state forObjectID:(uint32_t)objID
{
    // 0 is a reserved ID, must not be used
    if (objID == 0) return;

    _objectStates[@(objID)] = @(state);
}

- (BOOL)saveToFile
{
    NSUInteger capacity;
    __block uint32_t * raw;
    NSMutableData * saveData;

    // `raw` must be `__block` as we want to modify it within the block
    // and the modifications should be visible next time the block is called.

    // Two 32-Bit ints per state + end of list terminator
    capacity = sizeof(uint32_t) * (([_objectStates count] * 2) + 1);
    saveData = [NSMutableData dataWithCapacity:capacity];
    if (!saveData) return NO;

    raw = [saveData mutableBytes];
    [_objectStates enumerateKeysAndObjectsUsingBlock:
        ^(NSNumber * key, NSNumber * value, BOOL * stop) {
            *(raw++) = (uint32_t)[key integerValue];
            *(raw++) = (uint32_t)[value integerValue];
        }
    ];
    // Terminate list
    *raw = 0;

    return [saveData writeToFile:_filePath atomically:YES];
}

- (BOOL)loadFromFile
{
    NSUInteger i;
    NSUInteger count;
    NSData * saveData;
    const uint32_t * raw;

    saveData = [NSData dataWithContentsOfFile:_filePath];
    if (!saveData) return NO;

    // Even thouh the list is terminated, make sure we never read
    // beyond the end of the `NSData` memory! Don't rely on the
    // termination, it may be missing, the file may got corrupted, etc.
    // Also the file might have been truncated to 0 bytes, so be careful.
    raw = [saveData bytes];
    count = [saveData length] / 4;
    for (i = 0; i < count; i++) {
        uint32_t state;
        uint32_t objectID;

        objectID = *(raw++);
        // Stop `for` loop if end of list terminator is found
        if (objectID == 0) break;

        state = *(raw++);
        [self setState:state forObjectID:objectID];
    }

    // The list terminator was found way too early.
    // The save file is probably corrupt.
    if (i < count - 1) {
        [_objectStates removeAllObjects];
        return NO;
    }

    // No list terminator was found at all, the `for` loop was
    // terminated by the counter condition.
    // The save file is probably corrupt.
    if (i == count) {
        [_objectStates removeAllObjects];
        return NO;
    }

    return YES;
}

@end

```

The code is untested, but I verified that it does compile. It doesn't assume you are using ARC (automatic reference counting), but in case you do, the code will become somewhat simpler (all `retain`/`release` calls can be removed and `dealloc` must not call `[super dealloc]` in that case; `copy` calls need to persist also with ARC).

Of course, if all the "objects" like the player's sword are also represented by real objects in Obj-C, I would **not** place the values for the object states (`...ObjectState` enum values) into the `SaveGame` header. There is no need why the "whole app" needs to know about them, it's enough if the objects know how to interpret the state numbers. In that case I would place them into the implementation files of these objects, since this knowledge should then be private (encapsulated by the object).

I found a pretty useful web page, that lists all the objects from TLOZ.

Storing the Triforce State in object IDs is also easy. Each piece is represented by a flag (you have 32 flags per int, the Triforce doesn't even consist out of that many pieces).

Storing the dungeon maps seems a bit harder, but that isn't really the case. You know, those overview maps:

You only need to know which rooms the player has already visited and if he has the compass for this dungeon or not. Easy. Each room of of each dungeon has an objectID with a boolean state, that is 1 if the player has visited the room, 0 otherwise. Same goes for the compass, the compass of each dungeon has a boolean state. Same goes for doors in the dungeons (which may have been opened or not) and "crack-walls" (which may have been bombed or not), each one has a unique ID and a boolean state. All information of this game can be stored in this one simple list... it's pretty amazing, don't you think :-D

Here is a very cool web page that has detailed maps of all dungeons of TLOZ, as well as an overview map of the whole overwold. Including information where specific items can be found (including secrets). Also check out the "Interactive Overwold Map", which allows you to navigate a 3 by 3 screens map and show/hide secrets and tips, including the insides of all secret caves. Basically this page contains all the information necessary to make an exact copy of the game, pixel for pixel you like.

The game logic is rather simple and the whole game will tun out to need much less code than one might expect. I guess the most time consuming task is setting up all the maps of the game, defining all the object IDs and so. Doing all this "in code" is probably a rather bad idea. I would think of a format that your code can parse, e.g. XML or JSON or maybe something as simple as structured ASCII text. Each map has a fixed number of "fields", so you could store each map as X by X values, where each value defines the content of the field: a tree, water, a coast line and which coast line, rocks and which rocks, a wall and which wall, an enemy and which enemy and into what direction it is looking (most enemies cannot look at a direction, thus you could treat the looking ones simply as different enemies, there are only 4 directions they can look at after all). Values below a certain value represent static objects, those are always the same when you enter the screen, all other values represents dynamic objects (those that store their state) and the number is split into two parts, one part is directly the object ID of the object, the other part the type of object. E.g. dynamic objects have the highest bit set, the next 7 bits define the object type (allows 127 types, e.g. 1 is a door) and the last 24 bits are directly the object ID (allows up to 16.7 Mio objects, you won't need that many), however keep in mind that values below 1000 are reserved as special values.

Since creating levels is often the most time consuming task, you may want to speed the process up and instead of starting by writing the game code, you start by writing a level editor for your PC/Mac. This seems like a waste of time, since it will take a lot of time, but trust me, it DOES pay off. Most professional games started by writing at least a simple level editor. It makes creating levels a very easy task (drag'n drop an object where you want it to be, give it an object ID if required, done). So not only it speed up the level creation process dramatically in the end, you cannot test your game code unless you have level data for testing it, since untested code is worthless code. And if you only created dummy level in the beginning, an editor allows you to quickly create them and also quickly change them to test certain aspects of your code.

Now go out and have fun young jedi. I wish plenty of luck with this project.

## Update 2

If you'd like to use all the original artworks in your project, I found them online. Have a look at this page. It contains all the sprites used in the game. Even the original font. Just thought this might be useful for you.

# Answer
> 6 votes
The key phrase you're looking for is **game state serialisation**.

**Game state** is what it says. Your game has some sort of structure to keep the current state of the game. In an RPG game, you want to store the list of quests the player is on, how far they are into those quests and what their characters' stats are.

**Serialisation** is the reversible conversion of a data structure and its contents into a storeable format. You can find serialisers for various languages. The key here is *reversible*. The serialised program state can be used to sufficiently completely restore a program's state. Just for tasters, here's a Java explanation and a list of Lua implementations.

If your game state is fairly simple, you might want to write your **own serialiser** for the data. As a trivial example, consider a boring game in which a player is able to move on a 2D plane. They have coordinates `x` and `y`. To serialise the game's state (the `x` and `y`) you could simply write them onto two lines of a text file. To restore the game state, read the text file and parse the first two lines into numbers that you assign to the variables `x` and `y`.

# Answer
> 2 votes
First you have to ask yourself what you need to be saving. For a Zelda style game, what map the player is on, what quest you have completed, and what items you have should be enough. I usually just write that data in some semi readable text form and store it in a file. It usually does not have to be more complicated then that

# Answer
> 2 votes
I would create a system where there is a central object, `GameStateSerializer`, that keeps track of all objects with a certain interface, `ISerializable`. If a class implements this interface, it will be able to save its persistent data and then read it in again when the object is loaded, thus enabling save games.

The interface will have two functions: one for saving, one for loading. Both functions will have a stream parameter so they can write and read their own data without needing to know *where* that data is going. The `GameStateSerializer` is responsible for managing those streams. This decoupling allows 99% of the code to stay the same even if you decide to change to save games stored on the cloud; simply use a network stream instead of a file stream. You could also then apply compression or encryption through the `GameStateSerializer`.

Additionally, each unique serializable object should have its own unique ID. This way, the `GameStateSerializer` can map an ID to an object and be able to load the objects in the correct order or at least be able to hand the correct data to the correct object. These IDs can be determined automatically by the game's level editor.

For example, a treasure chest object will have a boolean flag that indicates whether it has been opened, or, like in most Zelda games, a flag to indicate whether or not it has appeared after the player has solved a puzzle. The chest class will inherit from the `ISerializable` interface and implement the two functions. The `Read` function will read the two flags from the stream, and the `Write` function will write the two flags from the stream. Remember to always read the data in the same order that you write it in.

# Answer
> 2 votes
You are definitely on the right path, I believe that having an ID for all objects in some sort of database is the way to go. The way you model your database is up to you though, there are multiple ways to achieve what you want each one with pros and cons.

For example, in your database, you could have a list of all "Treasures", it can contain information such as what's inside and whether or not it's been opened. On your map, you could place that Treasure and your character will behave different based on the properties of that Treasure object (opened or not and content).

You could also keep a list of Treasures that had been opened in the past, when the player tries to open the chest, it checks to see if it's in the list of opened treasure to see if it has previously been opened. If not, reward treasure and add it to the list of opened treasure. I prefer the other solution better, but as I said, there are many different alternatives.

Thank you and I hope this helps!

---
Tags: iphone, data-structure, databases, savegame
---


# Question
Title: Non-physics character movement in a Box2d Environment
I am in the process of creating a physics platformer. However, I want the player movement to feel very old-school(as in: non-physics like), which means that the character:

* Should always move equally fast horizontally, even on slopes.
* Has a reasonably fast jumping movement. The 'normal'(earthlike) gravity that is the default of Box2d tends to feel floaty.

Now, I have been trying lots of things to create a Box2d player that works this way. Multiple questions over the past few weeks are related to problems I've encountered with that:

* I increased the gravity and the density of the player to ensure they would jump/fall faster. (see this question)
* I worked with the 'unicycle' model(a square connected to a circle) to prevent getting stuck behind small corners. The bad part was that the player was now unable to stay on any slope, because they kept sliding down.
* To prevent that, I learned that I had to keep the density of both objects low.(see this question) This again created the gravity problem. Also, while the player now was able to keep standing on slopes, moving up on them was still extremely slow (and moving down incredibly fast).

I am getting a bit frustrated now over all this crazy behaviour that doesn't work the way I want it to. Now I am wondering:

Is there something wrong with the approach to handle the player's movement outside of Box2d, and after that let Box2d resolve the new collisions with ground and objects?

Or is this going to be extremely unstable and glitchy because I would 'teleport' the player instead of moving them with forces and is there still another, better way to get the movement I'd like?

# Answer
To make player move equally fast horizontally, even on slopes you can use technique of iforce2d. He changes tangent speed of contact in contact listener. Detailed description you can find there.
> 1 votes

# Answer
If you want specific and constrained behaviour, sometimes its easier to set the player as a kinematic body, meaning that it will act over other objects, but not the other way around.

Then you would program the player movement and behaviour yourself, and so it will always be what you expect, avoiding weird physical engines glitches.

You can for example switch to a normal body when the player dies, to get a cool ragdol effect :D
> 1 votes

---
Tags: box2d, physics, movement, platformer
---


# Question
Title: How many database connection should use in a MMO game server?
Game server links to database, how many database connection should use? The data update works like this: update role object to database every X minutes, commit all updates every Y minutes.

There are 3 ways:

1. Only one database connection
2. One worker thread one database connection and set transaction level to "Read Uncommitted". Worker thread loop all roles in it to do update & commit periodically
3. One game session one database connection and set transaction level to "Read Uncommitted". A dedicated thread to loop all connections to do update & commit periodically

Method 1 has a problem which database connection object needs shared by multiple worker threads, for JDBC, connection class is thread safe, but I don't know what about C++ such as MySql driver. If it have to use mutex to make thread safe, there will be a performance degrade: all worker threads have to synchronize their data frequently.

Method 2 has a problem to update old data. One map in game server run in dedicated worker thread. For example, role A in map 1 which compute by thread 1. role A transport to map 2 which compute by thread 2. This might cause thread 1's commit call after thread 2's commit call, so the older update which already executed in thread 1 commit after thread 2's commit.

Method 3 seems is a waste of system resource. Because in MMO there is no need to be transaction isolation, any change in a game session should be immediately seen by other sessions. In contrast with web app, so many connections has litte meaning. However the "Read Uncommitted" isolation level can let other session read data which has not committed yet.

==================================

I forget there is a thing called connection pool. Generally it is thread safe implemented so I do not need to care synchronization problem anymore. And the connection number is dynamic so I can leave problem of how many connection number to it. Only I do is get a connection from it. So, method 1 & 3 both practical.

# Answer
> 2 votes
I'm not sure how much of this is MMO dependent.

If you just have one connection and share it across threads, then maybe that would hold up your app when you lock access to that connection - but if you're making so many writes to an SQL database that this is a concern for your MMO, you're probably making too many writes anyway.

Whether a 'read uncommitted' approach will work for you depends a lot on how your application works. Often in an MMO you're never reading 'live' data anyway - you read once at the start to get it into memory and then it's write only until that data is unloaded from the simulation (eg. when a player logs out). But if you're doing explicit reads, and you have multiple possible writers to that data, you're in for data mismatches this way.

Personally, I would always stick with ensuring there is only ever one writer, and if I need to read live data during a session, I would try and use only one reader too, in the same thread and connection as the writer. This ensures consistency. In the parts of your application that do not need consistency, eg. read-only displays, they can use separate connections and threads.

# Answer
> 1 votes
Since you're talking about JDBC I'm assuming you're using an SQL database.

First of all, even though the JDBC specs theoretically state that all JDBC driver implementations should be thread safe, it doesn't really go into much detail, instead it even states that it's ok if said "thread safety" is achieved by serializing all concurrent queries which may lead to a major bog down in performance. If you chose to use JDBC, try using it via a wrapper library that creates a configurable JDBC connection pool. There's tons of those, check those from Apache for example.

As far as connecting to SQL databases using drivers created for other languages (like C++) I don't even think there's any spec guaranteeing thread safety at all, so again, unless you find a connection pool library you shouldn't use them.

What you can also do is try one of the NoSQL databases. They're made for dealing with large quantities of data and can prove in some cases to be faster than SQL databases. (Not always mind you, but in the context of a MMO this may be the case). I recommend Mongo DB. They have drivers for all major languages (Java and C++ included) and the driver natively supports connection pooling so you don't have to bother with that at all. There's a learning curve, especially for assimilating the Mongo DB equivalent of SQL transactions and such, but it could prove fitting to your need.

---
Tags: mmo, server
---