title: Game State 'Stack'?

text:
# Question
Title: Game State 'Stack'?
I was thinking about how to implement game states into my game. The main things I want for it are:

* Semi-transparent top states-being able to see through a pause menu to the game behind
* Something OO-I find this easier to use and understand the theory behind, as well as keeping orgranised and adding more to.

I was planning on using a linked list, and treat it as a stack. This means I could access the state below for the semi-transparency.
Plan: Have the state stack be a linked list of pointers to IGameStates. The top state handles its own update and input commands, and then has a member isTransparent to decide whether the state underneath should be drawn.
Then I could do:

```
states.push_back(new MainMenuState());
states.push_back(new OptionsMenuState());
states.pop_front();

```

To represent the player loading, then going to options, and then main menu.
Is this a good idea, or...? Should I look at something else?

Thanks.

# Answer
> 44 votes
I worked on the same engine as coderanger. I have a differing viewpoint. :)

First, we did not have a stack of FSMs - we had a stack of states. A stack of states makes a single FSM. I don't know what a stack of FSMs would look like. Probably too complicated to do anything practical with.

My biggest problem with our Global State Machine was that it was a stack of states, and not a set of states. This means, e.g., .../MainMenu/Loading was different than .../Loading/MainMenu, depending on if you got the main menu up before or after the loading screen (the game is asynchronous and loading is mostly server-driven).

As two examples of things this made ugly:

* It led to e.g. the LoadingGameplay state, so you had Base/Loading, and Base/Gameplay/LoadingGameplay for loading within the Gameplay state, which had to repeat much of the code in the normal loading state (but not all, and add some more).
* We had several functions like "if in character creator go to gameplay; if in gameplay go to character select; if in character select go back to login", because we wanted to show the same interface windows in different states but make the Back/Forward buttons still work.

Despite the name, it was not very "global". Most internal *game* systems did not use it to track their internal states, because they didn't want their states mucking about with other systems. Others, e.g. the UI system, could use it but only to copy state into their own local state systems. (I would especially caution against the system for UI states. UI state is not a stack, it's really a DAG, and trying to force any other structure on it is only going to make UIs that are frustrating to use.)

What it was good for was isolating tasks for integrating code from infrastructure programmers who didn't know how the game flow was actually structured, so you could tell the guy writing the patcher "put your code in Client\_Patch\_Update", and the guy writing the graphics loading "put your code in Client\_MapTransfer\_OnEnter", and we could swap certain logic flows around without much trouble.

On a side project, I have had better luck with a state *set* rather than a *stack*, not being afraid to make multiple machines for unrelated systems, and refusing to let myself fall into the trap of having a "global state", which is really just a complicated way to synchronize things through global variables - Sure, you're going to end up doing it near some deadline, but don't design with that as your *goal*. Fundamentally, state in a game is not a stack, and states in a game are not all related.

The GSM also, as function pointers and non-local behavior tend to do, made debugging things more difficult, though debugging those kind of large state transitions wasn't very fun before we had it either. State-sets instead of state-stacks does not really help this, but you should be aware of it. Virtual functions rather than function pointers may alleviate that somewhat.

# Answer
> 11 votes
Here's an example implementation of a gamestate stack that I found to be very useful: http://creators.xna.com/en-US/samples/gamestatemanagement

It's written in C# and to compile it you need the XNA framework, however you could just check out the code, the documentation and the video to get the idea.

It can support state transitions, transparent states (such as modal message boxes) and loading states (that manage the unloading of existing states and loading of the next state).

I use the same concepts in my (non-C#) hobby projects now (granted, it might not be suitable for larger projects) and for small/hobby projects I can definitely recommend the approach.

# Answer
> 5 votes
This is similar to what we use, a stack of FSMs. Basically just give each state an enter, exit, and tick function and call them in order. Works very nicely for handling things like loading too.

# Answer
> 4 votes
One of the "Game Programming Gems" volumes had a state machine implementation in it intended for game states.

This archived document has an example of how to use it for a small game, and shouldn't be too Gamebryo-specific to be readable.

# Answer
> 4 votes
Just to add a little standardization to the discussion, the classic CS term for this kind of data structures is a pushdown automaton.

# Answer
> 1 votes
I not sure a stack is entirely necessary as well as limiting the functionality of the state system. Using a stack, you can't 'exit' a state to one of several possibilities. Say you start off in "Main Menu" then go to "Load Game", you may want to go to a "Pause" state after successfully loading the saved game and return to "Main Menu" if the user cancels the load.

I would just have the state specify the state to follow when it exits.

For those instances where you want to return to the state preceding the current state, for example "Main Menu-\>Options-\>Main Menu" and "Pause-\>Options-\>Pause", just pass as a startup parameter to the state the state to go back to.

# Answer
> 1 votes
Another solution to transitions and other such things is to provide the destination and source state, along with the state machine, which could be linked to the "engine", whatever that may be. The truth is that most state machines are probably going to need to be tailored to the project at hand. One solution might benefit this or that game, other solutions may hinder it.

```
class StateMachine
{
public:
    StateMachine(Engine *);
    void Push(State *);
    State *Pop();
    void Update();
    Engine *GetEngine();

private:
    std::stack<State *> _states;
    Engine *_engine;
};

```

States are pushed with the current state and the machine as parameters.

```
void StateMachine::Push(State *state)
{
    State *from = 0;
    if (!_states.empty()) from = _states.top();
    _states.push(state);
    state->Enter(this, from);
}

```

States are popped in the same fashion. Whether you call `Enter()` on the lower `State` is an implementation question.

```
State *StateMachine::Pop()
{
    _ASSERT(!_states.empty());
    State *state = _states.top();
    State *to = 0;
    _states.pop();
    if (!_states.empty()) to = _states.top();
    state->Exit(this, to);
    return state;
}

```

When entering, updating or exiting, the `State` gets all the information it needs.

```
void SomeGameState::Enter(StateMachine *sm, State *from)
{
    Engine *eng = sm->GetEngine();
    eng->GetKeyboard()->KeyDown.Bind(this, &SomeGameState::KeyDown);
    LoadLevelState *state = new LoadLevelState();
    state->SetLevel(eng->GetSaveGame()->GetLevelName());
    state->Load.Bind(this, &SomeGameState::OnLevelLoaded);
    sm->Push(state);
}

void SomeGameState::Update(StateMachine *sm)
{
    Engine *eng = sm->GetEngine();
    float time = eng->GetFrameTime();
    if (shouldExit)
        sm->Pop();
}

void SomeGameState::Exit(StateMachine *sm, State *from)
{
    Engine *eng = sm->GetEngine();
    eng->GetKeyboard()->KeyDown.UnsubscribeAll(this);
}

```

# Answer
> 0 votes
I've used a very similar system across several games and found that with a couple of exceptions, it serves as an excellent UI model.

The only issues we encountered were cases where it's desired in certain cases to pop back multiple states before pushing a new state (we re-flowed the UI to remove the requirement, as it was usually a sign of bad UI) and creating wizard-style linear flows (solved easily by passing the data along to the next state).

The implementation we used actually wrapped the stack and handled the logic for updating and rendering, as well as operations on the stack. Each operation on the stack triggered events on the states to notify them of the operation occurring.

A few helper functions were added as well to simplify common tasks, such as Swap (Pop & Push, for linear flows) and Reset (for dropping back to the main menu, or ending a flow).

# Answer
> 0 votes
This is the approach I take for nearly all of my projects, because it works incredibly well and is extremely simple.

My most recent project, Sharplike, handles control flow in this exact way. Our states are all wired up with a set of event functions that are called when states change, and it features a "named stack" concept in which you can have multiple stacks of states within the same state machine and branch among them--a conceptual tool, and not necessary, but handy to have.

I would caution against the "tell the controller what state should follow this one when it ends" paradigm suggested by Skizz: it's not structurally sound, and it makes stuff like dialog boxes (which in the standard stack-state paradigm just involves creating a new state subclass with new members, then reading off it when you return to the invoking state) much much harder than it has to be.

# Answer
> 0 votes
I used basically this exact system in several systems orthogonally; the frontend and in-game menu (aka "pause") states, for instance, had their own state stacks. The in-game UI also used something like this although it had "global" aspects (like the healthbar and the map/radar) that the state switching might tint but which updated in a common way across states.

The in-game menu may be "better" represented by a DAG, but with an implicit state machine (each menu option that goes to another screen knows how to go there, and pressing the back button always popped the top state) the effect was exactly the same.

Some of these other systems also had "replace top state" functionality, but that was typically implemented as `StatePop()` followed by `StatePush(x);`.

Memory card handling was similar since I did actually push a ton of "operations" into the operation queue (which functionally did the same thing as the stack, just as FIFO rather than LIFO); once you start using this sort of structure ("there's one thing happening now, and when it's done it pops itself") it starts infecting every area of the code. Even the AI started using something like this; the AI was "clueless" then switched into "wary" when the player made noises but wasn't seen, and then finally elevated to "active" when they saw the player (and unlike lesser games of the time, you couldn't hide in a cardboard box and make the enemy forget about you! Not that I'm bitter...).

GameState.h:

```
enum GameState
{
   k_frontend,
   k_gameplay,
   k_inGameMenu,
   k_moviePlayback,
   k_numStates
};

void GameStatePush(GameState);
void GameStatePop();
void GameStateUpdate();

```

GameState.cpp:

```
// k_maxNumStates could be bigger, but we don't need more than
// one of each state on the stack.
static const int k_maxNumStates = k_numStates;
static GameState s_states[k_maxNumStates] = { k_frontEnd };
static int s_numStates = 1;

static void (*s_startupFunctions)()[] =
   { FrontEndStart, GameplayStart, InGameMenuStart, MovieStart };
static void (*s_shutdownFunctions)()[] =
   { FrontEndStop, GameplayStop, InGameMenuStop, MovieStop };
static void (*s_updateFunctions)()[] =
   { FrontEndUpdate, GameplayUpdate, InGameMenuUpdate, MovieUpdate };

static void GameStateStart(GameState);
static void GameStateStop(GameState);

void GameStatePush(GameState gs)
{
   Assert(s_numStates < k_maxNumStates);
   GameStateStop(s_states[s_numStates - 1])
   s_states[s_numStates] = gs;
   s_numStates++;
   GameStateStart(gs);
}

void GameStatePop()
{
   Assert(s_numStates > 1);  // can't pop last state
   s_numStates--;
   GameStateStop(s_states[s_numStates]);
   GameStateStart(s_states[s_numStates - 1]);
}

void GameStateUpdate()
{
   GameState current = s_states[s_numStates - 1];
   s_updateFunctions[current]();
}

void GameStateStart(GameState gs)
{
   s_startupFunctions[gs]();
}

void GameStateStop(GameState gs)
{
   s_shutdownFunctions[gs]();
}

```

---
Tags: c++, architecture, state
---


title: Why can't I write to my render targets?

text:
# Question
Title: Why can't I write to my render targets?
Alright, been working on setting up my first deferred rendering attempt using a light prepass technique in Direct3D 11.

Anywho, I've been having problems understanding and using render targets. Never really had to do much of anything with them in my previous forward rendering approaches. I'm pretty sure I'm correctly initializing them and binding them to the output merger stage however I'm not getting any results from my first geometry pass.

Now, what I'm doing to test my Geometry buffer pass could be the problem itself and the source of my confusion. I've been unclear as to how to choose which render target is presented with the swap chain. I've been working under the assumption that I just need to make sure I have a render target view that was initialized using the swap chain's backbuffer address and that this render target is what gets presented each frame. So based on that I've been binding my "Presentation" render target to the pipeline instead of what I would be using for my Position and/or Normal render buffers. However, I get nothing but an empty black frame so I assume the buffer isn't getting written to properly. (I'm actually overriding the values written to the buffer with a hard coded color in the pixel shader so I don't think it's related to the shader logic doing something funky, however sending the same "presentation" render target through my forward pass shader works fine...)

**So my questions essentially are:** am I missing a critical concept or failing to properly set up the Texture2D and Render Target View resources? And is my approach in choosing which render target to present correct, or can I directly bind a specific render target to the swap chain? Also my swap chain has a DXGI\_FORMAT\_R8G8B8A8\_UNORM format for the backbuffer, do the other render target views and textures have to match this?

**Edit:** With Nathan's clarification and debugging tips I was able to solve my buffer issue. It was actually getting written to however, I had a transposed matrix that was mucking up the vertex transformations. The code below works fine if someone reads this that is interested in it.

---

Providing the relevant code from my project.

Prepare pipeline for the geometry pass. (Pretty sure I've got this correct)

```
void GeometryBufferPass::StartRendering(RenderTargetView* _positionRT, RenderTargetView* _normalRT,
DepthBuffer* _depthBuffer, RasterizerState* _rasterizerState) {
static ID3D11RenderTargetView* _renderTargets[2];

static float _ClearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; // RGBA
pDeviceManager->GetDeviceContext()->ClearRenderTargetView(_positionRT->GetRenderTargetView(), _ClearColor);
pDeviceManager->GetDeviceContext()->ClearRenderTargetView(_normalRT->GetRenderTargetView(), _ClearColor);
pDeviceManager->GetDeviceContext()->ClearDepthStencilView(_depthBuffer->GetDepthBufferView(), D3D11_CLEAR_DEPTH, 1.0f, 1);

pDeviceManager->GetDeviceContext()->VSSetShader(vShader.GetShaderPtr(), 0, 0);
pDeviceManager->GetDeviceContext()->PSSetShader(pShader.GetShaderPtr(), 0, 0);

_renderTargets[0] = _positionRT->GetRenderTargetView();
_renderTargets[1] = _normalRT->GetRenderTargetView();
pDeviceManager->GetDeviceContext()->OMSetRenderTargets(2, _renderTargets, _depthBuffer->GetDepthBufferView());

pDeviceManager->GetDeviceContext()->IASetInputLayout(pVertexLayout);
pDeviceManager->GetDeviceContext()->IASetPrimitiveTopology(topologyType);

pDeviceManager->GetDeviceContext()->RSSetState(_rasterizerState->GetRasterizerState());

pDeviceManager->GetDeviceContext()->VSSetConstantBuffers(0, 1, transformBuffer.GetConstantBuffer());
pDeviceManager->GetDeviceContext()->PSSetConstantBuffers(1, 1, materialBuffer.GetConstantBuffer());
}

```

Render each object through the geometry pass.

```
void GeometryBufferPass::Render(Entity &_entity) {
static XMMATRIX _matrix;
static GeometryBufferPass_TransformBuffer _transformBuffer;
static GeometryBufferPass_MaterialBuffer _materialBuffer;
static unsigned int _offset = 0;

_matrix = XMMatrixMultiply(*_entity.GetInstanceObject()->GetScaleMatrix(), *_entity.GetInstanceObject()->GetRotationMatrix());
_matrix = XMMatrixMultiply(_matrix, *_entity.GetInstanceObject()->GetTranslationMatrix());
_transformBuffer.world = XMMatrixTranspose(_matrix);

_matrix = XMMatrixMultiply(_matrix, viewProjectionMatrix);
_transformBuffer.worldViewProjection = XMMatrixTranspose(_matrix);

transformBuffer.Update(&_transformBuffer);

_materialBuffer.specularExponent = _entity.GetRenderObject()->GetMaterial()->GetSpecularExponent();
materialBuffer.Update(&_materialBuffer);

pDeviceManager->GetDeviceContext()->IASetVertexBuffers(0, 1, _entity.GetRenderObject()->GetVertexBuffer()->GetVertexBuffer(), _entity.GetRenderObject()->GetVertexBuffer()->GetVertexStridePtr(), &_offset);
if (_entity.GetRenderObject()->GetVertexBuffer()->GetIndexBuffer() != 0) {
    pDeviceManager->GetDeviceContext()->IASetIndexBuffer(_entity.GetRenderObject()->GetVertexBuffer()->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, 0);
    pDeviceManager->GetDeviceContext()->DrawIndexed(_entity.GetRenderObject()->GetVertexBuffer()->GetIndexBufferSize(),0,0);
} else pDeviceManager->GetDeviceContext()->Draw(_entity.GetRenderObject()->GetVertexBuffer()->GetVertexBufferSize(), 0);
}

```

---

Here is how I create Texture2D and Render Target View objects.

```
bool Texture2D::InitializeTexture(const unsigned int _width, const unsigned int _height, const bool _isShaderResourceView, const bool _isRenderTargetView) {
if (!StartUp())
    return false;

D3D11_TEXTURE2D_DESC _desc;
_desc.Width = _width;
_desc.Height = _height;
_desc.MipLevels = 0;
_desc.ArraySize = 1;
_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; // or DXGI_FORMAT_R8G8B8A8_UNORM? Even though I am writing 4 floats to it...
_desc.Usage = D3D11_USAGE_DEFAULT;
_desc.CPUAccessFlags = 0;
_desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS; // Not sure if I need to generate a mip map chain for my purposes.

unsigned int _bindFlag = 0;
if (_isShaderResourceView)
    _bindFlag |= D3D11_BIND_SHADER_RESOURCE;

if (_isRenderTargetView)
    _bindFlag |= D3D11_BIND_RENDER_TARGET;

_desc.BindFlags = _bindFlag;

DXGI_SAMPLE_DESC _sampleDesc;
_sampleDesc.Count = 1;
_sampleDesc.Quality = 0;
_desc.SampleDesc = _sampleDesc;

if (FAILED(pDeviceManager->GetDevice()->CreateTexture2D(&_desc, 0, &pTexture)))
    return false;

if (_isRenderTargetView)
    if (!renderTarget.StartUp(pTexture, _desc.Format))
        return false;

return true;
}

```

Render Target View initialization

```
bool RenderTargetView::StartUp(ID3D11Resource* _resource, const DXGI_FORMAT _format, const D3D11_RTV_DIMENSION _viewType) {
pDeviceManager = D11DeviceManager::GetSingleton();

D3D11_RENDER_TARGET_VIEW_DESC _desc;
_desc.Format = _format;
_desc.ViewDimension = _viewType;

// Class only handles Texture2D at the moment.
D3D11_TEX2D_RTV _rtv;
_rtv.MipSlice = 1;
_desc.Texture2D = _rtv;

return !FAILED(pDeviceManager->GetDevice()->CreateRenderTargetView(_resource, &_desc, &pRenderTargetView));
}

```

---

And figured I might as well post the shader code just in case.

```
cbuffer TransformBuffer : register(b0) {
float4x4 worldMatrix,
         worldViewProjectionMatrix;
};

// Pretty sure constant buffers have to be atleast 16 bytes
// but shader compiler has yet to throw a warning or error.
cbuffer MaterialBuffer : register(b1) {
float  materialSpecularExponent;
};

struct vsInput {
float3 positionLS : POSITION;
float3 textureLS  : TEXTURE;
float3 normalLS   : NORMAL;
};

struct vsOutput {
float4 positionCS : SV_POSITION;
float2 textureLS  : TEXTURE;
float3 normalWS   : NORMAL;
float3 positionWS : POSITION;
};

struct psOutput {
float4 normalWS   : SV_TARGET0;
float4 positionWS : SV_TARGET1;
};

vsOutput VS( in const vsInput _in ) {
vsOutput _out;

_out.positionCS = float4(mul(_in.positionLS, (float3x3) worldViewProjectionMatrix), 1.0f);
_out.positionWS = mul(_in.positionLS, (float3x3) worldMatrix);
_out.normalWS   = mul(_in.normalLS,   (float3x3) worldMatrix);
_out.textureLS  = (float2)_in.textureLS;

return _out;
}

psOutput PS( in const vsOutput _in ) {
psOutput _out;

// Overwriting the pixel shader return values just so I can see if the render
// target is getting written to.
_out.normalWS   = float4(0.5f, 1.0f, 0.0f, 1.0f);//float4(normalize(_in.normalWS), materialSpecularExponent);
_out.positionWS = float4(0.5f, 1.0f, 0.0f, 1.0f);//float4(_in.positionWS, 1.0f);

return _out;
}

```

# Answer
You don't choose which render target to present. The `IDXGISwapChain` object owns the back buffer (the render target that gets presented); it's automatically created when the swap chain is set up. To draw to the back buffer, you first get a reference to it as a texture by calling `IDXGISwapChain::GetBuffer`; then you set up a RenderTargetView from that.

In order to display another render target on the screen, you can use `ID3D11DeviceContext::CopyResource` to copy from the other render target to the back buffer. That only works if they're exactly the same size and format; in other cases, I believe you have to copy the image by drawing a full-screen quad with a simple pixel shader that samples your image and returns it.

Other render targets and textures do not need to have the same format as the back buffer; they can have any supported format you want.
> 9 votes

---
Tags: rendering, directx11, deferred-rendering
---


# Question
Title: How can I use Rectangle.Intersect() to resolve collisions in XNA?
I have a 2D game written in XNA, and I've been trying to fine-tune my collision resolution. All of my game objects are squares, which means detecting a collision is easy - use the position and the size of each entity (which is already known) to craft a corresponding `Rectangle`, then compare the two with `Rectangle.Intersect()`.

This works fine for the most part, but has been running into weird corner cases where the collision resolution doubles an entity's jump height, or gets caught between tiles when moving horizontally across a flat surface.

I have recently expanded my code to include a velocity for each game entity, and I thought it would be possible to avoid some of these problems by preventing the need for these resolutions in the first place.

The idea would be to use an entity's position + velocity to predict a collision, then reduce the velocity to prevent a collision from occurring in the first place.

I can still use `Rectangle.Intersect()` to determine if the entity is in a collision, but I'm horribly confused on how to go from the `Rectangle` returned by `Rectangle.Intersect()` to an appropriate velocity counter-vector to avoid the collision.

Is there a straightforward way to go from the intersection `Rectangle` to an appropriate counter-velocity?

# Answer
I've actually implemented this just the other day. I started from the XNA Platformer Sample but noticed it had a few problems on corner cases. This was especially noticeable when using it for Zelda-like movement, because the character would get stuck between tiles when hugging the walls in *a certain direction*. I tried several changes to the algorithm, but there would always be one direction where the problem would appear.

I looked around a bit, and although I was skeptic, ended up trying a simple solution that I read in one forum - and it worked! So, instead of moving the player all at once and then resolving each collision along the smallest axis of intersection depth, the trick was to update and resolve on the X and Y axes separately. The process is still very similar to before, except for that difference. In other words:

1. Apply horizontal velocity to your position.
2. Round position.X to prevent jittering on some edge cases.
3. Iterate through each obstacle that the player is intersecting, calculating the horizontal intersection depth and subtracting it from the player's position so that he no longer intersects that obstacle.
4. Repeat 1-3 but for the vertical axis.

And so far it seems to be working, even when trying different player sizes and movement speeds, and "hugging" every wall in every direction. I've also noticed that as long as I cap the maximum instantaneous speed to the smallest value between the player's size and the tile's size, then he won't ever funnel through the walls. And that's still moving pretty fast!

I intended to clean it up a little, maybe make it completely generic, and release on my blog one of these days. But meanwhile I'll just drop every relevant bit of the code in a pastie, albeit unorganized, so you can read through it:

http://pastie.org/3152377

And here's a little video of that code in action, where I'm forcibly trying to push against every wall. I used normal a player size slightly smaller than the tile, and a normal movement speed, but I've also tested with many different values.

**Edit**

By the way, I'm using a custom method to get the intersection depth (basically the one from the Platformer sample modified to work on 1 dimension at a time) instead of `Rectangle.Intersect`. That's mostly because while `Rectangle.Intersect` gives you the depth, it does not give you the direction of the intersection, so you'd need to do some extra checks to find that out.
> 10 votes

---
Tags: xna, collision-detection, collision-avoidance
---


title: Transformed Pretransformed coordinates?

text:
# Question
Title: Transformed Pretransformed coordinates?
I am creating a minecraft like terrain engine thing in XNA and C#, and I am trying to create a item/block selector tool. The thing is I would like to have 3D objects on the tool. So I thought for the 3D objects to not move where the camera rotates/moves I would have to use pretransformed coordinates. Is that true? Also I would like to be able to use the world matrix to transform these objects like I would normally be able to when using world coordinates? Here is what I have got sofar in the effect file:

```
VertexToPixel PretransformedVS(float4 inPosition : POSITION, float4 inTexCoords : TEXCOORD0, float4 light : TEXCOORD01)  {
    VertexToPixel Output = (VertexToPixel)0;

    Output.Position = inPosition; // mul(inPosition, World)?
    Output.TexCoords = inTexCoords;
    Output.Light = light;

    return Output;
}

technique Pretransformed  {
    pass Pass0  {
        VertexShader = compile vs_2_0 PretransformedVS();
        PixelShader  = compile ps_2_0 PixelShaderFunction();
    }
}

```

Then in the pixel shader (I didn't include it in this as it is abit lengthy) all it does is get the color from the texture of that pixel and lights the vertex accordingly.

Any ideas?

**EDIT:** I just realised a problem with this approch. Each object, has a slightly different rotation when it is further to the left/right of the screen any ideas?

Something like this should work?

```
view = Matrix.CreateLookAt(Vector3.Zero, new Vector3(0, 0, -10), new Vector3(0, 1, 0));
projection = Matrix.CreateOrthographicOffCenter(0, 800, 600, 0, 0.1f, 100.0f);

```

The problem is with that is that none of my objects appear for that control on the screen?

**EDIT 2:**

```
    public override void Draw(SpriteBatch spriteBatch)
    {
        GetSelector();

        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
        world.Draw(spriteBatch);

        DrawSelector(spriteBatch);

    }

    private void GetSelector()
    {
        device.SetRenderTarget(selectorTarget);
        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        itemRender.Render(world.player.ItemSelector);

        device.SetRenderTarget(null);
        selectorTexture = (Texture2D)selectorTarget;
    }

    private void DrawSelector(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(selectorTexture, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 0.4f, SpriteEffects.None, 1);

        selectorTexture = null;
    }

```

**EDIT 3:**

Here is my drawing code:

```
        for (int i = 0; i != 5; ++i)
            DrawModel(sphere, Matrix.CreateScale(2f) * Matrix.CreateTranslation(100 + i * 200, 100, -10), view, projection);

        effect.CurrentTechnique = effect.Techniques["Block"];
        effect.Parameters["World"].SetValue(Matrix.Identity);
        effect.Parameters["View"].SetValue(view);
        effect.Parameters["Projection"].SetValue(projection);
        effect.Parameters["Texture"].SetValue(Variables.TILE_ALAIS.SheetTexture);

        int counter = 0;

        foreach (CubeObject cubeObject in CubeObjects)
        {
            effect.Parameters["World"].SetValue(Matrix.Identity * Matrix.CreateRotationY(MathHelper.ToRadians(65f)) * Matrix.CreateScale(30f) * Matrix.CreateTranslation(100 + counter * 200, 100, -10));

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, cubeObject.vertices.ToArray(), 0, cubeObject.vertices.Count / 3, cubeObject.indices.ToArray(), 0, cubeObject.indices.Count / 3, VertexPositionTextureLight.VertexDeclaration);
            }

            counter++;
        }

```

I am drawing the sphere for testing purposes, also note that I have rotated the cube in the world matrix by 65 degress on the y axis but it didn't appear to do anything. Here is what it looks like when I am looking in the air:

And here is what it looks like when I am looking at the terrain, why does it change when I look at the terrain?

The missing faces has nothing to do with culling, I do beleive ambient lighting is not a factor because all faces as a default have full light

**EDIT:**

Ok, well I fixed the problem and it had to do with me dividing the number of vertices by three... *very* embarasing. (So is my spelling ;)

Ok, so now I still have a problem... It is explained in the following screen shot:

**EDIT 5:**

```
    private void DrawSelector(SpriteBatch spriteBatch)
    {
        device.Clear(ClearOptions.DepthBuffer, Color.White, 1f, 0);

        itemRender.Render(world.player.ItemSelector);
    }

```

...

```
    public void Render(ItemSelector itemSelector)
    {
        view = itemSelector.View;
        projection = itemSelector.Projection;

        effect.CurrentTechnique = effect.Techniques["Block"];
        effect.Parameters["World"].SetValue(Matrix.Identity);
        effect.Parameters["View"].SetValue(view);
        effect.Parameters["Projection"].SetValue(projection);
        effect.Parameters["Texture"].SetValue(Variables.TILE_ALAIS.SheetTexture);

        int counter = 0;

        foreach (CubeObject cubeObject in itemSelector.CubeObjects)
        {
            effect.Parameters["World"].SetValue(Matrix.Identity * Matrix.CreateRotationY(MathHelper.ToRadians(45f)) * Matrix.CreateRotationX(-15f) * Matrix.CreateTranslation(100 + counter * 80 + itemSelector.ScrollOffset, 80, -10));

            if (counter == itemSelector.Index)
            {
                effect.Parameters["World"].SetValue(Matrix.Identity * Matrix.CreateRotationY(MathHelper.ToRadians(45f)) * Matrix.CreateRotationX(-15f) * Matrix.CreateScale(1.8f) * Matrix.CreateTranslation(100 + counter * 80 + itemSelector.ScrollOffset, 80, -2));
            }

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, cubeObject.vertices.ToArray(), 0, cubeObject.vertices.Count, cubeObject.indices.ToArray(), 0, cubeObject.indices.Count / 3, VertexPositionTextureLight.VertexDeclaration);
            }

            counter++;
        }
    }

```

Any ideas?

**Edit 6:**

Also when I draw my block selector - it is drawn right before the HUD is - this is what happens:

# Answer
> 4 votes
If all you want is for those objects to be unaffected by the camera, why don't you just **use a separate view matrix** for them (one that never changes)? Simple!

And since you probably want them to always appear on front of everything else, don't forget to clear the depth buffer, or use separate render targets.

**Edit**

> I just realised a problem with this approch. Each object, has a slightly different rotation when it is further to the left/right of the screen any ideas?

They don't have a different rotation, that's just the effect of perspective. Use an orthographic projection instead if you don't want it to appear that way.

**Edit 2**

1. Download this sample (random 3D sample I downloaded).
2. Replace the content of HeightmapCollision.cs with this
3. And it should look just like this video.
4. Compare with yours, that's all I can say. I did exactly as I described above and it works.

The only relevant differences to the code compared to the original sample are:

```
fixedViewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up);
fixedProjectionMatrix = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1f, 1000f);

device.Clear(ClearOptions.DepthBuffer, Color.White, 1f, 0);
for (int i = 0; i != 5; ++i)
{
    Matrix worldMatrix = Matrix.CreateScale(2f) * Matrix.CreateRotationY(angle) * Matrix.CreateTranslation(100 + i * 200, 100, -10);
    DrawModel(sphere, worldMatrix, fixedViewMatrix, fixedProjectionMatrix);
}

```

And it was working even without clearing the depth buffer, so I'm no longer sure if that's even necessary, but added it just in case.

---
Tags: xna, shaders, matrix, coordinates, voxels
---


# Question
Title: Are there any good engines for isometric collision detection and platforming?
I've decided to resurrect an old game idea I had years ago. I currently have zero experience with programming, but I'm going to begin studying either C#, Python or both in the near future.

The issue I'm currently facing is that what I plan on making is an isometric Metroidvania-type game, similar to that old GBA title *Scurge: Hive* on a very basic level. Naturally, this means that there will be some emphasis on platforming. The problem is, I hear that programming those kinds of physics into a 2D game is highly impractical. General consensus, from what I've seen, seems to be that it's easier to just make isometric games in 3D so that programming collision detection and the like is simpler.

I really want this to be a 2D game, as I have absolutely no experience with 3D modeling. Yet I also don't want to have to build the entire underlying physics engine from scratch. I've looked around a bit and there don't seem to be any engines for this type of game that are compatible with C# or Python. There are isometric engines, but most seemed to be geared toward 3D games and RPGs.

So I guess what I'm trying to ask is, are there any engines available that would make it easier to program an isometric 2D platformer? Or would I have to do the collision detection coding myself?

(As an aside, while I'm considering both #C and Python, I'm leaning toward Python due to the fact that it's multiplatform and apparently better for beginners. So please take that into consideration if possible.)

**Edit:** After some more research, I've chosen to go with Lua, but I may still study Python and C# as well if possible. Hopefully I'm not biting off more than I can chew.

# Answer
> 12 votes
Whoever's general consensus you have, is wrong. There is nothing special needed to implement collision detection in an isometric game. It is no different from implementing collision detection in Robotron or even Pitfall. This is a common misconception, and one that often leads to a lot of struggling. On contract recently I met a senior developer who couldn't for the life of him fix a broken isometric engine's collision detection, and furthermore refused to rewrite the thing, because he didn't grok what I am about to tell you.

Consider an isometrically-rendered space. Is that space, the actual space, *what you see on the screen*? No, that is just a representation. In reality it is a set of underlying data in memory, and that data is a 2D array (or a set of them, layered by height). *From a visual perspective*, that space could just as easily be imagined as an orthogonal top down view (a la Robotron), with left=-x, right=+x, up=-y, down=+y, -z=out, +z=in, and it is pragmatic to visualize your data structure as such. In other words, *imagine* the game as orthogonal top-down, do all physics and other logic in that mode, but then perform transformations into an isometric format *for the purposes of rendering only*. I advise you to first render as vectors i.e. using points/lines/squares: An article like this one will help you get the basics right for point placement using isometric transformations, and subsequent line drawing between those points. Then after some tweaking you will see from your drawn lines, what your isometric tile sizes and character sizes should be. You could then take screenshots (or save bitmap data to disk) and use these ("diamonds") as the bases for your sprites.

The key distinction to be made here is that what you *see* is not the data model of your game. *It is only a representation* thereof. No special engine is required to do any of what you want to do, easily.

---
Tags: c#, 2d, collision-detection, python, isometric
---


title: How should I manage level progression?

text:
# Question
Title: How should I manage level progression?
In my code, I just have a Level class right now in the main game loop that just blits a background and spawns some enemies for testing purposes...But I can't figure out how to go about implementing multiple levels and level progression. What is the best way to manage multiple levels and level progression in a game?

I'm thinking that I would make the Level class just read level data from a file, and create a Level vector...But I'm not sure if that's the best way to do it.

# Answer
> 4 votes
You'd handle this using a state machine, and a couple of variables.

Something like this:

```
enum GameState
{
    Intro, // title screen
    Running, // gameplay running
    Cutscene, // showing cutscene
    End     // game over
} ;
// the variables:
GameState gameState = GameState::Intro ; // maintain the current gamestate.
int cutSceneNo = 1 ; // what cutscene we're currently displaying
// (only used WHEN in GameState::Cutscene)
int levelNo = 1 ; // what level we're going load and play next
// (only used WHEN in GameState::Running)

```

It's really simple. Have a different "state" for every "state" the game can be in! This gives you a really easy way to transition from `Intro` screen to `Cutscene` to `Running`.. see pseudocode below.

### Main loop:

```
while( 1 )
{
    update() ;
    draw() ;
}

```

Now, in both the `update()` and `draw()` basic functions, the decision what to do can be made based on `gameState`:

### Update function: look at `gameState` to figure out what to do. Include code to watch for key events that will transition to the next state.

```
void update()
{
    getInput() ; //read current state of the keys.. used below

    switch( gameState )
    {
        case GameState::Intro:
          if (any key) was pushed
          {
            cutSceneNo = 1 ;  // ON FIRST CUTSCENE
            gameState = GameState::Cutscene ; // display a cutscene next time
            // the update() function is called
          }
          break ;

        case GameState::Cutscene:

          runCutscene() ; // RUN THE CUTSCENE, whatever that entails

          // WATCH FOR EVENTS THAT WILL CAUSE TRANSITION
          // TO NEXT STATE (this code could actually go in runCutscene())
          if( cutsceneDone OR (any key) was pressed )
          {
            LOAD_LEVEL(   levelNo   ) ; // LOAD THE NEXT LEVEL
            // FROM A FILE OR WHATEVER, WHEN THE CUTSCENE IS DONE
            // Once that's done and the level is loaded:
            gameState = GameState::Running ; // jump into game when cutscene done
          }
          break ;

        case GameState::Running:
          run() ; // run the game itself
          // if you die in game, then transition to GameState::End
          break ;
    }
}

void run()
{
    // here you run the game.
    // if the level is DONE, increment cutSceneNo
    // and transition to cutScene state.

    // RUN GAME LOGIC BASED ON LOADED LEVEL

    // now if the player FINISHES the level, transition
    // to next cutscene
    if( player finished level )
    {
        cutSceneNo++ ;
        gameState = GameState::CutScene ;
    }
}

```

### Draw function: also look at `gameState` to figure out what to do

```
void draw()
{
    switch( gameState )
    {
        case GameState::Intro:
          drawIntro() ;
          break ;

        case GameState::Cutscene:
          drawCurrentCutscene() ;
          break ;

        case GameState::Running:
          drawGame() ;
          break ;
    }
}

```

So the idea is, you maintain enough state variables so the game knows exactly what it's doing at each moment. Depending on `gameState`, different things happen in the `update()` and `run()` loops.

# Answer
> 2 votes
I think it entirely depends on the amount of data (and memory-resources available) you'll have to load for each level. If your level-data alone is huge, then your level-progress might be just an array (or vector) of files:

```
levels = { "Level1.dat", "Level2.dat", "Level3.dat" };

```

Then you keep track of level-index and load the level file at the current index. If the level is complete, you load the level at the given index.

If you always use the same assets and the level-data easily fits into memory, you could preload everything. But since you have intermediate cut-scenes, that isn't really necessary as you can use them to load the next level.

Another idea would be to have some sort of "story" or "progress" data file you load. Sometimes you need meta-data that is external to your actual level data.. for example if you have a time-limit on the level. I prefer to not have this time-limit inside my level-data, but rather separate from it, so that I can easily tweak it. Also if your level should have a name, you could put it into the "story" data-file, and this could easily be translated.

Here's how such a story-file could look like (JSON):

```
{
    "progress" : [
        {
            "Type"      : "Level",
            "Title"     : "Hello world!",
            "Data"      : "level1.dat",
            "Timelimit" : 30000
        },
        {
            "Type"      : "Cutscene",
            "Title"     : "You completed level 1!",
            "Text"      : "I completed level 1, but then I took an arrow in the knee"
        },
        {
            "Type"      : "Level",
            "Title"     : "Arrow begone",
            "Data"      : "level2.dat",
            "Timelimit" : 40000
        },
        ...
    ]
}

```

Having such a story- or progress-file will easily allow you to swap and re-arrange levels and cut-scenes. If your cut-scenes are really simple, you could even get away with something like above, where the entire data of the cut-scene is in the story-file. Otherwise you might just have to reference a file for the cut-scene. Also you're free to add more meta-data. For example you could add an array of resources to load for each level (if that isn't already specified in your level file).

So in your game you would load the story-file and then move from one entry to the next...

---
Tags: c++, sdl, shoot-em-up
---


# Question
Title: Should SIMD be used by people who are new to game development?
I have been learning game development, using C++ and OpenGL, for about 4-5 months. Before that I used to program in C# and the .NET platform(about a year). So, I consider myself new to game engineering and software development as whole.

Recently I read about SIMD math. I found it interesting and started wondering if it was good to use it in my math library. But, considering that I have so much to learn and I haven't even laid the foundations of my knowledge of game development, should I explore it in depth and start using it? Or should I wait until I really start to need it?

# Answer
This is really a matter of opinion, but I think SIMD can safely be postponed. It'll probably be a long time before you're doing so much math on the CPU that you'll need it. Besides, there are probably vector/matrix math libraries out there that have SIMD built-in already, and if you use one of those, it should "just work" and you'll have very little need to dig into the details.
> 5 votes

# Answer
SIMD in and of itself is straightforward to use, provided you are even mildly experienced with C++. The problem here is that not every problem *lends itself* to SIMD calculations. You need to appreciate that using SIMD to save time naturally assumes that you have a set of operations all of which are the same in nature (eg. div, sqrt) and all of which may be executed in parallel. Given the nature of real-time simulations (games), I would furthermore assume that there would be some degree of repetition of these set-operations several times per second for it to be worth considering using SIMD ops at all, as well. Two examples are:

* Ray packets in RTRT (real-time raytracing)
* Pixel operations (as found on the GPU which is massively parallel -- originally more SIMD but things have moved toward MIMD)

SIMD is never useful where you need the results of one operation to calculate the results of the next; performing physics stepping for an entity is an example of where SIMD would not be useful.
> 1 votes

---
Tags: c++, opengl, mathematics, simd
---


# Question
Title: How to calculate FOV with four-walled tiles?
I'm working on a 2D tile-based game. I'm trying to calculate FOV and I've implemented walls so they don't take up an entire tile. Instead, they just take up a side of each tile. Similar to:

```
class Tile {
    bool northWall;
    bool westWall;
}

```

Most of the algorithms I've been looking at expect walls to take up a full tile, and the check to see if a tile is blocking tiles behind it is trivial. I'm having trouble wrapping my head around this. I've got an implementation of Recursive Shadowcasting right now, but not sure how to write my is\_blocked() function. Can anyone give me some advice?

# Answer
Given that your walls are not cells, you will need a way to identify occluders as you raymarch. The easiest way to do this would be, as you step from one cell to the next, check whether there is a wall on the boundary you are crossing from tile A to tile B, and store the result for use.

Let's look at three different approaches to clarify this for you.

**Recursive shadowcasting**, your current algorithm. You can never have "matchstick" (infinitesimally thin) walls. Why? Because the order in which the algorithm iterates through cells is *not the same direction the ray would come from in a geometrically-correct lighting model*, that is, it's an octant-based *approximate*. Recursive shadowcasting is a simplification of the problem, and by breaking some of the fundamental requirements for that "shortcut", the algorithm simply won't work. So although you may place individual walls at first, these edge-walls must, *before the algorithm is run*, be connected in loops. Otherwise, due to the direction in which the algorithm iterates, it will simply miss some walls altogether. Essentially the problem is one of quantisation and resolution -- the walls becomes 0-dimensional from certain angles and thus cannot be detected by the algorithm.

**2D DDA raycasting**. This is what is used in Wolfenstein and Doom, only it looks much fancier. Cast a ray along every possible path, using DDA, after selecting your angular resolution, eg. if you want one ray per degree, use 360 rays. You can use matchstick walls if you want to, but there is a caveat: While this method is geometrically correct in terms of ray direction, due to resolution limits of the underlying grid, it may miss matchstick walls at distances relatively far out from the viewer, as the rays diverge.

**Back-projection**. You will never lose matchstick walls, because instead of evaluating the lighting based on a grid, you are evaluating every vertex of every polygon (or edge in the case of your matchstick walls) in that space, and backprojecting them to the light source. Note however this will require you to construct actual polygons as lists of edges if you want to do the occlusion correctly, because you will need to intersect rays that are cast back from each vertex, with potential occluder that lie in front of them (i.e. between them and the light source). The biggest problem here is that arbitrary geometry leads to potentiall high complexity of the area to be evaluated for lighting, unless of course you still use a grid as your guide for vertex placement.

**My advice?** Use recursive shadowcasting if you are at all willing to accept using cells, because it's a shortcut that relies on this to work at all and is simple to implement and understand. Use raycasting if you can accept some loss of accuracy out at a certain distance from the light source. If all other methods fail and you need the highest possible degree of accuracy, use vertex-based back-projection.
> 3 votes

---
Tags: tiles, lighting, projection, line-of-sight, raycasting
---


title: Trade shows and competitions in the UK

text:
# Question
Title: Trade shows and competitions in the UK
So I'v been hobby programming games for a few years now but never released anything.

This year I was thinking about deepening my knowledge of the industry and doing some networking buy going to some trade shows and maybe taking part in a contest.

My first instinct was try E3 but that is not open to the public and is in america :(

So what I want to know is what shows and contest are held in the UK for game development.

I have found this difficult to Google when you as I am not sure what I am even looking for so if anyone has any recommendations. Ideally the show would have elements dedicated to design and development of games instead of just previewing the new releases.

Any information on any game competition would be great no matter the level.

# Answer
There's a few things to mention. First, do some research to see if there's a game development meetup locally, googling `<city name> game developers` is a good start. Doing that will probably get you something like London Indies. Side note: if there's no local group near you, why not start one? If you live in any decent sized city, there's bound to be 10-30 people interested in game development in your area.

Second, participate in events like Global Game Jam, there's over 100 sites around the world, and it's a great way to meet other local people (and ask them about any other events that might exist). If there's nothing close to you, then sign up to host a site next year!

Finally, for a wider "Europe" set of events, the Copenhagen Game Collective and GDC Europe are two things worth checking out, as they're both ways to meet other game developers and learn about the industry.

Finally finally, don't forget the online option. Various game developers use twitter, google+, and even facebook as a way of connecting and talking to people, in addition to online game jams like Ludum Dare.
> 2 votes

# Answer
I don't know about all the networking, but one thing you should do is to release something. You can make a simple website and offer your games for free, you can upload stuff to one or more of several different app stores, charge a little if you think your game is worth it.

Don't ask the industry to let you in, just be part of it, at whatever level you can manage.
> 1 votes

# Answer
AFAIK the first four, at least, are international/online competitions.

Go to it, my son!
> 0 votes

---
Tags: game-industry, competition
---


# Question
Title: Bezier Curves for visual programming node connectors
Probably everyone is familiar with all kinds of visual node based programming tools like HLSL editor in Visual Studio 2011 or UDK engine Kismet/Material editors. My point of interest are the connectors between the nodes. Basically those are implementation of Bezier Curve algorithms. Those are not hard to put into code.

How I make each connector line bend into right direction and with the right angle when it is being connected between two points not laying on the same line?

# Answer
> 6 votes
Start with something simple. Use cubic bezier curves (2 control points), with the control points directly pointing out from the control nodes by some fixed distance. That should be good enough.

# Answer
> 1 votes
I would personnaly use a cosinus. Why bother with a complicated and costly bezier curve ?

---
Tags: software-engineering, beziers
---


# Question
Title: How can I achieve glow effects similar to those in  WoW?
I've recently implemented a glow effect using a gaussian filter and could not get the full effect I was wanting. I'm curious to know if how certain glow effects are done in WoW. Like this image:

Around the sword is a really nice glow effect. How might this be done? Also, sometimes in WoW you see these glow effects take a life of there own. Like the purple glow in this pic:

Are these accomplished with particle effects? Are there any good resources/tutorials that could help with someone to learn how to do these effects?

# Answer
> 4 votes
Use sprites textured with glow textures, with an additive blend. The additive blend is crucial here. This is how most glowing effects are achieved.

Additive is the synthesis of lights, actually. You don't need an alpha mask for textures used with an additive blend. The RGB mask is used as the alpha layer, where black is fully translucent and white fully opaque.

# Answer
> -2 votes
for a glow effect ,create the glow as normal image (in maya) in Targa or whatever alpha support extention then load it to your game draw it as square that always face the camera from its place (you can also change the texture with time);

---
Tags: particles, glow
---


# Question
Title: Good game design process for a do-it-all programmer
I am pretty new in game development - on Android platform and thinking about one-man game development. I know I can't professionally do everything such as graphics, sounds, and music but I think I can worry about them later once I finish its coding.

My current road block is setting up game design process. I've read some books and lecture notes on game design such as A Theory of Fun, and Book of Lenses, but still not sure about the process.

Of course, making game ideas is kind of separate process in long term so I can assume I already have an idea for a game in this question. But for conceptualization, what can I do? I think people usually make a design document and story boards for this. But for android platform, I am not sure design document is necessary - maybe design summary would be enough. In that case, would story boards (or doodles of game screens) be enough for design process? What else do I need to do in the game design?

# Answer
I've made a few mobile games, made a little bit of money on the apple app store, and have started to almost exclusively use this process. But as all development processes go, you will develop your own after a while.

This is a copy from an email I sent to one of my team members.

1. Write out a short description of the game
2. Write out the main gameplay events
3. prototype the ideas on paper and see if they logically make sense. "Play" through the events on paper
4. Write a basic use case for each of the events
5. Draw some concepts of the artwork for the game
6. Draw use case diagrams for each of the basic use cases
7. Detail the required system interactions to make the use cases possible (don't skip any interactions that seem like black magic "click the screen and unicorn spawns on the terrain". There are a lot of data transformations going on to get the unicorn to the exact terrain location under the mouse.)
8. start writing out a class diagram (avoid God classes such as "GameCoordinator" and instead make a class for each logical object and break apart as much of the interaction between these classes as you can, this was a painful lesson)
9. make a playable demo of the game with limited functionality
10. have some friends play and break it
11. iterate...iterate...iterate on gameplay events
12. draw out the interface.
13. make the interface work
14. start sending out review requests to all of the mobile app review websites
15. polish the interface
16. test the hell out of it on MANY mobile devices, not just yours
17. cry at the bad reviews
18. fix the big problems
19. smile at the good reviews
20. Update the game

All of that being said, you probably won't appreciate this type of plan until you rapid prototype your first few games. I'm torn between telling you to use this plan and saying just prototype it and iterate as Tetrad said. I will say, avoid getting too stuck on design processes for your first game or two. **Coming up with a design process is less significant than the experience you get in learning why you need to have a process.** Still I wish I had a process for my first game because I had to refactor most of the code once it started making money and I needed to update a few things.
> 45 votes

# Answer
Personally I would start with just rapid prototyping.

For smaller games, design docs are really only good at forcing you to think about the problem as a whole. There isn't any reason to write everything down if you can encapsulate it all in a prototype.

Get some game ideas in your head, and implement the core loop. If there seems like there's something there, iterate on it. When you have something fun, build the boring parts around it (menu screens, options, etc.) and ship it.
> 28 votes

---
Tags: game-design, process
---


# Question
Title: Can I achieve a torchlight effect (lighter area around a light source) in a 2D game?
I am thinking of writing myself a simple 2D game. It will not shine with perfect graphics or gameplay at first, but I'd consider it my first step in PC game development. So, imagine such simple sprite-based 2D game (like Heroes IV or Startcraft BroodWar).

I want the gameplay to support day/night with the according lighting changes and at the same time it will be madness to have to create sprites for every lighting nuance. So, I decided adding a semi-transparent layer on top of other objects will be enough.

The issue with this solution is if I have a light source object in the game (like the hero wearing a torch, or a burning building), there must be a lighter area around it, right? Since I am putting my semi-transparent layer over everything, how would you suggest to achive the torchligt visual effect I want? Maybe redraw that layer adding 'gaps' or differently colored areas based on the lighting effect?

# Answer
I don't know what you're programming in, but this is how I handled it in XNA:

1. On the draw call, a `List<Light>` object is created/cleared.
2. During the tile draw loop, each tile is checked to see if it has any Lights associated with it. If it does, the `Light` objects are appended to the `List<Light>`.
3. The tiles are drawn onto their own `RenderTarget2D`.
4. After the tile loop, the list of `Light`s is iterated through and drawn on their own `RenderTarget2D` using a texture I made that looks like this:
(Note: I used the R, G and B values here but you should probably use the alpha channel in your actual texture.)
5. Using a custom shader, I render the tile surface to the screen and pass in the lighting surface as a parameter which gets sampled for the "darkness" value at each pixel.

---

Now, there's a few things to note:

**Regarding Point 4:**

I actually have two custom shaders, one to draw the lights to the lighting render target (step 4) and another to draw the tile render target to the screen using the lighting render target (step 5).
The shader used at point 4 allows me to add (what I call) a "luminosity" value. This value is a `float` that gets multiplied against each pixel in the texture before it's added to the render target so that I can essentially make lights brighter or darker.
At this point, I also take into account the light's "scale" value which means that I can have large or small lights using only one texture.

**Regarding Point 5:**

Think of the lighting render target as essentially having a value for each pixel from 0 (black) to 1 (white). The shader essentially multiplies that value against the RGB values for a pixel in the tile render target to make the final drawn image.

I also have some more code here where I pass in (to the shader) a value to be used as the day/night overlay colour. This is also multiplied into the RGB values and included in the lighting render target calculations.

---

Now, this won't allow you to do things like block light from going around objects and whatnot but, at least for my purposes, it's simple and works well.

I've written more detailed blog posts here and here which may help you. I don't have time right now, but if you want I can go into more detail here on gamedev.

Oh, and here's a look at it in my map editor:
> 12 votes

# Answer
Normally, lighting in 2D games is done by having a Normal Map for all of your sprites, then calculate the 3D lighting effects on your 2D sprites. This is known loosely as "2.5D". I would however *not* recommend doing this in your first game as it is complex.

Here's an awesome video of someone who has done this in XNA: http://www.youtube.com/watch?v=-Q6ISVaM5Ww

That said, there are probably ways to cheat and get a pseudo-lighting system that could work with various assumptions.
> 9 votes

# Answer
It's hard to suggest an approach if you're not completely specific about the effect you're trying to achieve. Details such as if the lights should be obstructed by the environment or not, what's the point of view of your game, to what extent should the light interact with the environment, etc.

I'll drop my two cents though. See if this tutorial by Catalin Zima entitled Dynamic 2D Shadows fits your bill. As you can see, the light has a radius and does not go through obstacles. You could animate the radius and the color a little to make it look closer to a real torch light.

In this case, the light acts as sort of overlay on top of your scene, but does not interact with it to the same extent as in John's example, although it does take obstacles into consideration.

**Edit**

Catalin links to another article he used as reference, but the link is broken. Here's an updated link.
> 5 votes

---
Tags: 2d, lighting
---


# Question
Title: How can I evenly fan out a hand of cards?
Given a set of playing cards (rectangle images with a width and height) how can I rotate and position each one so that they appear in a 'fan' pattern, much like you would hold a hand of cards in real life. What math is needed to do this?

**UPDATE**

Here is the final, in browser implementation in JavaScript: https://cosmicrealms.com/blog/2013/03/16/hand-of-cards/ and http://jsfiddle.net/tyyvk/108/

# Answer
> 30 votes
**Theory**

Since you didn't specify in what platform you're implementing this, I'll give a description of the algorithm in a language-agnostic way:

1. First **stack every card** on top of each other by giving them the same initial position.
2. Then for each card **apply a rotation** (usually *centered around one of the bottom corners*, but moving this origin around will essentialy allow you to tweak the look of the fan).
3. **Increment the angle of rotation between each call**, depending on the number of cards and how much you want them to be spread.

That the *rotation is centered around one of the card's bottom corners* (or near the corner) should be evident from looking at it:

---

**Implementation**

As for how to implement this, it depends on your platform. On XNA you can simply use the Origin parameter of `SpriteBatch.Draw` to change the center of your rotation.

Here's what I got with the following code (with a few tweaks to the origin to make it look better - basically the origin starts near the right corner and ends up near the left corner):

```
int cards = 20;
float range = MathHelper.ToRadians(90);
float initialAngle = MathHelper.ToRadians(-45);
float increment = range / cards;
Vector2 leftCorner = new Vector2(0, texture.Height * 0.9f);
Vector2 rightCorner = new Vector2(texture.Width, texture.Height * 0.9f);
Vector2 fanPosition = new Vector2(400, 300);
spriteBatch.Begin();
for (float angle = 0; angle < range; angle+=increment)
{
    float cardAngle = initialAngle + angle;
    Vector2 cardOrigin = Vector2.Lerp(rightCorner, leftCorner, angle / range);
    spriteBatch.Draw(texture, fanPosition, null, Color.White, cardAngle, cardOrigin, 1f, SpriteEffects.None, 0f);
}
spriteBatch.End();

```

And the result:

---
Tags: mathematics
---


title: Game State Management using Lua

text:
# Question
Title: Game State Management using Lua
I want to be able to (only) define game states using Lua script, but I'm not sure how I should do it. Here's what I have in mind currently:

For each state, I will create a .lua file that contains a class (table) that has the same name as the file name. Each table must have a set of event handlers: onEnter (called when the state is entered), onUpdate (called every frame) and onExit (called when exiting the state). So if I want to have a MainMenuState, I will have a file called "MainMenuState.lua" which will contain something like this:

```
MainMenuState = {}

MainMenuState["onEnter"] = function()
end

MainMenuState["onUpdate"] = function(elapsedTime)
end

MainMenuState["onExit"] = function()
end

```

Defined states will be exposed to the game engine via a singleton StateManager class. StateManager will have a function that registers a state under a unique name:

```
void registerState(string stateName, string fileName);

```

State registration will be done in script by placing the registration codes inside an init script that is called once after the game engine is initialized:

```
--init.lua
--Register all the states needed by the game
StateManager:registerState("SplashScreen", "SplashScreen.lua")
StateManager:registerState("MainMenuState", "MainMenuState.lua")
StateManager:registerState("InGameState", "InGameState.lua")
-- etc etc

```

StateManager will also keep track of which state is currently active and also handle state transitions:

```
//cpp
void changeState(string state);

--lua
StateManager:changeState("PauseMenuState")

```

# Answer
It's not entirely clear what you're asking, but there's nothing inherently "wrong" with the way you are structuring your state machine. As long as it fits the task at hand, any implementation can be considered "correct".

One change I would suggest making is to allow the states themselves to be instanced, so that you can store state in your instance. This can be as simple as:

```
SplashScreen = {}
local instance = setmetatable({}, SplashScreen)

SplashScreen.createInstance = function(...)
    local instance = setmetatable({}, SplashScreen)
    instance.endTime = 5.0 -- set instance data
    return instance
end

function SplashScreen:update(elapsedTime)
    if elapsedTime > self.endTime then -- use instance data
        changeState('MainMenuState')
    end
end

```

Note that, due to the `setmetatable` call, `instance` tracks all of your state's functions; so your 'current state' is really just an `instance` ref in your `StateManager`:

```
function StateManager:changeState(stateName, ...)
    local stateTable = --[[ get state from file ]]
    local instance = stateTable.createInstance(...)

    self.currentState = instance
end

function StateManager:call(funcName, ...)
    local fn = self.currentState[funcName]
    fn(self.currentState, ...)
end

```
> 5 votes

# Answer
I preferred to use numbers with my state systems. It's not the best way but it works great for me.

```
state = 1
while true do
    if state==1 then
       if 1=1 then
          state=2
       end
    end
    if state==2 then
        if 2=2 then
          state=1
        end
    end
end

```

works for me :)
> -2 votes

---
Tags: c++, scripting, state, lua
---


# Question
Title: Understanding log/exp formula for RPG experience
While looking for examples of RPG experience formulas I came across this one How to create adjustable formula for RPG level up requirements?, and I would really like to figure it out because I don't seem to get the same results. I'm trying to understand the maths behind it because actually we are using UDK and Unreal scripts for our project.

Thank you in advance for your time.

# Answer
When used together with `exp`, the `log` function is commonly understood as the natural logarithm. You are actually using base 10 logarithm (which would be `log10` in C++).

Fortunately you can get the same results using base 10 logarithm, provided you also use base 10 exponent: just replace every occurrence of `exp(X)` with `10**X` (10 to the power of `X`) in the formulas.

UnrealScript’s logarithm and exponent functions are called `Loge` and `Exp`.
> 9 votes

---
Tags: mathematics, udk
---


title: Display Lists in OpenGL

text:
# Question
Title: Display Lists in OpenGL
I heard that there was a faster method of displaying vertices, rather than recreating the GL\_TRIANGLES, each time the scene is drawn. I thought I read somewhere that this method was obselete. Why would the OpenGL group remove something that was faster? Even if it is obselete, how would I go about implementing this?

# Answer
The main issue is that OpenGL 3 deprecates immediate mode rendering, which means you can't use `glVertexXX` etc to draw your triangles. If you aren't using immediate-mode rendering, display lists don't help you get any additional performance.

What you should be using are Vertex Buffer Objects (supported since version 1.5). As with display lists, VBOs allow you not to re-send the entire scene to the GPU every frame, resulting in a huge performance boost.
> 8 votes

---
Tags: opengl, 3d, optimization
---


# Question
Title: How should I handle shared classes between the Game project and the Content Extension Library?
I've been using XNA for a while but recently I've needed to write a content extension library which I haven't done before. I need to import a *TextureAtlas* class from a file that is exported by a tool I wrote. The output of my editor is a serialized XML file that contains a list of all *StaticImages* and *Animations* in the *TextureAtlasFile* class that its serialized from. In my solution I have the *TextureAtlasContentLoader* project which holds all of the classes that I will need for the texture atlas both in game and for loading the actual content. The importer deserializes the xml back to a *TextureAtlasFile* and the processor converts it to a *TextureAtlas* to return after it is loaded.

The problem is that I have no idea how to share the classes between the content extension project and the game project that will be using the *TextureAtlas* class. I've tried referencing the content extension project in the game project and that works fine to get me pass compiling but it throws a *ContentLoadException* exception when I call

```
textures = Game1.content.Load<TextureAtlas>("MainMenu");

```

saying

> Error loading "MainMenu". Cannot find type Client.Render.TextureAtlas, TextureAtlasContentLoader, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.

The only other clue to whats wrong I have is a warning while compiling that says/

> Warning 2 The referenced assembly "Microsoft.Xna.Framework.Content.Pipeline, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553, processorArchitecture=x86" could not be resolved because it has a dependency on "Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project. Client

which leads me to believe I'm not supposed to reference it in the game project. So to summarize my question, how do I handle my *TextureAtlas* and *TextureHandle* class that both the content loader and the game project need without causing errors?

# Answer
You could put your shared type in another project (game library) that is referenced by your content pipeline extension project and by your game project.

You might like to create `TextureAtlasContent` and `TextureHandleContent` classes, and have your content pipeline use those, with your game using your `TextureAlias` and `TextureHandle` class (that way there's no need for an extra project). It's what's done often for classes that use the graphics device in some way (Texture2D and Texture2DContent for example).

---

Shawn Hargreves' blog has some excelent posts on the topic of the content pipeline (as well as many other things):

Shawn Hargreaves Blog Index #Content Pipeline

There are also many good posts on the App Hub forums, there's a dedicated section for the content pipeline:

XNA Framework Content Pipeline - App Hub Forums
> 4 votes

---
Tags: xna, c#, xna-content-pipeline
---


# Question
Title: How can I make a sprite move in the direction it's facing using radians?
I am using PGELua for the PlaystationPortable. I would just like to know how to make a 2D sprite move in the direction that the sprite is facing.

When the sprite is blitted to the screen it should be heading down the y axis (like it's moving up the screen) but it doesn't appear to be working that way. As far as I am aware, the angles of the images use radians for the rotations.

I have this in a function

```
function FUNC_MOVE_SHIP(speed,angles)
    VAR_SHIPX = VAR_SHIPX + pge.math.sin(angles) * speed
    VAR_SHIPY = VAR_SHIPY + pge.math.cos(angles) * speed
end

```

and I call it in my main program like

```
    FUNC_ST_DR()
    if pge.controls.held(PGE_CTRL_LEFT) then
        VAR_SHIP_ANGLE=VAR_SHIP_ANGLE-0.01
    elseif pge.controls.held(PGE_CTRL_RIGHT) then
        VAR_SHIP_ANGLE=VAR_SHIP_ANGLE+0.01
    end
    FUNC_MOVE_SHIP(VAR_SHIP_SPEED,pge.math.rad(VAR_SHIP_ANGLE))
    SHIP_11:activate()
    SHIP_11:draweasy(VAR_SHIPX,VAR_SHIPY,pge.math.rad(VAR_SHIP_ANGLE))
    FUNC_EN_DR()

```

# Answer
A common problem with using radians is that they start to the right. Look at this picture (from Wikipedia):

As you can see, it starts at `0` on the right of the circle and goes counter-clockwise around the circle until it hits `2 * PI`. So if your sprite isn't pointing to the right with a rotation of 0, you might have to add some constant. Eg. if your sprite is pointing up, you have to add `PI * 0.5` to the calculated angle. Also, instead of adding and subtracting `0.01` from the angle, I'd rather choose some fraction of PI instead. Eg. `PI / 90` equals 2 degrees of rotation per update.
> 3 votes

# Answer
I believe that your movement formula should only work if the angles value is in degrees. To convert radians to degree simply multiply the radian value by 180 and divide it by pi.
> 0 votes

---
Tags: 2d, rotation, lua
---


# Question
Title: 2D helicopter game, how to create corridor walls?
I'm looking into adapting the classic "helicopter" game (i.e. http://www.addictinggames.com/helicopter.html), but I haven't yet figured out how to create the walls-generation engine.

Any pointers into the pseudocode? I'm not so interested in the objects in the middle- only the methodology for generating the sides in a way which increases with difficulty (closes in more, has more unexpected curves) as the game progresses.

# Answer
You could use 1D Perlin noise for that. Here's an image of 2D noise. I took samples where the red line is and multiplied them with some constant to get the green line.

The constant you multiply the values with is going to determine the height of the noise. So you could easily ramp up the difficulty. Another benefit of Perlin noise is, that it can generate tileable noise, so that you can build a seemingly endless level.

If you want to create a bottom and a ceiling, it's important that you don't generate any impassable areas. The easiest way would simply be to use the "upper" part of the noise (eg. `1.0 - noiseValue`) as ceiling and the lower part (`noiseValue`) for the bottom (with some offset in between of course). If that's looking too dull, you could also consider two close samples, eg. imagine another red sample line one or two pixels up or down. This will give a similar, but not identical wave.
> 17 votes

---
Tags: 2d, mathematics, algorithm
---


# Question
Title: How can I get involved with open source game projects?
I have a limited experience in game development and would like to get involved with open source game project. Where should I look and how should I begin?

# Answer
Without referring to any of my previous projects, I can say that I've been involved with a great deal of open source activities, game-related and otherwise, and by and large I have thoroughly enjoyed the ride. Right now I'm a manager with the jMonkeyEngine project. I'll be glad to type up somewhat of an 'introduction to open source games', but bear in mind this will by no means be an exhaustive list of resources.

I highly recommend checking out similar pages for all of the links I provide.

## Free, open source etc. - The subtle differences

It's worth merely noting that there are some differences to terms like 'free' (vs 'gratis'), 'open source', and 'free software'. The GNU project has a good but somewhat one-sided take on it, titled Open Source Misses The Point. Simply put though, I'd say the most damaging misconception about open source is that you're not supposed to make any money off of it.

Point is, even if you're giving away your code as well as your art assets (though copyrighted art assets could be a good way to make an essential part of your game proprietary, without really damaging its technical 'openness') for free, that doesn't mean you can't commercialize other parts of your project.

There's another gamedev thread here that'll hopefully bring in many good ideas on how to commercialize a free game.

## Independent preparation

If you want to sharpen your talents before getting involved with a group of fellow developers, 'try make your own game' is a no-brainer, and there's no shortage of open source engines (see devmaster.net/engines and wikipedia.org/wiki/List\_of\_game\_engines). If you're looking for a little motivational push though, there's nothing like a little bit of competition:

* Ludum Dare \- Frequently hosted 48h game competitions.
* GameJolt \- Infrequently hosts uniquely themed competitions. You can also upload your finished games there for free promotion.
* GameCareerGuide's Game Design Challenges \- Although not always requiring programming, GCG's weekly challenges open up a lot of opportunity for networking and unique concepts.

## Find a project

There are plenty of places to look, and it's been a while since I was on the lookout, but I reckon most of the hobbyist projects (because that's what every open source game project is right now) make an appearance at either of these waterholes:

## Choose a project

Choosing the right project that matches your particular skillset and interests (no one's gonna want to work with you if you're not enthusiastic about the game you're making) can prove to be quite the challenge. Take your time, and for the love of all that is good pick (or start, but I'll get back to that) a project that looks perfectly achievable within just a couple months time, at most. There are disappointingly few of these around, but for a first-time open source project it comes highly recommended.

**Extra pointers:**

1. Don't start out too picky; look in different sites, consider odd genres, get to know the width of your skill-sets and interests.
2. Consider scope. How much time are you willing to commit? How soon do you want to see the project finish? Any pending time-sinkholes (studies, work, life commitment) worth factoring in?
3. Start by talking. Exchange at least 1000 words with someone involved in a given project before finally making up your mind.
4. Now stick with it and bring it to the finishline!

A great thing about open source projects is the low barrier to entry. There's loads of ways to contribute to a project besides applying your key skills. Just look at the `CONTRIBUTING.md` of any major project on GitHub for examples.

Honestly, the 'open source games' complete/incomplete ratio could use a boost. The beauty of transparency and open source though is that 'incomplete' is far from 'unsuccessful' so long as you make the most out of the ride.

**Update:** Also see my closely related article on opensource.com, which is based on this answer.
> 47 votes

# Answer
There is a free game dev community based on the freegamedev forums http://forum.freegamedev.net/ and the associated IRC at #freegamer on freenode.net that you might check out for some projects you could potentially join.
> 5 votes

# Answer
SourceForge could be an idea, browse it and try to find a project that is active, interesting and may be accepting people, and get in contact with the current maintainers. You could branch off another project to add your own features, and merge in later.
> 3 votes

# Answer
Getting involved in the modding community might be a good option.

Alternatively there's a tradition of grabbing the source for games like Nethack, tweaking the source to add cool features, and releasing the changes as a patch. The community is pretty friendly to boot.
> 3 votes

# Answer
The FreeGameDev community has a section for projects looking for collaborators and developers: http://forum.freegamedev.net/viewforum.php?f=22

There is also the FreeGameDev wiki with more information on getting involved with open source / Free software game development.

The advantage that FreeGameDev community has over GameDev etc is that is it specifically for open source / Free software games.

The FreeGameDev community originated from the Free Gamer blog, which is a blog tracking Free software game news.
> 3 votes

# Answer
Some of the open-source game projects have wiki pages or bug-trackers where you can find out about stuff to be done and where to contribute. I think in all cases it's a good idea to first get familiar with the game. Download and play it (if it's already in a playable stage), get familiar with the code, file bug-requests or try to fix open bugs. Get in touch with the developers.

Here are two links to (rather big) open-source game projects, but of course there are plenty others out there:
> 2 votes

# Answer
Are you looking to contribute to a general framework as a way to learn about game programming? Or are you looking for an open-source-style community to help you learn?

If the latter (and maybe the former?), I recommend Pygame: http://www.pygame.org/

I got started with Pygame (for traditional game dev) many years ago for the original Boston Game Jam, and I found it to be a great tool for learning basic game development concepts.

Also, if you decide to try Pygame, don't miss the tutorials here: http://www.pygame.org/wiki/tutorials
> 2 votes

# Answer
If you want to have a go at participating in an open-source game project, then may I suggest Battle for Wesnoth. It's a fairly popular open source game with nice graphics and clean code base (from what little I remember. I haven't hacked on it, but I skimmed the code a few years ago).

It's written in C++ and Lua.
> 0 votes

---
Tags: open-source
---


# Question
Title: Best open-source 3D game engine for a first person shooting game?
What is the best opensource 3D game engine suitable for 1st person shooting game? This engine should be script-able with lua.

# Answer
> 5 votes
You haven't told us your skill level. But, you can even try integrating Lua scripting functionality with any open source engine of your choice. There are libraries like Luabind & toLua++ for this.

After quick google search there are some interesting results,

1. IrrLua is a Lua binding for the Irrlicht 3D rendering engine. Last update : 08/23/06
2. Scripting with LuaBind in Ogre
3. Plugin development tutorial for integrating Lua scripting with Crystal Space Engine. But, I would suggest to stay away form this engine.
4. BlendElf is a good choice.But, I don't think the developer isn't maintaining it any more.
5. If you see Horde 3d feature list, you will see `Strong modularity and high abstraction through flat C-style DLL API (also makes it possible to use Horde3D from virtually any programming language)`, just like Leadwerks Engine.

*Many well/less known engines has Lua with it. Check it out.*

# Answer
> 0 votes
Try http://blendelf.com/

Found it from here: Easy to use cross-platform 3D engines for C++ game development?

# Answer
> 0 votes
The Doom 3 engine was recently Open Sourced under the GPL.

It doesn't have Lua support through. However it does have it's own inbuilt c-like scripting language. If your working on your own game engine you can generally add it in yourself.

# Answer
> 0 votes
OctaForge is:

* A 3D Game Engine, with Lua scripting and an easy to use in-game editor.
* A Game Platform, where you can find multiplayer games to play and upload your own games to as well.
* A place to find and upload game content to, from 3D models to textures to sounds.
* A community of game developers.

The above I lifted from their about page. OctaForge is actually a fork of the popular Sauerbraten engine, with one of the goals replacing CubeScript with Lua.

# Answer
> -1 votes
Ogre or Irrlicht 3D are good for C/C++ game programmers.

# Answer
> -1 votes
The Blender Game Engine is pretty good for 3D games. It doesn't use Lua, but it uses Python, which is more comfortable to me (objects, classes, inheritance). It can definitely do FPS games, and supports GLSL shading. It also has the Bullet physics engine included, and, of course, is present inside of the 3D modeler, Blender.

# Answer
> -1 votes
Open source AND with Lua scripting?

Well, that pretty much leaves Ogre, although frankly it isn't a game engine, it's a renderer/scenegraph. You still need to plug in the other bits like IO, physics and audio, but plenty of options already exist.

If you drop the Lua requirement, your options open up a heck of a lot more, as does if you drop the Open Source requirement.

# Answer
> -1 votes
jMonkeyEngine is a very good open source 3D engine.

It runs on the JVM and you can also use Lua on the JVM for scripting if that is a requirement.

---
Tags: first-person-shooter, open-source
---


title: Can packet latency fluctuate?

text:
# Question
Title: Can packet latency fluctuate?
Can the time it takes for a packet to be transmitted from a client to the server fluctuate?

# Answer
The IP protocol, atop which TCP and UDP are constructed, specifies that datagrams are neither guaranteed to arrive in order, nor via the same route, nor, for that matter, *at all* (thanks Trevor for the reminder). So, irrespective of whether TCP or UDP is used, latency will fluctuate. Latency is partly due to distance travelled, which changes if the path changes, and partly due to protocol stack translation on the routing devices along the chosen path -- which also change if the path changes.

This is part of the self-repairing nature of the internet, enabling it to do what it does every day: if one route becomes less suitable according to heuristics programmed into various routing devices along the way, another route will be chosen instead. This can be either momentary, or long-term. Remember that before it was the internet, it was the ARPANET -- a defense network designed to deal with eg. the instant removal of vast sections of the network (think nuclear warfare), without the network as a whole going down. By routing around damaged or otherwise non-ideal areas, the greater network continues to function (albeit, perhaps, suboptimally).
> 9 votes

# Answer
This is probably not game development question, but yes. In normal IP connection, each packets may go through different intermediary "hops", and each different "hops" may have different latency.

If you're using TCP to transfer your data, the protocol abstracts that for you and will reorder packets to deliver the packets in the order they were originally sent; however if you're using UDP, the packets can and do arrive out of order, depending on the latency of each individual packets.
> 5 votes

# Answer
Absolutely everything about an IP network can change at any time.

The following article discusses how things like latency, packet loss, and throughput can vary and why: DEI Tech Note 0021: Loss, Latency, and Speed
> 2 votes

# Answer
Aside from what's already been said, don't forget that routers are allowed to **arbitrarily drop packets**, meaning in TCP a packet could theoretically take arbitrarily long to reach its destination (and in UDP, it might *never* reach its destination!).
> 1 votes

---
Tags: networking, lag, packet
---


# Question
Title: Can learning how to do empirical research help a game developer?
I know this may be an odd question, but I have the opportunity to take a graduate class that teaches how to do empirical research.

I've taken a Human-Computer Interaction class in the past where it was important to perform empirical studies to find out how users interact with your application and study what improvements can be made. I can see where doing the same type of empirical studies might be useful when developing a game.

Also, we get to choose the type of empirical research we do which I would choose to do on either computer graphics or game development. Would a class like this potentially be helpful for a wanna-be indie game developer?

# Answer
Definitely. The reason? Because the more research you do of techniques used by those at the leading edge of your field, the better and more creative a \[insert name of your profession here\] you will become.

On a weekly basis, I read or at least skim over research papers on real-time raytracing, global illumination models, up-and-coming AI techniques, procedural generation, narratology and/or game design as well as other random topics in math and geometry. In fields you are new to, it will take you a while to grok the fundamentals, and you may sometimes feel stupid. **Don't be intimidated**. (This assumes you are not already post-grad or an otherwise seasoned researcher). The more you immerse yourself in that knowledge the sooner you will begin to see the bigger picture and the brilliance of the solutions documented. You don't have to read entire papers either. Sometimes just a skim through or looking at the results concluded in the study are enough.

I think it's all too common in the game development field *not* to think of ourselves as computer scientists. IMHO this is one reason why there's been an increasing lack of innovation since the mid-90's, and conversely an increasing interest in indie titles.

I've found another excellent place to research solutions that push the boundaries of available technology is the demo scene. In earlier days, many game developers (take Zyrinx/Lemon for example, the guys who developed AMOK) came from the ranks of demoscene coders, and I think in some parts of the world at least, this still happens a fair amount.
> 7 votes

# Answer
Probably. Certainly empirical research techniques have their place in game development -- usability studies, for example, or analysis of market data or marketing trends for competing games. Large studios conduct this kind of thing in one form or another (with varying degrees of rigidity with respect to the empirical model).

For an indie specifically, it can still be useful to know about, but in practice it would become more of a question of whether or not you have time to engage in serious market research (or resources to put forward in serious usability research) versus spending that time, money, et cetera on actually producing and polishing your game.
> 2 votes

---
Tags: education, career
---


title: Generating random Pools or lakes

text:
# Question
Title: Generating random Pools or lakes
I have implemented functions that can draw any polygonal shape, however I have been unable to generate a smooth shape that mimics the rounded edges of a lake. I tried generating two circles and joining the edges but there is not enough variation or smoothness to it. Does anyone have any pointers or ideas that could generate a shape like this?

# Answer
> 8 votes
alwynd mentioned Perlin noise. Here's how I generated the island shapes for the polygon map generator:

1. Generate perlin noise.
2. For each location `(x, y)` in the noise bitmap, compute the distance from the center, normalized so that the bitmap is 2x2: `(dx, dy) = (2 * x / width - 1, 2 * y / height - 1); d = sqrt(dx*dx + dy*dy)`.
3. Location `(x, y)` is part of the island if `noise[x, y] > 0.3 + 0.4*d*d`. This step attempts to make the shape round by cutting off areas that are far from the center.

Islands are a little more ragged than lakes though, so I'm not sure if these shapes will be to your liking. I've put up a demo of the above algorithm, with buttons at the bottom to control the two magic numbers. There might be different values of the magic numbers 0.3 and 0.4 that produce shapes you like.

# Answer
> 4 votes
You could use a Perlin Noise algorithm to generate the lakes for you, if you are using a top down view (polygon shape, sounds like you are), this guy from Stanford did just that.

http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/

# Answer
> 0 votes
One way would be to start with a basic polygon, maybe your 2 circles approach.

Firstly offset all points randomly, so doesn't look too much like a circle, then for every edge, split it in 2 and offset the middle point by some small random amount. Keep doing this until you have the required detail.
This is similar to what's done when generating forks of lightning.

---
Tags: algorithm, procedural-generation, terrain
---


title: from normal to rotation matrix

text:
# Question
Title: from normal to rotation matrix
(i'm on OPENGL)

i have a mesh O (object) and a mesh T (terrain). i know a single triangle in T and i want to orient O to be aligned to that triangle (torate O to align to T in that point).

i have only the normal in the triangle. how can i achive the roation matrix?

i have thought this algorithm:

```
// pseudocode
float[] normal2rotation(Vector3D normal) {
    angleX = Vector3D.angleBetween(normal, Vecto3D.Axis3D.X);
    angleY = Vector3D.angleBetween(normal, Vecto3D.Axis3D.Y);
    angleZ = Vector3D.angleBetween(normal, Vecto3D.Axis3D.Z);

    float[] result = {angleX, angleY, angleZ};
    return result
}

```

but it does not give me the desired result.

# Answer
The easiest way to do this is to directly build a rotation matrix to accomplish the desired transform. If you need to convert it to a quaternion or Euler angles afterward, you can do that using the standard conversions.

Since you're in OpenGL I'll assume you're using column vectors. In that case, with a 3x3 rotation matrix, the first, second and third columns are the vectors to which the X, Y, and Z axes will be taken by the matrix. Therefore, if you want to rotate an object so that its Z axis points along the normal, you would set the third column of the matrix to the normal, and find two perpendicular vectors in the plane of the triangle to use for the first and second columns.

Something like this (I don't know your libraries, so I'm guessing at the syntax):

```
Matrix NormalToRotation(Vector3D normal) {
    // Find a vector in the plane
    Vector3D tangent0 = Cross(normal, Vector3D(1, 0, 0));
    if (Dot(tangent0, tangent0) < 0.001)
        tangent0 = Cross(normal, Vector3D(0, 1, 0));
    tangent0 = Normalize(tangent0);
    // Find another vector in the plane
    Vector3D tangent1 = Normalize(Cross(normal, tangent0));
    // Construct a 3x3 matrix by storing three vectors in the columns of the matrix
    return ColumnVectorsToMatrix(tangent0, tangent1, normal);
}

```
> 3 votes

# Answer
There are an infinite number of possible orientations that will orient 'O' to 'T'. A single vector ('T's normal) isn't enough since 'O', once aligned with the normal can rotate freely about that normal and still meet the criteria... a second vector is needed to lock it in a specific orientation, perhaps another known direction 'O' is pointing?

The crossing that is needed (as Nathan's post demonstrates) to find the other to matrix basis vectors should start with a cross between the normal & that 2nd direction vector.
> 0 votes

---
Tags: rotation, quaternion
---