# Question
Title: How do history generation algorithms work?
I heard of the game Dwarf Fortress, but only now one of the people I follow on Youtube made a commentary on it... I was more than surprised when I noticed how Dwarf Fortress actually generates a history for the world!

Now, how do these algorithms work? What do they *usually* take as input, except the length of the simulation? How specific can they be?

And more importantly; can they be made in Javascript, or is Javascript too slow? (I guess this depends on the depth of the simulation, but take Dwarf Fortress as an example.)

# Answer
First off, there are *some* hints for history generation about Dwarf Fortress. Someone asked on the Bay12 forums a while back, and a transcript was shared and you can find where the discussion begins by searching for: "our topic today is world generation and history generation".

---

I don't know exactly how Dwarf Fortress does it, but I'll explain how I'm planning on implementing a very basic first draft in my game. I'm going to use a simple cellular automata. If you look through these Spore prototypes, like cell culture and biome.

These are examples of cellular automations and what they can produce. Essentially I'll create rules for different races. Some examples of rules would be:

* Their hostility towards other races
* Their climate preferences
* Their resource requirements
* Their birth rates and life spans
* Their desires (technology research, commerce, peaceful existence, world domination)
* Their capabilities (structure building, resource gathering, war making, etc.)
* And so on...

So, the most critical input for all this to work is a world to plop these races into. The terrain will determine their preferences and expansion. So once you've generated a world, pick random locations in the world where these races would suitably live and let them loose. Now the interesting stuff starts happening. Now that you have land and races with desires and capabilities, you can start building a history. These races gather resources, then structures are built:

* **Towns** in high resource, high livability areas.
* **Roads** connect the larger towns.
* **Bridges** across rivers.
* **Tunnels** through mountains.
* **Fortresses** near the front lines of expansion in response to battles.

Any structure can be raided/conquered by other races. The longer a structure (like a town or fortress) exists in history, the more defensible it is, the harder it is to take over. And the more desirable it is for races that want control. Battles are waged where races meet (at at least one is hostile). Battles are named after landmarks or nearby structures, or if the battle is significant or the landmarks are not named, the landmarks are named after the battle.

Roads, bridges and tunnels are expanded through commerce and resource transport. Each has a maximum throughput that can increase with resource expenditure. Building a stone fortress in the middle of grasslands? Those roads are going to get heavy use transporting the required stone. They'll become larger and get a name.

Natural disasters occur, affecting populations and the course of history. Earthquakes might reduce a town to ruins or collapse a tunnel. A flood might wash out a road or bridge.

---

It's not as in-depth as Dwarf Fortress, but it's a start. Now as you can imagine, (and as Johnathan Hobbs mentioned) the more these races expand, the more cells are being simulated. Not only are more cells being simulated, but the simulations are more complex as there are now structures to build/maintain, battles to wage, commerce to... commerce, and so on. This gets heavy for any language. Javascript might slow down sooner. However, you can always sacrifice complexity for improved speed.

It's all a simulation (albeit complex), you're just recording the important events along the way and calling it history.

I also just found a Bay12 forum post for people brainstorming how to make the Dwarf Fortress world generation faster. I haven't read through it, but it may provide some hints if you ever run into issues with your implementation being too slow.
> 27 votes

# Answer
Just as a side point, JavaScript isn't as slow as you might think.

The browser developers have spent *a lot* of time and energy in optimizing their JavaScript engines. The benchmark that I linked to shows that, out of the benchmarked tasks, in the median, JavaScript was **only 5 times slower than C**, which can't be said for some other interpreted languages. And the lower bound is even more impressive: **on par with C**.

Of course, language benchmarks don't really mean much - you could probably find counterexamples using a different benchmark. But the point is that JavaScript is **pretty fast**. No, it isn't C or C++, and it doesn't try to be. But it's good to not get stuck in the "interpreted language == slow" mindset, because for any task of nontrivial complexity, the performance is going to matter more on algorithm design and less on language choice.

I was actually going to write all this in a comment, but I ran out of space.
> 5 votes

# Answer
Yes, it can be build on javascript, check proyects like ASM.js, which get almost 2x slowest speed than C. If you take care of multiple cores (using webworkers) it can be even faster than the DF (in terms of resources), which is monocore right now.
> 1 votes

---
Tags: algorithm, javascript, random
---


# Question
Title: Sprites: Are there any tools to scale sprites individually without using Photoshop/GIMP?
I am using TexturePacker as tool to pack my 2D sprites, it is good but it doesn't provide the possibility to scale individual sprites to a specific scale.

I am wondering whether there is any good tool or command line to scale the files in the original folder without having to use TexturePacker.

What I am trying to do is to fix some scaling errors that the illustrator that produced the files did without having to re-scale/fix things using Photoshop that is more time expensive.

# Answer
You probably want the ImageMagick Convert Command-Line Tool:

It is very easy to manipulate images, for example to resize:

```
convert input.png -resize 200% output.png

```
> 4 votes

# Answer
Ok I don't know exactly what the problem is. First if the sprites are small (16x16 or 32x32), you want to use a proper editing tool anyway. At these resolutions scaling will almost always look very ugly.

Now to the solution: ImageMagick

ImageMagick is a command line tool and combined with a small shell/batch script you can convert, resize or whatever lots of images in a batch.

Here is the documentation on resize

Here is a forum thread discussing your program with some example batch scripts.
> 1 votes

---
Tags: game-design, textures, sprites, tools, scale
---


# Question
Title: Render just the pixel under mouse cursor in DirectX
I'm having difficulties rendering just a single pixel which is on the defined coords of viewport. I'm using D3DXMatrixPerspectiveOffCenter function, but the result is not what I expected.

Here is how I calculate the parameters for the function:

```
// pCamera is the actual camera used to render full screen picture

// what is the width and height of camera near plane in Camera Space
double dHeight = 2 * pCamera->m_dNear * (tan(pCamera->m_dFOVy/2.0));
double dWidth  = dHeight * pCamera->m_dRatioXY;

// what is the pixel size in Camera space
double dHeightReduced = (dHeight / pCamera->m_dViewportHeight) * CAMERA_1x1px_SIZE;
double dWidthReduced = (dWidth / pCamera->m_dViewportWidth) * CAMERA_1x1px_SIZE;

// mouse pixel position in Camera space
double dCamSpaceX = -0.5*dWidth  + double(uiMousePosX) / pCamera->m_dViewportWidth    * dWidth;
double dCamSpaceY = -0.5*dHeight + double(uiMousePosY) / pCamera->m_dViewportHeight   * dHeight;

// create matrix
D3DXMatrixPerspectiveOffCenterRH( &m_mProjection,
         (float)(dCamSpaceX),
         (float)(dCamSpaceX+dWidthReduced),
         (float)(dCamSpaceY),
         (float)(dCamSpaceY+dHeightReduced),
         (float)m_dNear,
         (float)m_dFar );

```

(I set CAMERA\_1x1px\_SIZE = 100 to see a part of the scene, but I see the scene distorted and it's definitely NOT just the cut-off of the original)

How do I need to calc the params to make it work?

Thanks.

# Answer
> 1 votes
I am more into openGL, but I think its simpler to use Scissor test to clip part of the Framebuffer/render target plus I don't see any benefits from modifying the projection matrix (unless its a requirement to modify the projection matrix).

Keep in mind that scissor test and projection+viewport work on a different part of the pipeline, scissor test for instance is a fragment operation while projection+viewport matrix is not. You can also use stencil test which can be used if the area you want to mask is not rectangular. Performance wise I don't think the two methods are equivalent but you need to measure and decide.

---
Tags: c++, directx
---


title: touchDragged how to move a sprite

text:
# Question
Title: touchDragged how to move a sprite
I have 1 simple sprite on the screen and I'd like to move it with the finger. (not necessarily by putting the finger on it, just anywhere on the screen)

I built the project using gdx-setup-ui.jar which created 3 projects (game, game-android, game-desktop)

Inside game/game.java I draw my sprite:

```
@Override
public void create() {
    //...
    batch = new SpriteBatch();
    sheetTexture = new Texture(Gdx.files.internal("animation.png"));
    //...
    InputProcessor ip = new MyInputProcessor();
    Gdx.input.setInputProcessor(ip);
}

```

Inside game/MyInputProcessor.java

```
public class MyInputProcessor implements InputProcessor {

    private float lastx;
    private float lasty;

    @Override
    public boolean touchDragged (int x, int y, int pointer) {
    if(x > lastx)
        game.xPosSprite += game.speed_sprite;
    else
        game.xPosSprite -= game.speed_sprite;
    if(y > lasty)
        game.yPosSprite -= game.speed_sprite;
    else
        game.yPosSprite += game.speed_sprite;
    lastx = x;
    lasty = y;
    return true;
    }
}

```

In game/game.java the variables are declared like this:

```
public static float xPosSprite;
public static float yPosSprite;
public static float speed_sprite = 0.2f;

```

This code makes the sprite move very approximately according to the finger movement but it's very sloppy, especially on the x axis.

The lack of very simple code example and the number of methods to get user input makes the exercise difficult.

# Answer
> 4 votes
In your touchDragged function you move the object a set distance. but you only seem to move the sprite based on its initial position, not the position of the touch.

Shouldn't you move the object towards the X and Y sent into touchDragged so that it would end up under your finger?

I would save the XY from touchDragged and send it to the object so that during the objects update it can move itself towards the XY that way you get smooth movement to your finger even if you keep your finger still.

# Answer
> 0 votes
Calculate the distance

```
distance = Math.sqrt(Math.pow(x - lastx,2) + Math.pow(y - lasty, 2));

```

Create two LigGDX vectors:

```
Vector2 start = new Vector2(lastx, lasty);
Vector2 end = new Vector2(x,y);

```

Calculate the delta

```
Vector2 delta = end.sub(start);
delta.nor(); // Normalize the vector or you get odd diagonal movement

Vector2 position = Vector2(x,y);
position += delta * distance;
x = position.x;
y = position.y;

```

---
Tags: libgdx
---


# Question
Title: Refering to an object from an array in Java
In my game, the whole thing is based off of grids. So the map is a dual dimensional array of 32 (32 x 32 grid map). Now what I want to be able to do is to grab a grid and be able to access it and alter it by using a method. To put it simply, I want a method such as *Grid grid = getGrid(10, 10);* and that would grab the grid at 10 x and 10 y, then when I do some basic edition to the object, it would change the object in the array as well. I don't know how to edit an object after it was changed by being grabbed by a method. I've heard about Java references and I don't know how to use it. I would like help being able to grab an object from an array, pass it on through a method, and be able to save it in another object and when that object is edited, the one in the array is edited. Thanks in advanced!

# Answer
From what I understand you want something like this. You can change the name and value from the Grid-object. It refers to the same object as in the array. So this works 'out of the box'. Is this what you mean?

```
public class Game
{
private static final int LENGTH = 32;
public Grid[][] grids = new Grid[LENGTH][LENGTH];

public Grid getGrid(final int row, final int column)
{
    if (row >= 0 && row < LENGTH && column >= 0 && column < LENGTH)
    {
        if (grids[row][column] == null)
        {
            grids[row][column] = new Grid();
        }

        return grids[row][column];
    }

    return null;
}

public static class Grid
{
    int value;
    String name;
}

```
> 3 votes

---
Tags: java, 2d, grid, objects
---


title: OpenGL/SDL2 window stopped rendering

text:
# Question
Title: OpenGL/SDL2 window stopped rendering
I have been working on a game engine for a couple of days now and I've had it rendering a colourful cube and playing sounds in OGG format, but, after refactoring my code-base to make things easier; it no longer displays the cube! (This happened when I put the shader program and methods into a seperate class)

What could be the problem?

**OpenGL/SDL2 context class:**

```
class RenderContext{
    public:
        RenderContext();
        ~RenderContext();

        void draw();

        int16_t good;

        ShaderProgram *program;
};

```

**BufferObject class**

```
class BufferObject{
    public:
        BufferObject(){};

        template<class Type>
        BufferObject(GLenum bufferTarget, vector<Type> &bufferData){
            target = bufferTarget;

            glGenBuffers(1, &buffer);
            glBindBuffer(bufferTarget, buffer);
            glBufferData(bufferTarget, bufferData.size(), bufferData.data(), GL_STATIC_DRAW);
            glBindBuffer(bufferTarget, 0);

            glGetBufferParameteriv(bufferTarget, GL_BUFFER_SIZE, &size);

            good = true;
        }

        void bind(){
            glBindBuffer(target, buffer);
        }

        void unbind(){
            glBindBuffer(target, 0);
        }

        void draw(GLenum drawMode){
            switch(target){
                case GL_ELEMENT_ARRAY_BUFFER:
                    glDrawElements(drawMode, size/sizeof(uint16_t), GL_UNSIGNED_SHORT, 0);
                    return;
                    break;

                case GL_ARRAY_BUFFER:
                    glDrawArrays(drawMode, 0, size/sizeof(float));
                    return;
                    break;

                default:
                    return;
            }
        }

        ~BufferObject(){
            glDeleteBuffers(1, &buffer);
        }

        bool good;

    private:
        uint32_t target;
        uint32_t buffer;
        int size;
};

```

**ShaderProgram class:**

```
class ShaderProgram{
    public:
        ShaderProgram(){
        }

        ShaderProgram(const char *vsPath, const char *fsPath){
            int32_t compileStat, linkStat;
            uint32_t vertexS = glCreateShader(GL_VERTEX_SHADER);
            uint32_t fragS = glCreateShader(GL_FRAGMENT_SHADER);

            string vsSource = LoadFile(vsPath);
            string fsSource = LoadFile(fsPath);
            const char *source = vsSource.c_str();
            glShaderSource(vertexS, 1, &source, NULL);
            source = fsSource.c_str();
            glShaderSource(fragS, 1, &source, NULL);

            glCompileShader(vertexS);
            glGetShaderiv(vertexS, GL_COMPILE_STATUS, &compileStat);
            if(compileStat == 0){
                char BUFFER[256];
                glGetShaderInfoLog(vertexS, sizeof(BUFFER), NULL, BUFFER);
                cerr << "-!- Error compiling vertex shader: " << BUFFER << endl;
                good = false;
                return;
            }

            glCompileShader(fragS);
            glGetShaderiv(fragS, GL_COMPILE_STATUS, &compileStat);
            if(compileStat == 0){
                char BUFFER[256];
                glGetShaderInfoLog(fragS, sizeof(BUFFER), NULL, BUFFER);
                cerr << "-!- Error compiling fragment shader: " << BUFFER << endl;
                good = false;
                return;
            }

            program = glCreateProgram();
            glAttachShader(program, vertexS);
            glAttachShader(program, fragS);

            glLinkProgram(program);
            glGetProgramiv(program, GL_LINK_STATUS, &linkStat);
            if(!linkStat){
                cerr << "-!- Error linking program." << endl;
                good = false;
                return;
            }

            good = true;
        }

        void getUniform(uint32_t &location, const char *uniformName){
            location = glGetUniformLocation(program, uniformName);
            assert(location != 0xFFFFFFFF);
        }

        void bind(){
            glUseProgram(program);
        }

        void unbind(){
            glUseProgram(0);
        }

        ~ShaderProgram(){
            glDeleteProgram(program);
            glUseProgram(0);
        }

        bool good;
        uint32_t program;
};

```

**Then the ShaderProgram is used like so in the drawing loop:**

```
**first init:**
VBO = new BufferObject(GL_ARRAY_BUFFER, coord);
IBO = new BufferObject(GL_ELEMENT_ARRAY_BUFFER, indicies);

**then:**
program->bind();

glUniformMatrix4fv(projMatrixLoc, 1, GL_FALSE, &projMatrix[0][0]);
glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, &viewMatrix[0][0]);
glUniformMatrix4fv(modelMatrixLoc, 1, GL_FALSE, &modelMatrix[0][0]);

glEnableVertexAttribArray(0);

VBO->bind();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
VBO->unbind();

IBO->bind();
IBO->draw(GL_TRIANGLES);
IBO->unbind();

glDisableVertexAttribArray(0);

program->unbind();

```

# Answer
> 0 votes
It's hard to tell from just that code. How do you use ShaderProgram during the actual drawing process? The only thing that I can think of from that code (assuming you aren't getting shader compile/link errors) is that maybe an instance of the ShaderProgram object is going out of scope and deleting the program prematurely.

EDIT:

```
 glBufferData(bufferTarget, bufferData.size(), bufferData.data(), GL_STATIC_DRAW);

```

bufferData.size() is the number of elements in the vector, not the size in bytes. You are probably not allocating enough space for all your data. Change it to:

```
glBufferData(bufferTarget, bufferData.size()*sizeof(Type), ...

```

Not sure how valid the `sizeof(Type)` thing is but you can always add an extra parameter or something if that doesn't work.

---
Tags: c++, opengl, sdl
---


# Question
Title: Are there shaders or at least shader like things in Swing?
Is there? Because I'm wondering if it supports GLSL, HLSL, or it's own shading language? I don't know much about Swing graphics. Does anyone know?

# Answer
> 2 votes
No there isn't.

What you can do is use OpenGL in Java with Java™ Binding for the OpenGL® (JOGL). JOGL can interoperate with Swing pretty well, so you can render 3D (or 2D) graphics with GLSL shaders in your Swing components.

---
Tags: 2d, graphics, shaders, swing
---


title: Flixel or Pygame for a small game?

text:
# Question
Title: Flixel or Pygame for a small game?
* I have some experience in Bash and Python, Lua.
* I've always wanted to try and make point & click quest games. Most
quest games I loved aesthetically and gameplay wise were made with
Flash.

So now I'm pulled apart between Flixel and Pygame since I naively think Pygame is less powerful in graphical aspect (judging from pygame site screenshots)

In short, what are cons and pros?

# Answer
The choice of development technology is something you have to decide based on your goals. If you have never written a game before, then the last thing you need to worry about is any sort of middleware limitations, what you need is experience under your belt. Either way, the technology choice should be made based on the skillset of the development team, the designed feature set and aesthetic requirements of the game, as well as the target platform. Either of these choices will get you started and familiar with the technology no problem. This kind of question is pretty open ended, and can turn into a sort of "religious debate", so you should avoid these sorts of questions.
> 2 votes

---
Tags: flash, actionscript-3, python, pygame, flixel
---


# Question
Title: How to stretch Movie Clip according to user's touch coordinates?
I have code like this:

```
touchX = e.stageX;
touchY = e.stageY;

```

I also have a player movieclip that I'm trying to make shoot lasers. So I got the MovieClip to appear and rotate according to the player's location and the user's touchX and touchY. How do I make the laser MovieClip stretch according to the distance between the player's coordinates and the touchX and touchY coordinates?

# Answer
Simply have the pivot point in the center of your laser clip. Calculate the distance between the player and the input.

```
var dx:Number = touchX - player.x; //Assuming SAME coordinate space
var dy:Number = touchY - player.y; // Else use localToGlobal
var halfdist:Number = Math.sqrt(dx*dx+dy*dy)/2;

```

Now scale your movieclip by distance.

```
   laser.width = halfdist;

```

Rotate your laser

```
var rot:Number = Math.atan2(dy,dx);
laser.rotation = rot * (180*Math.PI);

```

Place your Laser by rotation:

```
 laser.x = Math.cos(rot) * halfdist + player.x;
 laser.y = Math.sin(rot) * halfdist + player.y;

```
> 1 votes

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


title: Game Networking Update Packets

text:
# Question
Title: Game Networking Update Packets
So, I've been working on a project for a while which is basically just a little 2D game. The fun/hard part is that I've been trying to make it work as a multiplayer game. Right now, the game is just a bunch of entities, both players and projectiles shot from players. I have a question about how to keep the entities in sync on both the client and the server.

Is it better to send many many little "update packets" for each entity whenever it is updated? What I mean is, should I send a packet containing an entity's x and y position whenever it moves?

or

Is it better to send larger update packets that contain the updated info for many entities? What I mean here is should I send a bigger packet that has an array of smaller "update packets" that each have updated info on a specific entity?

I'm not sure which will cause less lag and be more scalable. What about if I had a hundred or more entities to update? Which method would work better in that case?

Thanks.

# Answer
The choice to make depends on what your multiplayer architecture is for the game. There are two major architectures for multiplayer games, the first being client based, in which each client is responsible for its own decision making and updating, and the server simply distributes these updates to other players. The other is an authoritative server, and prediction based clients. In this architecture, the clients are basically fancy renderers, that are responsible for simply sending "intentions" to the server. The server is responsible for managing the global game state, and telling the clients what the current state is. In this case, the prediction code is simply used to help mitigate the affects of latency, and smooth gameplay.

To answer your question about more smaller packets, or less larger packets, this would depend on your send/receive architecture, as well as whether or not your game can handle less frequent updates. Stalling an update until you have enough data to reach your desired packet size would lead to less frequent updates, and could make time sharing on the server less effective for asynchronous handling if the number of clients was large enough. This is something that is specific to the architecture of both client and server, but in general I would say "send em when you have em".
> 4 votes

---
Tags: networking, synchronization, packet
---


title: Game State and Configuration via Events

text:
# Question
Title: Game State and Configuration via Events
Often "singletons" are problematic for testing, so with my next game I'm trying my best to avoid them. But there is bunch of data (configuration or game state information) that different parts of my game require to function. So far I've used events (publish/subscribe) to pass around for example keyboard/touch actions.

Is it a bad idea to try to do the same with configuration/game state? So for example user changes some configuration parameter and instead of all those that need it doing something like `ConfigurationSingleton.getParam("someparam")` my event handler would call all those interested in param changes with `SomeSubscriber.paramChanged("someparam", "new value")`.

How do you usually make available this kind of "global state/configuration" data in games?

# Answer
> 4 votes
Whether you need a publish/subscribe pattern or not depends on *when* your data changes. If it does so during the lifetime of the interested objects, and if those objects need to know (and react) immediately, then publish/subscribe certainly is the right thing to do.

If you do not need immediate notification, just store a direct or indirect reference to the configuration/gamestate in the objects that need those information and let them ask for the values whenever they need them - `configuration.getParam("someparam")`. While at first sight this adds an additional dependency to the objects, it does not. The locally stored reference is not more of a dependency than the global singleton, and whether you have to "connect" the objects with a link to their "environment" (i.e. some object that directly or indirectly can get the information about gamestates, configuration etc.) during construction or with some publisher does not make a big difference either.

---
Tags: architecture, events, state, fsm
---


title: Deferred decals normal problem

text:
# Question
Title: Deferred decals normal problem
I've been working on a deferred decal system. So far I have finished the projection part, meaning I can click something in the scene and it will properly project a decal onto the surface of the object.

There are a couple other things I wish to add to this system: normal clipping and normal mapped decals. Normal clipping is when I discard fragments that are stretched across a sharp angle. Seen here. A way to solve this is to discard fragments that have a large difference between the normal in the G-Buffer and the decal's normal. This would require reading the G-buffer's normal texture.

In order to do decal normal mapping, I need to blend the decal's normal (from a normal map) with the G-buffer's normal. The requires writing to the G-buffer's normal texture.

I hope it's clear that in order to support these two features, I need to read and write to the normal texture in the same shader pass. Sadly, this is undefined behavior, so I'm wondering if there is some other way to implement these features.

# Answer
Which rendering system do you use? The following information should be valid for all rendering systems, but in DX11 or later OpenGL versions there might be a better solution using UAV's.

--

You will have to copy the normal buffer before each pass. As long as you know that the decals do not modify the same screen space fragments you do not have to update the copy.

You could also render all your decals into seperate buffers and only do one blend pass into your normal buffer using a single normal buffer copy. This would scale much better with the amount of decals you have.

As long as you do not write the normal buffer, eg only perform normal clipping, as you call it, you can just sample the original normal buffer but you may not bind it as a render target.

In DX9 I found that reading and writing to the same texture results in the expected output as long as you do only use nearest point filtering and never read a different pixel than the one you currently write to, BUT! as this is undefined behaviour there might be drivers and graphic cards that do not behave this way. DX10 will prevent you from doing this by unbinding textures currently bound as render targets.
> 1 votes

---
Tags: deferred-rendering, normal-mapping, frame-buffer, decal-system
---


title: Can I use Nyancat for my game?

text:
# Question
Title: Can I use Nyancat for my game?
I tried to find the information regarding the copyright/ownership of the Nyancat but couldn't find anything concrete.

1. Can I use Nyan as part of the name of my game?
2. Can I use the Nyancat graphics for my game?
3. Can I use the Nyancat sound for my game?

# Answer
If you're unsure, you need to research. One search in Google for "nyan cat copyrighted" brings up this question and answer, and this one and this one and so on. This is the process for any resource you find online, research it before using it.

You can also search the government's database for copyright in the US and find Nyancat there.

To answer you specifically about this meme. Yes it has copyright on everything about it. There's some question about whether the owners of the copyright would pursue you for using it, so that's up to you.
> 5 votes

---
Tags: legal, copyright
---


# Question
Title: Changing map 0,0 origin to top left while using D3DXMatrixOrthoLH
Thanks to Tetrad (for pointing out D3DXMatrixOrthoLH ) I have figured out how to set it up in DirectX9. However, the problem I am now facing is my 0,0 mouse position is now in the middle.

What I Want To Achieve: I want my 0,0 origin to be the top left of the window (not the middle). I also want to be able to zoom in.

Thanks for any help!

*edit* (this seems to add the 0,0 to the bottom left)

```
D3DXMATRIX m_d3dts_projection;
D3DXMatrixOrthoOffCenterLH ( &m_d3dts_projection , 0.0f , console_editor.window_w , 0.0f , console_editor.window_h , 1.0f , 10.0f );
console_editor.directx_device->SetTransform ( D3DTS_PROJECTION , &m_d3dts_projection );

```

---

*Old Post -- Dont Answer*

I have been developing a map editor in C++ DX9 for the past couple of months, and have ran into a particular development problem.

How my map editor works: I split the screen into 16x16 cell blocks each with their own struct for rendering. When you click on the window, it will find the cell block that you clicked based on the win32 whereabouts of the mouse cursor. It then will do its magic. This seems to work well with a FOV of D3DXToRadian(float 90).

However!

I also want my map editor to be able to zoom in and to zoom out, so when I increase or decrease the FOV, the mouse cursor and the cell block code are all correct, but wrong. Example:

Normal 90 FOV - *Looks Good*

Zoomed In - *Opps*

Question: How can I add functionality of zooming in and out, but still have the mouse position be relevant to the render? I assume I have to recode how everything works, and I am okay with doing that...

# Answer
Take the position of the mouse and divide it by the width of the tiles (relative to the zoom level) will give you the tile it is hovering over.

For example, if your base tiles are 25 pixels wide, and you zoom in to 2x, your tiles will be 50 pixels wide. If your mouse is at 255x and 325y, divide by 50 each and you get 5x 6y (using integer division).

You may have to do some extra math if the center of your screen is 0,0 but the premise is the same.
> 0 votes

---
Tags: c++, directx9, picking
---


# Question
Title: Is it worth having AI opponents step in for disconnected players in an online multiplayer card game
I have an online multiplayer card game resembling spades/bridge and I want to implement a system that autoplays when a client disconnects. Right now, there is a client and server. In the new system, there will be an autoplay server sitting between the client and the actual game server.

The client connects to the autoplay server which in turn connects to the game server. If the client disconnects during a match, the autoplay server is activated.

Both servers will reside on the same machine so communication cost should be minimal. Processing cost should be minimal as well as the autoplay will be programmed with limited skills only to keep the match going till the end. The idea is not to break the game flow once a player disconnects. But, I don't see autoplay systems in popular commercial games such as Zynga poker (maybe in this case because a disconnection can be easily be considered as a Check or Fold.) Well, is it really worth it to have an extra layer for autoplay?

Edit: Are there other drawbacks for having an extra layer for autoplay?

# Answer
> 4 votes
When you play a game online, you usually play it online because you want to play against a human opponent. So it doesn't make much sense to play when your opponent is computer-controlled.

But when you have a multiplayer game which has more than two players and which becomes unplayable when one player drops out of the game (like Hearts), it would certainly be preferred by the remaining players when they could end the game with the remaining human players while the missing player is taken over by an AI. The more players the game requires the more likely will it be that one player will drop out of the game.

When the game system allows players to leave the game suddenly (like in a game with a last-player-standing win condition), leaving the game should be treated like another lose condition.

# Answer
> 12 votes
If you want the feature, implement it.
If you don't want the feature don't implement it.

If you're unsure if the player wants it, implement it and notify the user if the other player disconnects and give them an option to continue with the AI player.

# Answer
> 0 votes
Whether to replace a player or not is of course a design choice. I think the question you have to ask yourself is: do you want to count a player quitting as a win for the other player or not?

* If not, you'd probably end up forfeiting the match results, to which replacing the player with an AI might be a good alternative.
* If you do want to count it as a win, there is no need to replace the player. But in the case of a connection problem, you'd end up with branding the disconnected player as a quitter and therefore count it as a loss. Having them both play against the AI in this scenario would allow both of them to get a fair chance at winning the game.

So in the end it all comes down to your preference and what you think is fair to the players involved in the match.

---
Tags: game-design, multiplayer, online, card-game, automation
---


title: spaceship collision and dying

text:
# Question
Title: spaceship collision and dying
I have a spaceship on the left side on the screen that can move up and down. Enemy spaceships move from the right side of the screen to the left. The goal is to shoot as many spaceships as you can.

Because the player ship can move up and down, I have set up collisions so that they can't go above or below the window bounds, this is handled in the following code.

```
public void playerWCollision()
{
    if(y < 0)
    {
        y = 0;
    }
    else if(y+height > Main.WINDOW_HEIGHT)
    {
        y = Main.WINDOW_HEIGHT - height;
    }
}

```

Now if the player spaceship crashes into an enemy spaceship, I want my player ship to fall down, like so.

```
public void hit()
{
    // these are player positions. so if player crashes into
    // an enemy spaceship then add to x, y position
    // so player spaceship will go forward and down, forward and down, etc..
    x += dx;
    y += dx;
}

```

But the problem I have is that the player ship will stop at the bottom due to this collision detection check `else if(y + height > Main.WINDOW_HEIGHT)`.

So if the player gets hit there is no way it will go below the screen.

I want the player to stay within the bounds of the window **unless he is hit**, in which case he should be able to go below the screen.

# Answer
> 0 votes
Add a boolean value like shipIsAlive on your ship class and set it to false when the ship gets hit and then change your else if to:

`else if(y+height > Main.WINDOW_HEIGHT && shipIsAlive)`

---
Tags: nifty-gui
---


# Question
Title: gluLookAt strange behavior implementing camera
I'm having a super tough time trying to implement what I thought would be a very straightforward problem. I'm trying to demonstrate a free camera that can move forward/back, strafe left/right, fly up/down, and look up/down/left/right. The mouse will control the look and the keyboard (WSADRF) will control the movement.

The movement appears to work just fine, and the look behavior appears to be correct from my camera starting point, but as I deviate away from the camera start point, the mouse movement goes into a crazy non-linear type thing where stuff is rotating all over and going nuts. Here's my basic camera setup:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(70.0, static_cast<GLdouble>(w) / h, 1.0, 10000.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glm::vec3 lookat = camera_.pos - camera_.Back();
glm::vec3 up = camera_.Up();
gluLookAt(
  camera_.pos.x, camera_.pos.y, camera_.pos.z,
  lookat.x, lookat.y, lookat.z,
  up.x, up.y, up.z
  );

```

My camera starts off at (0, 0, 25) and is looking at (0,0,0) where my model is. The look behaviour is fine there. As I start to approach a point like (5,0,0), the look behaviour gets completely boned. Also at that point, it feels like the camera "up" vector gets screwed up. Trying to fly up/down makes the camera kind of move in/out. Here's the code I'm using to update the camera:

```
static float p = 0.f;
static float y = 0.f;
static float r = 0.f;
p -= 0.5f * delta_y * dtime;
y -= 0.5f * delta_x * dtime;
camera_.ori = glm::quat(glm::vec3(p, y, r));

```

This problem is super frustrating, because it feels like I'm so close to having everything working, but something is evading me! For reference, here's how I calculate the Up, Right, and Back vectors from the camera orientation, which I got from this site:

```
glm::vec3 Actor::Right() const
{
  return glm::normalize(glm::vec3(1-2*(ori.y*ori.y+ori.z*ori.z), 2*(ori.x*ori.y+ori.w*ori.z), 2*(ori.x*ori.z-ori.w*ori.y)));
}

glm::vec3 Actor::Up() const
{
  return glm::normalize(glm::vec3(2*(ori.x*ori.y-ori.w*ori.z), 1-2*(ori.x*ori.x+ori.z*ori.z), 2*(ori.y*ori.z+ori.w*ori.x)));
}

glm::vec3 Actor::Back() const
{
  return glm::normalize(glm::vec3(2*(ori.x*ori.z+ori.w*ori.y), 2*(ori.y*ori.x-ori.w*ori.x), 1-2*(ori.x*ori.x+ori.y*ori.y)));
}

```

# Answer
Thanks to @DaleyPaley I was able to figure this out. The problem lay in my code to figure out the camera vectors Right, Up, and Back. I was just using some code that I found online, and once I started showing the actual camera placement and vectors from the perspective of a hardcoded camera, I could tell that the vectors being produced by Right, Up, and Back were definitely not orthogonal to each other. They were getting really wonky and flipping over each other.

I switched to this code, and everything resolved itself immediately:

```
glm::vec3 Actor::Right() const { return glm::mat3_cast(ori)[0]; }
glm::vec3 Actor::Up()    const { return glm::mat3_cast(ori)[1]; }
glm::vec3 Actor::Back()  const { return glm::mat3_cast(ori)[2]; }

```
> 2 votes

---
Tags: opengl, camera, glm, glfw
---


# Question
Title: How to fix thi gameover scene audio transition?
I created a gameover scene in a crafty.js project but it does not run.

```
  Crafty.scene('gameover', function() {
    Crafty.background("#ccc");
    Crafty.audio.stop("bg");
  });

 var gameOver = function () {
    Crafty.scene('gameOver');
  };

```

The background music ("bg") doesn't stop playing once the game ends. How do I fix this?

# Answer
> 1 votes
I was able to get the transition to work by removing this code:

```
  function () {
    Crafty.unbind('EnterFrame', appleEvent);
  }

```

It is the **uninit** callback for the main game scene. I wonder why it prevented the transition.

# Answer
> 2 votes
As Byte56 said

> You sure the background music is referenced with "bg"?

And, Are you sure the scene is really changing?

```
Crafty.scene('gameOver');
Crafty.scene('gameover',.. );

```

you have an 'O' instead of 'o' when you call the scene, unless Crafty is case-insensitive when naming entities i don't what is the problem.

---
Tags: javascript, audio, crafty
---


title: Space Shooter "level" generation

text:
# Question
Title: Space Shooter "level" generation
I'm currently working on a 2.5D space shooter and there will be a survival mode in the game. I'd like a few suggestions on how to tackle the enemy generation problem. This is not procedural generation at all, it's more like a sequence generation. The characteristics the system needs to have are:

1. Increasing difficulty based on time
2. Ability to use enemy patterns as input and not only single enemies
3. It has to be beatable, it's quite easy to make a wall of thousand of enemies :)

I'm not looking for a fully-optimized, ready to use algorithm, just some suggestions or links to papers or articles. I have found many resources on procedural generation, but nothing that can be applied to this game genre. The game is 2.5D but the level will be generated as it was 2D, in addition it's not omnidirectional, it will scroll in only one way (this should make the task easier).

# Answer
What I have done in the past is to have a single value to represent difficulty of each wave:

```
float wave_difficulty = START_WAVE_DIFFICULTY;

```

then every wave:

```
generateWave(wave_difficulty);
wave_difficulty += DELTA_WAVE_DIFFICULTY;

```

The hard part is taking the value and building a wave based on it in a fair and balanced way. Here are some ideas.

* number of enemies
* frequency at which enemies come
* total health of enemies
* spread of enemies
* inverse probability of getting a powerup
* intelligence of enemies
* manuverability of enemies
* targeting skills of enemies(use dead reckoning with randomness)
* interval between waves

Everything that is not affected by the difficulty value should be constant and consistent, so that there is just a single variable to tweak for difficulty. This is to make level design and tweaking as simple as possible, which is incredibly important for balancing. It's a bit of a vague answer, but I hope it gives you some ideas.
> 6 votes

---
Tags: procedural-generation, level-design
---


title: XNA texture GetData exception

text:
# Question
Title: XNA texture GetData exception
When using this code:

```
public static Texture2D MakeTexRed(Texture2D tex)
    {
        Texture2D drawTex = new Texture2D(Game1.graphics.GraphicsDevice, tex.Width, tex.Height);
        Color[] data = new Color[tex.Width * tex.Height];
        tex.GetData<Color>(data);
        for (int i = 0; i < data.Length; i++)
        {
            data[i].R = (byte)((data[i].R + 255) / 2);
            data[i].G /= 2;
            data[i].B /= 2;
        }
        drawTex.SetData(data);

        return drawTex;
    }

```

I'm getting this exception:

```
The type you are using for T in this method is an invalid size for this resource.

```

The size of the texture I'm using is 64x64 pixel.

When using this line:

```
Texture2D drawTex = new Texture2D(Game1.graphics.GraphicsDevice, tex.Width, tex.Height, false, SurfaceFormat.Color);

```

it still doesn't work.

# Answer
So here are the possible format types.

you are going to have to check tex.Format and use the correct datastructure for tex's SurfaceFormat.

For example.

```
var b = new Bgr565[result.Width * result.Height];
tex.SetData(b);

```

The below SurfaceFormat have a corresponding value types that can be used.

```
Color
Bgr565
Bgra5551
Bgra4444
NormalizedByte2
NormalizedByte4
Rgba1010102
Rg32
Rgba64
Alpha8
Single
Vector2
Vector4
HalfSingle
HalfVector2
HalfVector4

```

For the Dxt formats means that the texture is compressed you are going to need to know the size after the texture is compressed get the data and then decompress it.

After some searching I found a DXT1 and DXT5 decompression library. Unfortunately I can't find anything managed so unsafe C# code is probably the best bet for converting it over. According to Wikipedia 16 pixels are stored in 8 bytes which makes have a byte per pixel so theoretically `byte[] data = new byte[(Width * Height) / 2]` should work for extracting the data.

```
Dxt1
Dxt3
Dxt5

```

This one is a special case just use HalfVector4 for the type and you are fine.

```
HdrBlendable

```
> 1 votes

# Answer
Have your tried not specifying the T when calling GetData() ?

```
tex.GetData<Color>(data);

```

To :

```
tex.GetData(data);

```

The error you posted refers to the Color you pass as T.
> 0 votes

---
Tags: xna-4.0, textures, exceptions
---


# Question
Title: Handle Input Processor in Device Back Button and Button as Actor
How to handle a event for both key as well as actor added in the screen? My problem is that at a time only one input processor is available either for button or device back button. How can I set input processor for both back button of device and button which act as actor on the screen.

I implemented following code for button input processor Gdx.input.setInputProcessor(stage); button was added in the stage so I implement input processor for the stage.

For device back button Gdx.input.setInputProcessor(this); Register actor as input processor

In keyDown event I write if (keycode == Keys.ESCAPE || keycode == Keys.BACK) LevelLoadScreen.flagResume = true;

Other solution also acceptable if it handle both the action listener

# Answer
Not sure if I understand your question clearly. I'll assume the following:

* You got a Stage set as InputProcessor
* You got another special button as InputProcessor which you refer to as "device back button"
* You want them both to process input but it seems you can only set 1 InputProcessor at a time

If above is the case, then one way is to use an InputMultiplexer which is apart of libgdx.

First, create an InputMultiplexer.

Then, set it as the InputProccessor.

Add your two InputProcessors to the InputMultiplexer: back button, then stage in this order.

* If you return **false** in back button event handlers, then the **event gets passed to** stage as well.
* If you return **true** in back button event handlers, then **events do not get raised** in stage.
> 4 votes

# Answer
You have to overwrite the `keyDown` function in Stage.

See this example code

```
mStage = new Stage() {
        @Override
        public boolean keyDown(int keyCode) {
            if (keyCode == Keys.BACK) {
                Gdx.app.exit();
            }
            return super.keyDown(keyCode);
        }
    };
    Gdx.input.setInputProcessor(mStage);
    Gdx.input.setCatchBackKey(true);

```
> 3 votes

---
Tags: libgdx
---


# Question
Title: Texture not carrying over to game correctly?
I have created my map for my game using 3DS Max. I have then applied textures to the map within 3DS Max, where the textures all show correctly. I export the map as a .fbx file to use within an XNA project.

However as you can see from the below screenshot, the textures are not displayed correctly in XNA.

**Does anyone know why this is happening?**

I am using the Autodesk FBX content importer and the Model - XNA Framework Content Processor.

As you can see my model which was created in the same way has the textures displayed correctly, it is only doing it to my map.

# Answer
> 4 votes
Thanks to dadoo Games my problem is solved. He was correct I needed to change my sampler state to wrap.

I added this to my draw function to get it working:

```
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

```

---
Tags: xna, xna-4.0, textures, models, 3dsmax
---


title: Input skeleton not found

text:
# Question
Title: Input skeleton not found
I have a 3D-Model, made in Maya and I am trying to parse that through the latest XNA with the `SkinnedModelProcessor` (However, this issue remains without that processor).

In Maya, the skin is already attached to the skeleton, so why am I getting this error?

> Input skeleton not found

Is there anything special I should think of when exporting that .fbx file from Maya?

# Answer
After hours and hours of debugging we found out that the problem wasn't the skinning or connecting or whatever.

It was the rigging-system. My designer used a tool called *Advanced Skeleton*, that tool should work perfectly.

However, it doesn't really apply to the XNA-Standards and therefore its rigging-algorithm caused errors in XNA.

We ended up using the standard rigging-tool from Maya. Since then, everything is working.
> 0 votes

---
Tags: xna, fbx, windows-phone-8
---


title: How a 3D game map is stored and handled

text:
# Question
Title: How a 3D game map is stored and handled
I'm a programmer but have not yet developed any games.

I have played various 3D games and always wondered how the Map of the field is stored and rendered.

I know some acceleration card is a necessary hardware, but how exactly the view is changed without even a single flicker on the screen.

Do you have any online material to help me understand this.

Thanks

# Answer
> 9 votes
Generally, the world is map up of lots of triangles, and the map is a list of these triangles and the location in the world of each vertex. The process to draw them is:

* Setup the position of the 'camera' - if you were stood in the world, this is where you'd be in world position
* Transform the triangle vertices into 'camera space'
* Transform the triangles from 'camera space' into 'screen space' - this is where the perpective effect happens (distant things are smaller). The triangles become 2D at this point.
* Draw the 2D triangle onto a hidden screen.
* When all the triangles have been drawn, show the screen to the player.

The last step is usually tied to the monitor's frame rate, so that the process of showing the hidden screen is done during the v-blank interval - a concept derived from cathode ray tube monitors which allowed the cathode beam to move from bottom right to top left, this required rapidly, but not instaneously, changing voltages on the deflection coils at the back of the ray tube.

This is a really simple method. To get high performance you need to add things like hidden surface removal, occulsion, visible set determination, and so on. There's lots of algorithms involved in deciding what to draw.

Also, I said the world is made up of triangles, but it might not be stored on disk this way. Often, the triangles that are drawn to screen are defined at run time from higher order primitives, such as height maps, splines, tessalation, geometric primitives (e.g. a sphere, box, etc) and so on.

Dedicated hardware is not necessary - many early 3D games did it all in software (even on 8-bit CPUs with no FPUs). It just makes it quicker and easier to do.

Such a simple question. No easy answer.

# Answer
> 0 votes
The view is changed without any flicker on the screen because of double buffering, Process all the data on the back buffer, then when it is done being processed, you swap it on the front buffer.

---
Tags: 3d, maps
---


# Question
Title: How can I display an image for a predetermined amount of time?
I want to display an image, then return to the previous after one second when a certain key is pressed. I'm using Slick2d and Java. How can I accomplish this?

# Answer
> 2 votes
When you display the image you just need to keep track of some "elapsed time" variable and update it by the delta time each frame. When that elapsed time variable hits whatever time limit you want, then you switch the image back.

# Answer
> 0 votes
Use a timer for this, and make sure to connect its timeOut -- or similar -- method to the method responsible for switching between images.

Inside the key press event handler you check whether the timer is already running, if not, start it and it's done.

---
Tags: java, slick
---


# Question
Title: What are some good examples of exuberant in-game instructions for telling the player to repeatedly smash a button?
What are some good examples of exuberant in-game instructions for telling the player to repeatedly and quickly press a button or perform an action? I'm especially interested in examples in retro games (e.g., from the NES, SNES, and 1980-90s arcade eras), and I would love to see examples with text, graphics, or both.

To illustrate, here are a few examples of the type of instructions that I'm thinking of:

* Smash the A button to lift something heavy!
* Toggle the joystick back and forth to break free!
* Quickly press the button to build power in a meter!

I'm working on a 2D iOS game with retro-style pixel art, and there's a point where I want the player to quickly tap on a sprite to complete an action. I have a serviceable starting point -- the word "TAP" flashing with an arrow repeatedly moving downward beneath it:

But it still doesn't feel quite right.

I would love to see some actual examples from the golden days of 2D gaming to use as reference material. I know examples abound, but I'm just struggling to think of any concrete ones at the moment.

Can you think of any examples of this type of thing in old games?

# Answer
Sometimes, 2D can take a lesson from 3D. A graphical indicator that is reinforced by the game itself works better than the word "TAP" and an arrow. Here's a couple recent games that stand out in my mind for having good indicators of tapping.

**Madworld (Wii)**: Okay, it's not actually tapping but one category of attacks could be repeated a certain number of times by shaking the controller. To indicate this, the designers put a picture of shaking controller on screen, complete with movement, and highlighted it with "action spikes" (for lack of a proper term, think classic "BAM!" bubbles from old comic books).

**Batman: Arkham Asylum (360)**: Many actions like removing a vent grate used tapping. When Batman was ready to perform the action, the camera would change to focus on the action and an animated "A" button would show up as a prompt. If the player started tapping the button then stopped before the action was complete, Batman would either stop or, in the case of pulling down a wall, would slowly lose progress on the action. Either way, the game provided direct feedback in response to tapping.

As mentioned in other answers, older games didn't necessarily have any indicators for this sort of gesture. Just because your game is 2D doesn't mean you can't draw from the entire history of gaming to find a solution.
> 1 votes

# Answer
Here's an example I came across with a bit of Googling that gets the point across quite well, in my opinion. Either this, or just have the finger or a bouncing arrow and an outward-expanding target.
> 3 votes

# Answer
Kind of random example, but Power Rangers for SNES had a flashing GO with an arrow whenever you cleared an area to direct you to the next area.

I'd suggest community wiki for this question, since it's not going to have a definitive right answer
> 0 votes

# Answer
I think that in "golden days" where were little to none in-game instructions. The already mentioned flashing "GO" is one of those rare examples. So, I'm not really sure if there is some established patterns for such animations back then.

P.S. I think your current implementation is pretty good. You can add zoom animation on TAP, or make TAP move with the arrow, it's a matter of personal taste I think.
> 0 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: What beginner level game should I practice developing that has all the basics of game development?
I am a fresh graduate of Computer Science and am very nervoud for my skills test next week. So I have only about 4 days left till the exam and I really want that job which is game development.

They have a hands on programming exam using Visual C++.

So i would like to ask if there are any simple games that would fit the span of time I have to practice developing it that also has all the basics a game developer should know?

Any advice would be really appreciated!

# Answer
> 2 votes
**Tetris**

And make it as full-featured as possible. It will take you through quite a few basic concepts that are important in game development, but most importantly, it is based on a recipe that can be summarized as:

1. Give the player a single, easy to grasp, yet challenging to achieve goal (reaching a given score);
2. Let the player know what he must do in order to achieve it, and make sure it's not an overwhelming task (make straight lines of blocks);
3. Try to make the task require bits of judgment and thinking from the player (the player needs to be careful where those blocks go!). This will also increase the player's satisfaction with the game, as it will make him or her feel clever;
4. Let the player know that he's doing the right thing whenever he performs the task successfully (score++!);
5. Show the player a congrats screen on a successful playthrough (always a nice thing to do!).

It will require you to:

* keep track of the whole state of the game (Running/Paused for two basic states) and game grid;
* continuously check for user input; any kind of input from the user will change either the game state, or the grid's state;
* keep a close focus on *victory conditions* and whether they've been achieved yet;
* implement a scoring system for the player to feel the progression;
* make the game harder as the player progresses, by increasing the speed at which blocks fall down;

In short, search for game concepts that allow the player to reach a well defined goal by performing some simple tasks (preferably just a single task) that also progressively increase in difficulty.

Leaving Tetris aside, **Pac-Man** is also a great source of inspiration for a beginner's project. It also requires some very basic *pathfinding*, which Tetris does not. But the essence is still there: a simple goal (eat those ghosts), with increasing difficulty (ghosts get faster).

# Answer
> 0 votes
I would say Breakout, Asteroids, Pong, or Tetris are all very good beginner games with concepts that aren't very hard to emulate. If you're a bit more advanced, and you want more of a design challenge, try something like Tower Defense or a simple top-down racing game.

---
Tags: c++, game-design, game-mechanics
---


title: Which should I learn: DirectX or XNA?

text:
# Question
Title: Which should I learn: DirectX or XNA?
I've worked with the Microsoft Foundation Classes(MFC) and now I want to enter the world of game development.But should I start with directX or XNA? I'm hesitant towards DirectX because I feel it would be quite a laborious thing to work with. I'd really appreciate some expert advice on this, Thankyou.

# Answer
Do you want to learn high level or lower level? Do you want to make games or do you want to learn new tech? *PS: XNA is dead but it lives in updates through MonoGame; check them out. It's well worth your time.*

**XNA and MonoGame are a framework.** They allow you to devleop your game with structured utilities and pre-defined classes. This allows you to begin just writing game logic and forget about all the laborour stuff like handling your window, setting up a game loop, timing, effective sprite batch rendering, rendering basic models, setting up an effect framework and the like. Many other quick and easy modular libraries are available as well. You can't say the same for DirectX. **If you have to choose between two, and you just want to make a GAME; pick this option if you are comfortable with C# or willing to learn. You'll develop faster without having to worry about everything "under the hood". MonoGame also gives cross compatibility fairly easily which is a bonus.**

**DirectX is an API to interface with GPUs and Windows.** We use it to make games but it's a lot lower level than that; it provides no easy rendering pipeline, resource manager, or matrix transformation utilities. No game loop. If you want to learn it all from the ground up ... this or OpenGL is pretty much where it's at. You can't get much lower than this without stepping into some pretty insane territory. If you're already adept at C++ this might be an option - but if that is the case C# shouldn't be hard to pick up. **DirectX is for those who want to roll their own stuff.**

**The other case where one might want to use DirectX is if they need extremely, highly optimized rendering techniques they need to implement themselves or they need to write a VERY intensive game that C# and XNA fail to complete. If you have to ask this question, though it's probably not the case.**
> 5 votes

---
Tags: xna, directx
---


# Question
Title: Clipping a windows draw area - Direct x 9 and c++ - 2D using D3D
**DirectX 9, C++... Let me set the scene:**

* I have a 16:9 image.
* I have a 16:10 screen.
* I want the 16:9 image to be drawn so that it is vertically centred within my 16:10 screen.
* My 16:9 image is 1920 x 1080.
* My screen is 1920 x 1200.

*Easy:*

```
float topOffset = ( 1200 - 1080 / 2 )

```

But what if my screen was 1400 x 900

I have to resize the image and get its new height, then do the above again:

```
float newHeightForScaledImage = ( 1080 * 1400 ) / 1920

```

Okay so now I have a topOffset for both widescreen cases. I draw all of my images and interactive objects at their ( y position + the topOffset ).

**New problem** is that the menu is also needed to take into consideration, so I use that systemmetricssomething call which returns 20 which I then subtract from the topOffset... Okay my drawing is vertically centred... perfect!

Question is, regardless of my entire game now being vertically centred (in the most crazy long hauled way possibly known to man), I can still draw outside of the game area into the black zone that now exists.

I know I am approaching this wrong, but I am too new to this to know any better.

**How do you guys vertically centre your games if they are a different ratio to the artwork you have created for the backgrounds etc?**

# Answer
We use letterboxing. This allows us to keep a consistent ratio; you can implement it similarly here. The sample is done in XNA but the general gist is pretty much the same. I'll outline the steps here, anyway for consistency sake since this link has already gone dead once.

1. Create your backbuffer at the display adapter’s current resolution.
2. When drawing, first set the viewport to the full backbuffer and clear black.
3. Compute the largest viewport of the desired aspect ratio that fits on screen and set that to the device.
4. Clear the screen again (it will only clear the viewport area) and draw your game.

All credit to Mr. Nick Gravelyn.
> 1 votes

# Answer
Make your render target 19x10 and draw everything based on that. Then you can copy it to the window surface while scaling it down to fit.
> 1 votes

---
Tags: c++, directx9, aspect-ratio
---


title: XNA texture overlay with offset

text:
# Question
Title: XNA texture overlay with offset
Is it possible to overlay one texture over another and make them into a new texture? It should also work with an offset.

Here's an example:

This texture

and this texture

should make this texture

It should be possible to change the position of one texture.

# Answer
> 0 votes
I see a couple ways to do this when I first think of it. Here's how I would take my first stab at it.

1. Create a RenderTarget that you can draw to. (Make it the size of the "base texture")
2. Draw your base texture on the RenderTarget so it fills it up.
3. Draw onto the RenderTarget again if needed; you can use **SourceRectangle** and **DestinationRectangle** on the SpriteBatch overload to accomplish this.
4. You can then save or use this texture inside your game.

Seems simple enough.

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


# Question
Title: How to properly limit movement based on collision
I have a confusing problem on my hands. I've managed to get tile-based collision working, and I'm using the following code in my update loop to restrict my character's movement.

```
        for (Block b : grid.getSelectedRoom().map.blocks) {
            if (this.rect.intersects(b.rect)) {
                if (b.type.equals("wall")) {
                    if (this.direction.equals("north")) {
                        this.y = this.x + 1;
                    }
                    if (this.direction.equals("south")) {
                        this.y -= 1 * delta;
                    }
                    if (this.direction.equals("east")) {
                        this.x -= 1 * delta;
                    }
                    if (this.direction.equals("west")) {
                        this.x += 1 * delta;
                    }
                }
            }
        }

```

My problem is that if multiple keys are pressed at a corner, the character gets all wonky and clips through walls. I've considered checking to see if the rectangle *will* collide on key press before movement, but I'm not sure how I could do that since I have to deal with looping through every tile with collision. How should I go about limiting my character's movement?

# Answer
> 3 votes
Check horizontal and vertical collision separately. Also you shouldn't need to loop through every tile for collision, you should only have to check the tiles the character is entering.

As a personal preference, I like to check for collision before applying movement. It seems to save a lot of headache.

---
Tags: java, slick
---


# Question
Title: What 3D engine supports real-time editable 3D terrain loaded in from a server?
I'm currently having a problem choosing an engine for a game project I have since a few years. What I'd need is to be able to load a terrain from a remote server (which I can take care of) and display it dynamically, if possible with paging. The terrains should also be able to be edited in realtime (locally or remotely and transmitted by the server).

I can take care of the network part but need a 3d engine flexible enough to support the terrain features detailed above. Would you know a 3D engine which could support this ? I'd prefer programming with .NET but C++ is also fine.

# Answer
> 0 votes
Like @thedaian said in a comment, XNA and Unity3D are the two big players when it comes to .NET game development.

They each have different key features, but really it comes down to two simple differences. **Unity is art-centered**, meaning the scene editor and Asset Store are the primary features that really make it easy to use. The fact that uses C# and javascript for scripting is very nice, but in the end they are scripts and not programs, so a different approach to development .

**XNA on the other hand is more code-center.** While you have to do more work to get a game up and running, this will be more natural and extendable to an experienced developer.

---

I have used both Unity and XNA in multiple projects, and they are both great for game development. The question you need to ask is whether you want take the time to modify Unity to handle terrain deformation, or to take the time to build your own implementation in XNA. It has been done in Unity, but I feel like it might be less of a headache to whip it up in XNA.

---
Tags: 3d, terrain
---


# Question
Title: Machine Learning in AI for benefit analysis round to round in a rummy like game
For fun I am building the game 5 crowns. Well I've gotten to the point where I am implementing the rules for the computer players. I've found that my decision tree has so many nodes on it that I wonder if it would be easier to implement an algorithm that would take a small subset of the nodes and infer the rest from that basic subset.

Basically I would like to input a subset of rules.
So the following are the rules for each round

* Round number determines which card is wild
    + Minimum card value is 3 so in round one 3's are wild.
* You may only have a specific number of cards in your hand.
    + The amount of cards in your hand is equal to the value of the card that's wild.
* You can draw from the discard pile or the deck.
* Your goal is to be the first one to lay down their hand by building sets or runs.
    + A set or run must have at least 3 cards in it.
    + Runs can only have cards of the same suite.
* After a player lays down their hand each remaining player has one more turn to lay down.
* Any cards left in your hand when the round ends are totaled and added to your score.
* Higher cards are worth more points.

So if my hand was the following, and it was the first round (I.E. 3's are wild):

```
hand = [{value: 3, suite: hearts},  //3 of hearts
        {value: king, suite: clubs}, //king of clubs
        {value: 7, suite: spades}]  // 7 of spades

```

And the card on top of the discard pile is a 5 of diamonds (`{value: 5, suite: diamonds}`)

I would engage in the following thought process:

* The 5 has a lower score then the 12 or 7, which would be good if I can't lay down when the round ends.
* However, unless someone before me has already laid down, I will have at least one more turn; at which point, if I need to, I can ditch the 12.
    + There is a high probability that if the player right before me has a 12, they will dump it. Allowing me to pick it up next turn and lay down.
* This may not be the first turn and I may of seen the player after me take a 7 or 12.
* If I draw a card there is a higher probability of getting something useful (I.E. another 7, 12, or wild). Which would let me go out.

Most human players would accept the risk inherent in keeping the 7 or 12 and draw a card from the deck, instead of taking the 5.

The above logic isn't very hard to implement. It's when you extrapolate it out and have to do the cost/benefit analyses on 13 cards in your hand, that decision making tree becomes a lot more complex. Which would be why I want to look into machine learning to solve this problem.

---

<sub>As a note I have already implemented the logic to determine ***if*** you can go out. The above applies to how the computer should evaluate the pro's and cons of a specific action (which card to draw, and which card to discard, and to an extent, when in higher rounds, how to structure the runs/sets needed to lay down it's hand). </sub>

# Answer
> 3 votes
The best technique to use here is Reinforcement Learning.

These techniques rely on feedback from the environment in order to learn. Feedback takes the form of a numerical reward signal, and guides the agent in developing its policy. You can model the environment as a Markov decision process, which is defined by a set of states, actions, transition probabilities, and expected rewards. Each action has a probability of being the action selected, as well as an associated value, which corresponds to the expected reward of taking the action. A greedy action is an action that has the greatest value. In order to learn, the agent must balance exploration and exploitation of the environment. During exploration, the agent tries non-greedy actions in hopes of improving its estimates of their values.

One of the most easiest ways to implement a Reinforcement Learning algorithm is using the Q-learning algorithm.

# Answer
> 1 votes
What you're looking for is called a ***supervised neural network***.

This is a neural network that is trained with known data, rather than pitting a fitness function against unknown data. Where do you get the known data? You'll create it yourself.

There are two ways to do a cost/benefit analysis. The first is to determine some algorithm to predict likely cost and likely benefit of any action. The second is to record actual costs and benefits. The latter is only possible with large sources of data, but with modern computing and an easily automated process (such as your game), you can create this data fairly simply.

The data will be derived through many hundreds or thousands of sessions per set (the more sessions, the more accurate the analysis). These sessions will randomize all unknown data (other players' hands, the draw pile) and keep consistent the known data (turn number, player's hand, discard pile, whether it's the final turn). The decision made (draw from discard pile, draw from draw pile, etc) for a turn will be *random, but remembered*.

The reason to keep the known data consistent through the set of sessions is because this data will be the neural network's input. The reason to keep the unknown data random is because you want to teach the AI the odds of a decision based only on the known data. The reason to randomize the decision made is that the important aspect of the session is not which decision was made but the result of of the decision.

The sessions in a set give you results tied to decisions. This gives you, over the course of many sessions, the actual costs and benefits of each choice. For example, you might end up with, given a certain hand and a certain discard pile card, 20% of the "Draw from Discard" sessions resulted in a positive outcome, while 40% of the "Draw from Draw Pile" sessions resulted in a positive outcome. Or you could be recording the outcome as a continuous variable instead of a binary "good/bad", so you might find the average of one choice to be 0.87 and the average of the other to be 0.34.

This data is then used to trained the neural network. The known data is the input (number of turn, final turn yes/no, cards in hand) while the outcome of your set of sessions is the output of the neural network. Over many thousands of sets, the neural network will learn, given a random hand and other known variables, what the odds are for drawing from the discard or drawing from the draw piles (or any other choices one could make, such as discarding cards).

Notes:

1. Running through thousands of sets of thousands of sessions might seem worrisome, but this entire process is automated, from a single session to the training of the network. It can be done overnight if the process seems too lengthy.
2. You can play the sessions through the entire round, or you can play only a single turn. Playing through the round means a simpler analysis of the benefit of the decisions made (won or lost) but a slightly more complicated process of analysing each choice. A single turn means determining some function to score that turn's benefit/cost (if you gained a set, the sum of the card numbers, etc), but a simpler process integrating it into the neural network.

# Answer
> 0 votes
Maybe you should take a look at the Genetic Algorithms.

To solve your problem with these you basically need a function with the tree as the input and a number as output. If the number is higher, the decision tree is better.

The crossover function could be that you take some leaf parts from the tree and insert it at random places in the other tree.

The random mutation function could be that you randomly create treeparts and operations.

# Answer
> 0 votes
I think you are misunderstanding the role of machine learning, at least in its current 'off the shelf' form. In order to apply machine learning to assist with a decision you need to be able to reduce the problem into a set of values of a number of consistent inputs, a set of possible outputs to choose from and a function that lets you assess the comparative utility of the different outputs.

For your problem, getting it into this form is a much more difficult problem than applying some machine learning algorithm once you've done that.

To put in another way, machine learning *doesn't do the cost/benefit analysis for you*, it requires that to be implemented in order to optimise some algorithm for making decisions to *optimise* the cost/benefit. Doing the cost/benefit is the hard part of your problem, but it's not something that machine learning will help you with.

The way that you could implement machine learning would be to do no cost/benefit analysis at all and measure everything simply by games won, using that as your metric to evaluate models. Say you come up with an algorithm for playing that game that depends on a number of free parameters. If you have that algorithm play thousands of games against itself, you can use any multidimensional minimisation algorithm to search for the set of parameter values that is most likely to win. You still need to come up with that algorithm yourself though. You could use something like a neural network, which come with some standard ways of training the free parameters against the fitness function (in your case, winning the most number of games).

The down side to this approach is that it is essentially a black box and you are training the algorithm against itself (or some other similarly parametrized models), so you are not training it to be the best algorithm possible, just one that is the best possible given the limitations imposed on it by how you construct it. Once you have trained the model it can be difficult to understand why it makes particular moves so it can be difficult to correct the propensity to consistently do something silly in a particular situation.

---
Tags: ai, logic
---


title: Hiding pixels inside a Shape

text:
# Question
Title: Hiding pixels inside a Shape
I have a player wich is a png image and I want a part of him to be able to go behind things, so I need to know how to hide pixels that are inside of a shape

# Answer
That's not the way you do it. Simply draw the things that are on top last, they will overwrite the things below them. Or you can access the depth values and order the objects with that value.
> 2 votes

---
Tags: java, slick
---


# Question
Title: Rotating plane to be parallel to given normal via change of basis
I have two planes and their respective normals. I would like to rotate the second plane, planeB, so that it is parallel to the first, planeA.

To do this, I am using a change of basis to rotate each vector of planeB. To create the new axes, I do the following:

```
cAxis = planeA.normal;
aAxis = planeA.normal parallel to yAxis ? then xAxis else yAxis;
bAxis = aAxis cross cAxis

```

I create a rotation matrix from these new axes as such:

```
| aAxis.x  aAxis.y  aAxis.z |
| bAxis.x  bAxis.y  bAxis.z |
| cAxis.x  cAxis.y  cAxis.z |

```

I then multiply each vector of planeB by the rotation matrix to get their new coordinates. I think that this is the correct method for rotating the plane, but I don't believe the new axes that I am creating are correct. The results are correct when planeA's normal is parallel to the z axis, but not otherwise. Is there a standard formula for creating the new axes?

# Answer
I see a few potential gaps in your methods. One might be that you are using (presumably) constant axes for your `aAxis` calculation, `xAxis` and `yAxis`. I would guess those are the absolute world axes X and Y. That *might* be ok, if your specific scenario only uses planes oriented to X or Y. That's where you go awry.

### To rotate from one direction to another, cross those angles

You cross one plane's normal and an absolute axis. That's not right.

```
vector3 axis = planeA.normal cross planeB.normal;

```

However, this `axis` is only a vector with the same direction as the axis of rotation. A rotation axis needs to be a unit vector.

### Cross products need to be normalized

The result of any cross-product, `bAxis` or other, will only be a unit vector if both crossed vectors are unit vectors AND they are perpindicular to each other. This is a result of this property of cross products (and the fact that sin(90 degrees) = 1):

```
length(A x B) = sin(angle_between(A, B)) * length(A) * length(B)
// so if A and B are unit vectors (have length = 1)
length(A x B) = sin(angle_between(A, B))
// and if that length is 1...
1 = sin(angle_between(A, B)) = sin(90 degrees)  // A and B were perpindicular

```

(Side note, you might be able to get a unit vector by crossing a weird combination of non-unit vectors and an angle that coincidentally still adds up to magnitude 1. But that's not the point, and both your planes' normal vectors ought to be unit vectors anyway.)

### Rotation matrices are hard to build by hand

If you had normalized your axis, your matrix would still be very wrong. They are not constructed directly from the components of the participating vectors. This is a rotation matrix (again from wikipedia):

Moral of the story: use a library to construct your rotation matrix. You'll thank yourself later.

### The correct axis and angle rotation matrix

Good news! You already have it after generating your cross product!

```
// length(A x B) = sin(angle_between(A, B)
// which leaves us with a handy:
vector3 a_cross_b = A x B;
float angle = arcsign(length(a_cross_b));
vector3 axis = normalize(a_cross_b);

matrix correct_rotation_matrix = create_rotation_from_axis_angle(axis, angle);
// a quaternion is also acceptable here.

```

As a bonus, here is some VBA,VB6 code to play with:

```
'common used data type
Type POINT3D
    X As Double
    Y As Double
    Z As Double
    'W As Double
End Type
Function Arcsine(ByVal X As Double) As Double
    'inverse sine
    If X = 1 Then
        Arcsine = 0.5 * Pi
        Exit Function
    End If

    If X = -1 Then
        Arcsine = -0.5 * Pi
        Exit Function
    End If
    Arcsine = Sgn(X) * Atn(Sqr(X * X / (1 - X * X)))
End Function

Function POINT_TRANSFORM(Point As POINT3D, mat() As Double) As POINT3D
    'apply transformation matrix to a 3d point
    Dim P(3) As Double
    Dim RES As POINT3D
    P(0) = Point.X
    P(1) = Point.Y
    P(2) = Point.Z
    P(3) = 1
    RES.X = P(0) * mat(0, 0) + P(1) * mat(0, 1) + P(2) * mat(0, 2) + P(3) * mat(0, 3)
    RES.Y = P(0) * mat(1, 0) + P(1) * mat(1, 1) + P(2) * mat(1, 2) + P(3) * mat(1, 3)
    RES.Z = P(0) * mat(2, 0) + P(1) * mat(2, 1) + P(2) * mat(2, 2) + P(3) * mat(2, 3)
    'RES.W = P(0) * mat(3, 0) + P(1) * mat(3, 1) + P(2) * mat(3, 2) + P(3) * mat(3, 3)

    POINT_TRANSFORM = RES
End Function

Function VECTOR_CROSS(U As POINT3D, V As POINT3D) As POINT3D
    'vector cross product
    Dim P As POINT3D
    P.X = ((U.Y * V.Z) - (V.Y * U.Z))
    P.Y = ((U.Z * V.X) - (V.Z * U.X))
    P.Z = ((U.X * V.Y) - (V.X * U.Y))
    VECTOR_CROSS = P
End Function
Sub CREATE_TM_FROM_AXIS_ANGLE(AXIS As POINT3D, Angle As Double, MATR() As Double)
    'axis is given as normalized vector
    'angle in RAD
    'https://gamedev.stackexchange.com/questions/50880/rotating-plane-to-be-parallel-to-given-normal-via-change-of-basis
    'https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle

    ReDim MATR(3, 3)

    Dim c As Double
    Dim S As Double
    Dim CM As Double
    X = AXIS.X
    Y = AXIS.Y
    Z = AXIS.Z

    c = Cos(Angle)
    S = sIn(Angle)
    CM = 1 - c

    MATR(0, 0) = X * X * CM + c: MATR(0, 1) = X * Y * CM - Z * S: MATR(0, 2) = X * Z * CM + Y * S

    MATR(1, 0) = Y * X * CM + Z * S: MATR(1, 1) = Y * Y * CM + c: MATR(1, 2) = Y * Z * CM - X * S

    MATR(2, 0) = Z * X * CM - Y * S: MATR(2, 1) = Z * Y * CM + X * S: MATR(2, 2) = Z * Z * CM + c
    MATR(3, 3) = 1
End Sub

Function PLANAR_AREAS(A() As Double, B() As Double, MATR() As Double) As Boolean
    'given normal vectors aof two planes
    'searched: transform matrix to make them coplanar (align them)

    PLANAR_AREAS = False
    Dim U As POINT3D
    Dim V As POINT3D
    Dim R As POINT3D
    Dim AXIS As POINT3D
    Dim L As Double
    Dim Angle As Double
    U.X = A(0)
    U.Y = A(1)
    U.Z = A(2)

    V.X = B(0)
    V.Y = B(1)
    V.Z = B(2)

    R = VECTOR_CROSS(U, V)

    L = Abs(Sqr(R.X * R.X + R.Y * R.Y + R.Z * R.Z))
    If L = 0 Then GoTo ulos
    Angle = 0# * Pi - Arcsin(L)

    AXIS.X = R.X / L
    AXIS.Y = R.Y / L
    AXIS.Z = R.Z / L

    Call CREATE_TM_FROM_AXIS_ANGLE(AXIS, Angle, MATR())
    PLANAR_AREAS = True
ulos:
End Function

Sub TEST_PLANAR_AREAS()
    'This routine will make all entitys coplanar to the first ones
    Dim entity As AcadEntity
    Dim A() As Double
    Dim B() As Double
    Dim MATR() As Double
    ReDim A(2)
    ReDim B(2)
    Dim c As Long
    Dim V As Variant
    For Each entity In ThisDrawing.PickfirstSelectionSet 'select a bunch of acad entitys
        V = entity.Normal 'get their normal vectors

        If c = 0 Then 'use first ones as reference
            A(0) = V(0)
            A(1) = V(1)
            A(2) = V(2)
            c = 1
        Else 'use rest as "target"
            B(0) = V(0)
            B(1) = V(1)
            B(2) = V(2)
            If PLANAR_AREAS(A(), B(), MATR()) Then 'calculate transformation matrix
                entity.TransformBy MATR 'apply Transform Matrix to elements
            End If
        End If

    Next

End Sub

Sub SHOWNORMALS()
    'print the nomals of the autocad entitys (intermediate screen)
    Dim entity As AcadEntity
    Dim V
    Dim I As Long
    For Each entity In ThisDrawing.PickfirstSelectionSet
        V = entity.Normal
        Debug.Print "------"
        For I = 0 To UBound(V)
            Debug.Print V(I), Arcsin(CDbl(V(I))) / Pi * 180, Arccos(CDbl(V(I))) / Pi * 180
        Next
    Next

End Sub

```
> 2 votes

---
Tags: matrix, rotation, vector, linear-algebra
---


# Question
Title: Writing and reading from an XML file with Slick2D
I was wondering how you would go about writing and the reading from an XML file using the Java library Slick2D.

I have googled for the last couple of days and have found nothing succinct and simple that explains what I'm looking for.

I am looking for 3 things:-

1. How to create an XML file (would be awesome to be able to search a directory to see if there is an existing file and only create a new file if one does not already exist.
2. How to write to the created XML file.
3. How to read from the found XML file.

The reason for this is that I'm trying to create a save/load class for a game.

Just a general snippet of code, that I'd be able to modify for my needs would be great even for a learning experience.

So now for my question, does anyone have any information that may help me on my quest to succeed in my above stated three goals?

# Answer
Check out XStream, I found it to be **extremely** easy to use for serializing/de-serializing Java Objects.

For working with files such as checking if they exist, use the Java API: java.io.File is a simple way to check such a thing.

I think you should familiarize yourself with basic Java input/output before chasing goals such as serialization with XML.
> 1 votes

---
Tags: java, lwjgl, slick
---


# Question
Title: Slick & NiftyGUI. Nifty initialize exception
I found my self into trouble when trying to run a Slick game with a Nifty Game State. This is the code:

```
@Override
protected void initGameAndGUI(GameContainer container, StateBasedGame game)
        throws SlickException {
    initNifty(container, game);
}

```

If i run this i get: `java.lang.IllegalStateException: The NiftyGUI was already initialized. Its illegal to do so twice.`

If i delete the call to `initNifty()` i get another exception:`java.lang.IllegalStateException: NiftyGUI was not initialized.`

# Answer
> 4 votes
This evening I switched switched from TWL to Nifty to give it a try. I experienced some of the same issues as you. I did get it working though. The documentation isn't great and there's no complete example at the end, so it's hard to know exactly what you're supposed to do at a glance. Below I've included the function I implemented to properly set up Nifty.

As the documentation states(see manual), your main game class is supposed to extend `NiftyOverlayGame`, or one of the other classes it lists, as I answered in your other question.

One of the functions you need to override is `initGameAndGUI` and I believe this is where your issue originates from. This is how I did it properly:

```
protected void initGameAndGUI(GameContainer gc) throws SlickException {
    renderDevice = new SlickRenderDevice(gc);
    soundDevice = new SlickSoundDevice();
    inputSystem = new SlickSlickInputSystem(new PlainSlickInputSystem());
    timeProvider = new LWJGLTimeProvider();
    gui = new Nifty(renderDevice, soundDevice, inputSystem, timeProvider);
    initNifty(gc);
}

```

Where these objects were defined inside my main class as (I'll include the imports as well for reference):

```
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.slick2d.NiftyOverlayGame;
import de.lessvoid.nifty.slick2d.input.PlainSlickInputSystem;
import de.lessvoid.nifty.slick2d.input.SlickSlickInputSystem;
import de.lessvoid.nifty.slick2d.render.SlickRenderDevice;
import de.lessvoid.nifty.slick2d.sound.SlickSoundDevice;
import de.lessvoid.nifty.slick2d.time.LWJGLTimeProvider;
import de.lessvoid.nifty.spi.input.InputSystem;
import de.lessvoid.nifty.spi.sound.SoundDevice;

...

public final class MainGame extends NiftyOverlayGame  {
    Nifty gui;
    SoundDevice soundDevice;
    SlickRenderDevice renderDevice;
    InputSystem inputSystem;
    TimeProvider timeProvider;
    ...

```

Hopefully setting up your code similar to this should help you get on the right track (if you haven't figured this out already).

# Answer
> 0 votes
I'm using nifty 1.3.2 and I had the same issue. Whenever I use a state based implementation, I got the error described above. This seems definitely to be a bug in nifty. Their examples does not implement slicks state-based implementations...

I could make it running by manipulating the source and build my own jar file of nifty-slick-renderer-1.3.2

I know the following change does not solve the issue, but will make your code run. Change

```
if (guiPrepared) {
  throw new IllegalStateException("The NiftyGUI was already initialized. Its illegal to do so twice.");
}

```

to

```
if (guiPrepared) {
  return;
}

```

and rebuild the jar file (and name it custom or so). This change will just ignore the second run of trying to build nifty.

---
Tags: java, gui, slick
---


# Question
Title: How to reduce/handle image loading times?
I'm working on a 2D game that has very high resolution images (so that things look good on Retina MacBooks and such), and am seeing a noticeable lag caused by image loading.

I notice the strongest lag when I switch to a screen that loads 72 500x600 PNG images - it takes almost a second on a pretty modern system with an SSD. Loading the files from the disk is fairly quick, usually less than one millisecond. But loading the PNGs takes about 5-7 milliseconds each, using libpng.

Now I have two questions:

**What are my options for speeding up the loading?**

* Will using sprite sheets help? (My guess is no, since loading times seem to increase with image size).
* Would it make sense to add pre-downscaled versions of the files and use these on lower resolutions?

**Should I load all assets upfront?**

My current approach is a bit naive: Each entity loads its own texture as soon as it is instantiated. I can change things a bit to make sure all entities are instantiated upfront where possible, but that seems error prone.

Are there better approaches? I think we'll end up with around 100-200 MB of images, so it might be fine to load them all into memory when the game starts. The best approach I can come up with is to have a huge mapping from image files to image IDs and use the IDs to load images in the code - then I'd know all the image files upfront. Or should I shy away from loading everything upfront if I can speed the loading up until it's unnoticeable again?

# Answer
> 1 votes
Create an ImageLibrary class responsible for loading images from disk, and supplying them to the front-end on demand.

Have the ImageLibrary manage background task(s) to load images from disk steadily (individually, so they can be retargeted if necessary as the front end demands specific images that have not been loaded yet).

I suspect the bottleneck is not disk I/O, but rather the current need to perform all the IO serially. Parallelizing this task should help.

This framework could also morph into a disk cache over time, by tracking a most-recently-used time for each image, and retiring the oldest as needed to make room for newly demanded images.

# Answer
> 0 votes
In general terms you'll have the following bottlenecks for texture image loading (since you mention MacBooks I'm going to assume that you're using OpenGL):

* Disk I/O
* Decompression
* Load to GL/hardware

Disk I/O can be solved by using faster hard disks or smaller image file sizes (this includes those that compress well) and from your question you appear to have that well in hand.

Decompression can be solved by using image formats that are fast to decompress, or that don't need decompression at all. Here your use of PNG is working against you as PNG is quite slow to decompress. This will be one of your primary bottlenecks. Note here that not needing to decompress at all and smaller file sizes are not mutually exclusive; we'll discuss that later.

Load to GL/hardware overhead at first glance looks like just a bandwidth limit, but that's not all. Since most GPUs like texture image formats to be laid out in BGRA order, if you're loading any other format your GL driver has to do a lot of extra work to convert it to what it likes. In particular, the frequently seen GL\_RGB format is a worst-case format, as it may require the driver to both expand to 4-component *and* to reswizzle the data. This is further discussed here: http://www.opengl.org/wiki/Common\_Mistakes#Texture\_upload\_and\_pixel\_reads and here: http://www.opengl.org/wiki/Common\_Mistakes#Slow\_pixel\_transfer\_performance and is likely to be another one of your bottlenecks.

Using traditional image formats (TGA, BMP, PNG, etc) you're going to solve one or two of these bottlenecks, but not the other(s). I'd recommend that you solve them all before looking at threading/etc and there is one texture image format that is going to do this for you: DDS with DXT/S3TC compression.

Despite the name ("Direct Draw Surface") this format is in reality just a normal binary image format and can be easily loaded by OpenGL too (using the GL\_ARB\_texture\_compression and GL\_EXT\_texture\_compression\_s3tc extensions or GL 1.3 or higher). It provides the following advantages for you:

* File size is one-eighth (for images without alpha) or one-quarter (for images with alpha) the uncompressed size so it can come off disk reasonably fast.
* No decompression step is needed at all; just supply the pointer to your raw loaded data to a glCompressedTexImage call.
* The texture data is already in a GPU-native format so no intermediate driver-side work is needed during the texture upload.
* You'll also get better performance during rendering (in the order of 20% to 30% faster) owing to lower bandwidth requirements there too.

Of course there's no such thing as a free lunch, so it's necessary to warn you that this is a lossy compression format, and so you may see some compression artefacts. On the other hand, if it's good enough then it's good enough, even if lossy. It's also necessary to warn you that S3TC texture compression is burdened by IP and so may not be available in all drivers, but in practice it's ubiquitous outside of open source implementations.

---
Tags: image, assets, loading, asset-management, preload
---


title: Where to run logic update in openGL ES?

text:
# Question
Title: Where to run logic update in openGL ES?
Using Canvas with Surfaceview I had a run() method where I would essentially do the following:

```
onDraw();
update();

```

Where onDraw method would do the rendering and update would update all my game physics / logic etc...

Having switched to openGL ES (2.0) and therefore now using a glSurfaceview, I have the following:

```
onDrawFrame(){

//Rendering code here

}

```

Which I don't call myself as it gets called automatically (my rendering is set to continuous).

So where / how do I run my logic updates?

# Answer
I've been reading up some more on this and it seems if you want a 2 threaded set up (that being 1 thread for UI and another for rendering **and** logic updates, then your best bet is the use the onDrawFrame method as something akin to Canvas's 'run()' method. Simply create your own Draw() and update() methods and call them from inside onDrawFrame, this way you can put your limiting / timing code inside onDrawFrame (the stuff that would normally go into run()). I can't see any other way around it, but if anyone has any other ideas for an effective 2 threaded OpenGL ES 2.0 setup, I'd appreciate hearing it!
> 0 votes

# Answer
The easiest solution is always nice:

```
onDrawFrame(){

//Rendering code here

update();

}

```

Or you could put a break point in your draw code and step out to see if there's an update loop above it you could override.
> 1 votes

# Answer
You can override the `run` method:

```
@Override
public void run()
{
    while(gameRunning)
    {
        //logic updates
    }
}

```

Since the rendering will be performed on a separate thread. You can run inside this while loop on the main thread.

You'll likely want to implement some limiting in there as well, you can find an example of that here.
> 0 votes

---
Tags: android, rendering, opengl-es2, game-loop
---