# Question
Title: How to store the state of the world for a fixed time step?
Most of the posts on fixed time steps say something like this:

```
State previous;
State current;

while ( !quit )
{
     double newTime = time();
     double frameTime = newTime - currentTime;
     if ( frameTime > 0.25 )
          frameTime = 0.25;   // note: max frame time to avoid spiral of death
     currentTime = newTime;

     accumulator += frameTime;

     while ( accumulator >= dt )
     {
          previousState = currentState;
          integrate( currentState, t, dt );
          t += dt;
          accumulator -= dt;
     }

     const double alpha = accumulator / dt;

     State state = currentState*alpha + previousState * ( 1.0 - alpha );

     render( state );

```

How do they calculate and save a State snapshot of the whole world? do they just make memcpy's or something? I'm working in Flash and don't have that kind of cloning capability.

# Answer
> 2 votes
Generally speaking I would read this pseudocode as a rough overview, and break each bit down into handling all the relevant state piece by piece.

For example:

```
previousState = currentState

```

might become:

```
for each object in world:
    object.previousState = copyOf(object.CurrentState)

```

And:

```
state = currentState*alpha + previousState * ( 1.0 - alpha );

```

would become:

```
for each object in world:
    renderableState = object.currentState*alpha + object.previousState * ( 1.0 - alpha );

```

...and so on.

Once you're down to the level of an individual object there is usually very little state that you actually need to be able to clone. In a simple game it might just be the position, for example. If your position is a Point, you can clone() it to get a copy. Or you might just have the value types which you can copy trivially. Either way, when you dig down into the specific state, you usually end up with small pieces that are easy to copy.

# Answer
> 0 votes
If you have problems with deep copy, you can store the reference of the current state in previousState, and delegate the creation of a new state in the integration step. This implies that you have the responsibility to destroy the previousState before updating ( you can delegate this to your garbage collector if there is one)

*Pseudocode*:

```
StateRef previous;
StateRef current;
[...]
current = initState(genericStateSource);
[...]
    free(previous);
    previous = current;
    current = integrate(current,t,dt);

```

*Evolution*:

```
+-----+-----+-----+-----+
| n+1 | n+2 | n+3 | n+4 |  loop start
+-----+-----+-----+-----+
              ^-p   ^-c

+-----+-----+-----+-----+
| n+1 | n+2 | n+3 | n+4 | free n+3; advance p
+-----+-----+-----+-----+
                   ^-p,c

+-----+-----+-----+-----+-----+
| n+1 | n+2 | n+3 | n+4 | n+5 | integration step
+-----+-----+-----+-----+-----+
                    ^-p   ^-c

```

---

About your code there are some problems:

First you do not have to store the previous state in each iteration (particularly if it is is expensive): you know exactly how much iterations you will do as soon as you compute *accumulator*.

There is an error to the while loop: basically you integrate each in each step using a black-box integrator then you do a linear interpolation between last and current state. To make sure that this makes sense the the interpolation has to be done between the last state before and the first state AFTER the point of interest.

You did:

```
|-----|-----|-----|-----|---- |
                  p   ^ c

```

But you should do:

```
|-----|-----|-----|-----|---- |
                        p   ^ c

```

I.e. you have to integrate another step over the end if you have to interpolate: again, you know if is the case as soon as you compute *accumulator*

---
Tags: architecture, actionscript-3, game-loop, timing
---


# Question
Title: MMO architecture - Highly Scalable with Reporting capabilities
A friend of mine is asking me to help out on a project of his, I have done a small amount of game development before, but mainly do application and enterprise development these days.

He is asking me to look into some of the networking part of his game. I know that a huge part of this is going to involve reporting/analytics as well as scalability, so it isnt as simple as spamming a server and instantly getting responses.

In the enterprise app/web world we tend to use CQRS pattern or some other similar approach when we need to scale quite well and also take into account reporting on interactions etc.

So I imagine that most typical MMO style games (lets assume mmorpg games akin to WoW), they must employ a heavily distributed and scaleable system. So do they end up using a node system with a messaging fabric behind the scenes?

Sorry for being a bit vague but are there any sort of articles on people discussing the overall architecture for these style games?

# Answer
There are MMO code bases available, which might be better than articles? Depends on how you like to investigate a field.

Panda3D, Ryzom, Mangos (warcraft emu), the WorldForge project, and so on. Experimental engines like Smash in erlang. Many older MMOs are built on top of MUD code.

Most core MMO architectures aren't like enterprise setups, the usage pattern is built around a soft realtime simulation and not services.

The supporting bits like logging, authentication, load balancing are pretty much just like enterprise apps and services and some of the end user experience before attaching to the simulation have been done as traditional web services.
> 3 votes

# Answer
There are two types of MMO games. There are real-time games, along the lines of Eve and World of Warcraft, then there is everything else. Farmville, Mafiawars, etc. They both dictate totally different backend architectures.

For games like Farmville, your standard line-of-business type architecture will really excel, because the way users interact with the data is very similar and the data can easily be stored in a traditional Relational Database System.

Games that require real-time interaction between hundreds or thousands of players simply cannot be shoehorned into the line-of-business architecture. As @Patrick points out, many of the supporting elements of the game such as logging, authorization and authentication can be handled in a similar fashion to line-of-business applications. The tricky part, is handling "the world." This is where there really is no "right way" it all depends on how many players you expect to have, and what type of resources (programming and hardware) you are willing to throw at it.

I would argue, that you can start with a typical dedicated server setup for an FPS, and optimize from there where you start to see issues. Probably the first thing to implement is a way to have multiple of these "servers" talking to each other. Obviously you'll want to run this on a beefy physical box with plenty of bandwidth. IMO, the reason that many FPS games keep server size small, is because they know people are going to run it on some old P4 they have lying around and they'll do it on a crappy DLS connection, not because the server software cannot keep track of hundreds of players. Though I'd bet that typical "level size" is also a reason to keep the max players lower on FPS games.

The reality is that you will not have the same amount of players that World of Warcraft or Eve have overnight, and if you ever do approach those numbers where your architecture startes to show its weaknesses, I always say, that is a great problem to have because it means you're raking in the cash.
> 1 votes

---
Tags: architecture, networking, mmo
---


# Question
Title: Common game controls/ User interface libraries or source code?
Sorry for the ackward title, but i don't know what to call it exactly. **I'm looking for code or libraries that allow easy creation of commonly used user input devices, and code/libs that make gaming controls easy to set up (i'm using SFML and Box2D at the moment)**

I don't want to re-invent things like buttons, arrows being placed wherever the mouse is located, and more game specific items such as "controls settings" or even being able to drag objects around with the mouse.

More **specifically i want source code for interfaces that....**

* Makes Buttons and Textboxes easy to create
* allows mouse input to press buttons or drag objects in games
* has "Focuses" (like a textbox being able to gain focus and be typed in)
* Is compatable with SFML/Box2D

**and code for common game mechanics/controls that....**

* Allows easy setup of controls for a game
* Makes events like clicking and holding on an object easy to setup, as so objects can be dragged around afterward

***Are there any simple libraries or resources out there that i can use to avoid spending much of my time coding these now standard input devices/tecniques?***

# Answer
> 0 votes
There are literally hundred of them out there. cegui is widely adopted. Look into libagar, antisphere & mygui as well.

Turska UI/Framework has built in support for SDL.

Have you looked into this list(SDL Libraries)?

There are too many to list, but a handful of them continues with regularity.

---
Tags: c++, control, interface
---


title: 3D game engine for a beginner using C++

text:
# Question
Title: 3D game engine for a beginner using C++
Decided to try myself at gamedev, which game engine should i start working with? Or how should I develop my gamedev skills?

Have C++ experience, I have already started studying OpenGL programming, and I'm using only linux based distributives.

# Answer
Panda3D seems to meet all your needs. you can see user comments in DevMaster or check it's home page

you can use these search results for more engines (a hint check only those with more than 30 commnets)
> 1 votes

# Answer
You sound ready to start learning how game development is different from writing other software, with those skills.

The best advice I see repeated over and over from experienced developers is to **build a game, not an engine**. What they mean is that starting out you should write games instead of spending all your time writing engines that end up with no game at the end. Writing engines will come later once you've made a bunch of games.

Start small (something like Breakout), but build a complete game that's playable from beginning to end! Then slowly add features to that game and learn new libraries and techniques to make those features work. Very soon you'll know all about adding middleware to a project, what libraries are available, and your skills get better almost magically.

Now you can go look at engines and you will be able to decode what they offer and make some sense of why each one was designed differently. And from here you can build more complex games, maybe with an engine or one you decide to finally write.
> 9 votes

# Answer
I started writing a big post, but ended up deleting all of it. I think the best thing is you to look into the following, read the documents and see the feature list. See which suits you best.

Once I was on a quest to find the best engine for me, but there is not best. All has some strengths and weakness. I am prioritizing them -

1. Irrlight , Esenthel(No Linux) , Leadwerks (No Linux) & Panda3d
2. C4 Engine & Torque Game Engine

Havn't evauated yet, 3DGameStudio, DX Studio

Ogre is a rendering engine. To make a game with it you have to work on the additional parts. But, it worth Checking.

i haven't seen mentioned it anywhere, but apart from documentation its great, g3d engine

But, all of it is just a short list of what is available out there. Go here, DevMaster 3d Engine List and see all the engine and their features. *Caution :* many information are old.

& if you love java, you can always choose jMonkey Engine 3 \< I use it :) Its pipeline is shader based.

**I havn't checked them in a while. They might have drastic change in their feature set. So check them yourself.**
> 0 votes

---
Tags: c++
---


title: Making a camera in a 2D game (glOrtho)

text:
# Question
Title: Making a camera in a 2D game (glOrtho)
I'm trying to make a camera that follows my character and it seems I've managed. However, I don't know how to limit that my camera don't follow me when my character reachs the boundaries of the windows (it's ugly see black spaces beyond my tile map x\_x).

So, this is my code:

```
public class Camera {
    public void update(Vector2f spritePos) {
        Vector2f pos = new Vector2f(spritePos.getX()-368, spritePos.getY()-268);

        if((pos.getX()+368 > 368) && (pos.getY()+268 > 268)) {
                glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glOrtho(pos.getX(),
                pos.getX() + Display.getDisplayMode().getWidth(),
                pos.getY() + Display.getDisplayMode().getHeight(),
                pos.getY(),
                -1,
                1);
            glMatrixMode(GL_MODELVIEW);
        }
    }
}

```

I substract 368 to the X position, because I want to place my character at the center of my camera. Same with 268. This is a bad way to archieve this, because my camera "jumps" roughly to the position of my character \>.

Thank you very much.

# Answer
> 4 votes
The problem is the if condition

```
(pos.getX()+368 > 368) is equal to (pos.getX() > 0)  and
(pos.getY()+268 > 268) is equal to (pos.getY() > 0)

```

then the refactored condition can be

```
 if( ( pos.getX() > 0 ) && ( pos.getY() > 0 ) )
 //that means that the camera is only updated if pos is > that 0,0

```

For example, if pos is -2,0 the condition is false and the camera is not updated. We want that camera follow the character included in this case

then

```
public void update(Vector2f spritePos) {
Vector2f pos = new Vector2f(spritePos.getX()-368, spritePos.getY()-268);

// new code
float cameraPosX = 0;
float cameraPosY = 0;

cameraPosX = ( pos.getX() < 0 ) ? 0 : pos.getX();
cameraPosY = ( pos.getY() < 0 ) ? 0 : pos.getY();
//

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(cameraPosX,
            cameraPosX + Display.getDisplayMode().getWidth(),
            cameraPosY + Display.getDisplayMode().getHeight(),
            cameraPosY,
            -1,
            1);
    glMatrixMode(GL_MODELVIEW);

}

```

this code always update the camera, but clamps the camera position in x and/or y

---
Tags: opengl, java
---


# Question
Title: Can't update DirectX11 shader constant buffer
Alright, I'm currently making the transition from DirectX 10 to DirectX 11 (with very little help from the MSDN documention) and recently ran into a snag with updating a shader's constant buffer.

My application at the moment simply draws a rectangle in screen space and I've attached a float to the pixel shader so that I can quickly determine if the constant buffer is being updated by looking at the rectangle color.

I've used two methods presented in the MSDN tutorial (pDeviceContext-\>UpdateSubresource()) and the D3D11 sample code (pDeviceContext-\>Map()), both yielded the same results which leads me to wonder if maybe I missed an important flag earlier in the engine while initializing the D3D device or compiling the shaders. Also is anyone aware of any important trade offs between the two techniques?

Here is the relevant code...

```
struct UIShaderBuffer {
    XMMATRIX scale,
            rotation,
            translation;
    float temp; // Used to change the rectangle's color.
};

// Initialize the shader buffer and interface
bool UIRectangle::StartUpShaderBuffer() {
    UIShaderBuffer _shaderBuffer;
    ZeroMemory(&_shaderBuffer, sizeof(UIShaderBuffer));

    D3D11_BUFFER_DESC _bd;
    ZeroMemory(&_bd, sizeof(D3D11_BUFFER_DESC) );
    _bd.Usage                       = D3D11_USAGE_DYNAMIC;
    _bd.ByteWidth                   = sizeof(UIShaderBuffer);
    _bd.BindFlags                   = D3D11_BIND_CONSTANT_BUFFER;
    _bd.CPUAccessFlags      = 0;
    _bd.MiscFlags                   = 0;
    _bd.StructureByteStride = 0;

    D3D11_SUBRESOURCE_DATA _subResData;
    ZeroMemory(&_subResData, sizeof(D3D11_SUBRESOURCE_DATA));
    _subResData.pSysMem             = &_shaderBuffer;
    _subResData.SysMemPitch         = 0;
    _subResData.SysMemSlicePitch = 0;

    if(FAILED(pDevice->CreateBuffer(&_bd, &_subResData, &pShaderBuffer))) {
            MessageBox(0, TEXT("UIRectangle: Failed to bind shader constant buffer.\0"), 0, 0);
            return false;
    }
    return true;
}

// Update the buffer. Call before rendering.
void UIRectangle::UpdateShaderBuffer(XMMATRIX &_rScale, XMMATRIX &_rRotation, XMMATRIX &_rTranslation) {
    static UIShaderBuffer _updatedBuffer;
    _updatedBuffer.scale            = _rScale;
    _updatedBuffer.rotation         = _rRotation;
    _updatedBuffer.translation  = _rTranslation;
    _updatedBuffer.temp = 1.0f; // Used to affect rectangle color in order to see if buffer is getting updated.

    pDeviceContext->UpdateSubresource(pShaderBuffer, 0 , 0, &_updatedBuffer, 0, 0);
    pDeviceContext->VSSetConstantBuffers(0, 1, &pShaderBuffer);
    pDeviceContext->PSSetConstantBuffers(0, 1, &pShaderBuffer);

    /* Alternative method used in D3D11 sample code.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    UIShaderBuffer* bufPtr = 0;
    if (FAILED(pDeviceContext->Map(pShaderBufferAddr, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
            MessageBox(0, TEXT("UIRectangle: Failed to map shader buffer.\0"), 0, 0);
    bufPtr = (UIShaderBuffer*) mappedResource.pData;
    bufPtr->scale           = _rScale;
    bufPtr->rotation        = _rRotation;
    bufPtr->translation = _rTranslation;
    bufPtr->temp = pos;
    pDeviceContext->Unmap(pShaderBufferAddr, 0);

    pDeviceContext->VSSetConstantBuffers(0, 1, &pShaderBufferAddr);
    pDeviceContext->PSSetConstantBuffers(0, 1, &pShaderBufferAddr);
    */
}

// Render
bool UIRectangle::Render() {
    static XMMATRIX _scale          = XMMatrixTranspose(XMMatrixScaling(1.0f, 1.0f, 1.0f)),
                            _rotation       = XMMatrixTranspose(XMMatrixIdentity()),
                            _translation = XMMatrixTranspose(XMMatrixTranslation(-0.5f, 0.0f, 0.0f));

    UpdateShaderBuffer(_scale, _rotation, _translation);
    return Mesh<V_Pos>::Render();
}

template <class V>
bool Mesh<V>::Render() {
pDeviceContext->IASetInputLayout(pVertexLayout);
pDeviceContext->IASetPrimitiveTopology(topologyType);
pDeviceContext->VSSetShader(pVShader, 0, 0);
pDeviceContext->PSSetShader(pPShader, 0, 0);
pDeviceContext->Draw(bufSize, 0);

return true;
}

```

Shader code....

```
cbuffer ConstantBuffer : register( b0 ) {
    matrix scale;
    matrix rotation;
    matrix translation;
    float temp;
};

float4 VS( float4 _pos : POSITION ) : SV_POSITION {
    //return mul(translation, _pos);
    return _pos;
}

float4 PS( float4 Pos : SV_POSITION ) : SV_Target {
    return float4( temp, temp, temp, 1.0f );
}

```

Forgot to mention that I noticed this in the D3D11 debug output.

```
D3D11: INFO: ID3D11DeviceContext::Draw: Constant Buffer expected at slot 0 of the Pixel Shader unit (with size at least 208 bytes) but none is bound. This is OK, as reads of an unbound Constant Buffer are defined to return 0. It is also posible the developer knows the data will not be used anyway. This is only a problem if the developer actually intended to bind a Constant Buffer here.  [ EXECUTION INFO #350: DEVICE_DRAW_CONSTANT_BUFFER_NOT_SET ]

```

I'm assuming that this is the problem however I don't understand it! Playing with the slot parameter of the SetConstantBuffers() call doesn't change anything, and I have no idea where else I need to bind the buffer. Is there some kind of resource dispute between the pixel and vertex shaders over the constant buffer? Or is this a data packing and alignment issue?

Other questions...

Are there any advantages to using XMMatrices over D3DMatrices? (Other than having to transpose one)

"XMMATRIX is SSE2 optimized and the code inlined, which as far as I know, isn't true of D3DXMATRIX. So it's definitely faster than D3DX, and in addition, it's more portable (has an Xbox 360 port)." - DeadMG

I've mirrored this question here http://www.gamedev.net/topic/605347-updating-shader-buffers/

**Edit 1**

Jumped the gun, thought I found the solution. Same issue and warning remains.

Here is the shader initialization code

Vertex Shader

```
 bool VShader::StartUp(const character *_id, const void *_pDevice, LPCWSTR _pFileName, const char *_pFuncName, const char *_pShadModel) {
// Id used to reference the shader from the shader manager subsystem's hash table.
    // Replace with Int hash value!!!!
if ( !id.StartUp(GAME_OBJECT_STRLEN) ) {
    MessageBox(0, TEXT("VShader: Failed to start up shader id.\0"), 0, 0);
    return false;
}

if (!id.SetString(_id)) {
    MessageBox(0, TEXT("VShader: Failed to set shader id.\0"), 0, 0);
    return false;
}

// I'm under the impression that these are the correct flags since MSDN documentation referenced typedefs and enums that didn't exist.
unsigned int _shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;

// Debug flag
#if defined(_DEBUG)
    _shaderFlags |= D3D10_SHADER_DEBUG | D3D10_SHADER_SKIP_OPTIMIZATION;
#endif

ID3D10Blob* _pErrorBlob = 0;
bool _hasFailed = false;

// Create the vertex shader
if(FAILED(D3DX11CompileFromFile(_pFileName, 0, 0, _pFuncName, _pShadModel, _shaderFlags, 0, 0, &pVSBlob, &_pErrorBlob, 0)))
    _hasFailed = true;

if (_pErrorBlob || _hasFailed) {
    if (_pErrorBlob != 0)
        MessageBoxA(0, (LPCSTR)_pErrorBlob->GetBufferPointer(), 0, 0);
    else {
        SString _error(ERROR_STRING_SIZE);
        _error.SetString(TEXT("VShader: Unable to find \"\0"));
        _error.Append(_pFileName);
        _error.Append(TEXT("\". (\0"));
        _error.Append(id.GetStringPtr());
        _error.Append(TEXT(")\0"));

        MessageBox(0, _error.GetStringPtr(), 0, 0);
        _error.ShutDown();
    }
    return false;
}

if (FAILED(((ID3D11Device*)_pDevice)->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), 0, &pVShader))) {
    SString _error(ERROR_STRING_SIZE);
    _error.SetString(TEXT("VShader: Failed to create pixel shader.\0"));
    _error.Append(_pFileName);
    _error.Append(TEXT(")\0"));

    MessageBox(0, _error.GetStringPtr(), 0, 0);
    _error.ShutDown();
    return false;
} else return true;
}

```

Pixel Shader.

```
bool PShader::StartUp(const character *_id, const void *_pDevice, LPCWSTR _pFileName, const char *_pFuncName, const char *_pShadModel) {
if ( !id.StartUp(GAME_OBJECT_STRLEN) ) {
    MessageBox(0, TEXT("PShader: Failed to start up shader id.\0"), 0, 0);
    return false;
}

if (!id.SetString(_id)) {
    MessageBox(0, TEXT("PShader: Failed to set shader id.\0"), 0, 0);
    return false;
}

unsigned int _shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;

// Debug flag
#if defined(_DEBUG)
    _shaderFlags |= D3D10_SHADER_DEBUG | D3D10_SHADER_SKIP_OPTIMIZATION;
#endif

ID3D10Blob* _pErrorBlob = 0;
bool _hasFailed = false;

// Create the pixel shader.
if(FAILED(D3DX11CompileFromFile(_pFileName, 0, 0, _pFuncName, _pShadModel, _shaderFlags, 0, 0, &pPSBlob, &_pErrorBlob, 0)))
    _hasFailed = true;

if (_pErrorBlob || _hasFailed) {
    if (_pErrorBlob != 0)
        MessageBoxA(0, (LPCSTR)_pErrorBlob->GetBufferPointer(), 0, 0);
    else {
        SString _error(ERROR_STRING_SIZE);
        _error.SetString(TEXT("PShader: Unable to find \"\0"));
        _error.Append(_pFileName);
        _error.Append(TEXT("\". (\0"));
        _error.Append(id.GetStringPtr());
        _error.Append(TEXT(")\0"));

        MessageBox(0, _error.GetStringPtr(), 0, 0);
        _error.ShutDown();
    }
    return false;
}

if (FAILED(((ID3D11Device*)_pDevice)->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), 0, &pPShader))) {
    SString _error(ERROR_STRING_SIZE);
    _error.SetString(TEXT("PShader: Failed to create pixel shader. (\0"));
    _error.Append(id.GetStringPtr());
    _error.Append(TEXT(")\0"));

    MessageBox(0, (LPCWSTR)_error.GetStringPtr(), 0, 0);
    _error.ShutDown();
    return false;
} else return true;
}

```

**Edit 2**

I'm starting to think it's an issue with my draw call sequence and by extension the design of my Mesh superclass and UIRectangle subclass. Didn't originally include the Mesh.Render() function with the code I posted but I added it to the bottom of the first code block. Could someone validate it?

**Voting to delete. I solved the problem while rearranging my architecture and it was an inheritance issue! (kicks self) Don't believe this question can help anyone.**

# Answer
> 4 votes
You need to set the constant buffer on the shader after you've updated it. After this

```
pDeviceContext->UpdateSubresource(pShaderBuffer, 0 , 0, &_updatedBuffer, 0, 0);

```

you need to call

```
this->_context->PSSetConstantBuffers(0, 1, &pShaderBuffer);

```

This way you set the values on your struct instance, and then use UpdateSubresource to update the D3D11\_BUFFER with the new values, once that's done, you need to send the updated buffer to the GPU with PSSetConstantBuffers (in order to set it onto the pixel shader slot).

The way you are creating you D3D11\_BUFFER looks a little convoluted to me too, this is the way I set up most of my constant buffers:

```
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.ByteWidth = sizeof(cb_perObject);
bd.Usage = D3D11_USAGE_DEFAULT;
if (FAILED(this->_device->CreateBuffer(&bd, 0, &this->_perObjectBuffer)))
    return false;

```

and this is how I update it:

```
this->_perObject.wvp = XMMatrixTranspose(this->_model.getWorldMatrix() * this->_camera.getViewMatrix() * this->_projection);
this->_perObject.world = XMMatrixTranspose(this->_model.getWorldMatrix());
this->_context->UpdateSubresource(this->_perObjectBuffer, 0, 0, &this->_perObject, 0, 0);
this->_context->PSSetConstantBuffers(0, 1, &this->_perObjectBuffer);

```

It might not be the best way to do it, but it works for me.

The XNAMATH data types such as XMMATRIX are 16 bytes aligned and use SSE/SSE2 instructions (SIMD) and therefore faster than the older D3DXMATRIX. Depending on the alignment you are using, they can be a bit of a pain to work with and you will need to use the XMFLOAT3, XMFLOAT4, XMFLOAT4X3, XMFLOAT4X4 and load/unload them into XMMATRIX/XMVECTOR types.

# Answer
> 2 votes
XMMATRIX is SSE2 optimized and the code inlined, which as far as I know, isn't true of D3DXMATRIX. So it's definitely faster than D3DX, and in addition, it's more portable (has an Xbox 360 port).

---
Tags: shaders, directx11
---


title: game state saving/loading?

text:
# Question
Title: game state saving/loading?
what is the most used method or algorithm for saving game state (profiles), databases text files how there encryption goes and things related.

I have seen Caesar IV used mySQL.

any suggestions.

# Answer
I'm pretty sure it is most often done in a proprietary (binary) format, just writing each variable from whatever game state struct you use into a file, or reading that file back into an instance of the struct. In C++ for example you can treat an object like an array of bytes and just fwrite() it into a file, or fread() from the file and cast it back into its object form.

If you are using Java or another language you can opt to use **serialization** to make the task really easy. The Java explanation is at the bottom of this answer; other languages (higher-level than C++) surely have their own serialization libraries or built-in functions as well, which you should opt to use. No matter how inefficient the serialization routine might be, hard drive space nowadays is cheap, especially when the game state shouldn't be very large at all, and it prevents you from writing and *maintaining* your own serialization routines.

You should absolutely **not** use MySQL (just read the first sentence of this review). If you really need a relational database for some reason, use SQLite; it is a lightweight database system and exists in a single database file. But for most games, relational databases are not the way to go, and companies which try to use them usually end up using them as a key-value lookup table rather than a true relational database.

**Any sort of encryption of local disk files is only obfuscation**; any hacker will just sniff the data right after your program decrypts it. I'm personally against that sort of thing, ESPECIALLY with one-player games. My view is that the owners of the game (paying customers, mind you) should be allowed to hack at the game if they want to. In some cases it can create a greater sense of community, and "mods" can be developed for your game which drive more customers to you. The most recent example that comes to mind is the Portal in Minecraft mod that was recently released. It's published in gamer news sites all over the internet, and you can bet it drove up sales of Minecraft.

---

If for some reason you are actually crazy enough to be using Java for game development like I am, here's a quick explanation of serialization in Java:

> Keep all of your game state data in one class, make the class serializable by implementing `Serializable`, use the `transient` keyword if you mix special instantiated variables into the class (transient objects are not serialized), and simply use `ObjectOutputStream` to write to file and `ObjectInputStream` to read from file. That's it.
> 20 votes

# Answer
If you are writing your own code, say in C++, you can use binary files. Binary files give you a form of encryption through obfuscation. But as documented all over the internets, that is a very weak form of security.

OR, you can use something like RapidXML if you want a human readable solution.

If you are usuing some kind of framework, look into it's file support functions. HTH
> 3 votes

# Answer
Most games I've seen just use hand-written code to read/write from binary files. Often, the on disc format will be an exact replica of the memory layout of an object so loading is just:

1. Read file into memory.
2. Cast pointer to buffer to object type.

It's fast, but it's a chore to maintain, platform-specific, and inflexible.

Lately, I've seen a couple of games use SQLite. People I've talked to seem to like it.
> 0 votes

# Answer
Serialization is mentioned in some of the other answers, and I agree that is a reasonable solution. One way it fails though is in versioning.

Say you release your game and people play it and create some save games. Then in a later patch you want to fix a bug or add some features. If you use a simple binary serialization method and you add a member to your classes your serialization may not be compatible with the old save games when the customers install your patch.

So whatever approach you use, make sure you think of this issue before you release the game the first time! Customers will not be happy if they have to start over after applying a patch.

One way to avoid this is to have each basic data type implement Save(version) and Load(version) methods that are smart enough to know what data to save and load for each version of the game. That way you can support backward compatibility of your save games and fail gracefully if a user tries to load a save game from a newer version of the game than they are running.
> 0 votes

# Answer
If you can use the same format that you use to store your levels in, it is a bonus.

For example, a game like Peggle might have an initial board layout, number of balls, current score (0 for the initial board), etc. Then a saved game can use exactly the same format.

If you use the same format then the save game and the level load can share code making your job easier!

For a game with really big map files, the save game can include the map file by reference. The initial level files might do the same thing, even, which makes coming back to that map easier too if for some reason the story has the character come back to the same place, except some of the NPCs are dead and there's dead bodies lying all over.
> 0 votes

---
Tags: state
---


# Question
Title: XNA 4.0 keeping fonts/sprites without the use of a content project
*Note: The actual title of my question does not really reflect my problem but is actually one of the possible solutions to my problem. I couldn't find a proper way to express my question so feel free to propose a different title.*

So I've recently moved to XNA 4.0 and I'm new to this whole *content project* idea. I made a simple component based "engine" as a game library that I reuse over all my projects.

I implemented some basic debugging tools like a frame rate counter which used a `SpriteFont`, which was stored within the actual engine library.

Now that all the content was moved out of the library with XNA 4.0, I don't know where to put the `SpriteFont` and all other content used by the engine.

**I'd rather avoid having to include both the content project and the engine library every time I start a new program, but is this my only option?**

**Or is there a way to include content within a library without resorting to content projects?**

# Answer
> 2 votes
I think adding the solution to each new project is the best and easiest way to accomplish what you want.

**You can open two projects up at once, and drag the solution from one to another, it takes seconds, and it stays very organized.**

---
Tags: xna, c#, xna-4.0
---


# Question
Title: Online service and/or application to develop a story line for an adventure game
My friends and I were talking about an adventure game. There will be a surplus of possibilities in the game and the player can pick from this wide variety of choices at each stage to do something. There will be consequences for each decision and that may or may not end the story.

The result would be somthing like this:

(picture from flashforward series S01E17)

If any of you watched heroes season 1 there is also similar time lines represented as strings in isaac mandez workshop. Sorry for bad quality examples but right now I can't think of any better one.

Do you know any website or application which we can use to create the timeline?

These features are required:

* The ability to represent events as boxes.
* The ability to connect distant events to each other.
* The ability to move events on a scene freely
* The ability to expand the scene easily
* There should be some color options for the lines representing connections between events
* Easily sharing the idea with one another
* It's much more better to have a WYSIWYG editor
* Easily explore in the large scene of events

In the end if you know any application which could let me create a board just like the one in my sample picture and please share it

# Answer
I've found one other **online** graph tool named grapholite. it's based on silverlight. It's easy to use and has a very easy to use sharing system (just like the one google docs provide). I think I'm going with this one.
> 2 votes

# Answer
CmapTools was used to create this image, which is a visualization of a Choose Your Own Adventure book. This might fit your needs, even though it's not specialized for story-writing.

The full size image is available here.

The author of the image has some things to say about it and has some other recommendations:

> In addition to CMapTools, which has an invaluable “auto-arrange” feature, there are other tools you might want to try. Bubbl.us allows you to make maps of this sort online. You can try Powerpoint or Visio...

(read more here)

Disclaimer: I haven't used it myself
> 7 votes

# Answer
Any kind of diagramming/graphing tool should be able to handle this. OmniGraffle on the Mac is an excellent choice -- options on Windows include Visio, Dia or the drawing program that comes with OpenOffice (maybe, not ever used it).

As far as I know there are no real dedicated storyboarding software that supports egregious branching like that. There are programs like Scrivener (Mac, Windows) that can be used to organize story concepts and flow, but they don't generally bother with a graph view because it is a limited practical utility.
> 4 votes

# Answer
You could use StarUML, it's not strictly speaking for this kind of useage, but you could create quite easily any sort of diagram you want.

Microsoft Visio is also a good piece of software, if you're a Student check with your campus you may be ably to get it free, otherwise you have to pay.

I also found a forum thread (are we allowed to post to other forums?) that had a few free links to specific storyboarding software :

http://www.atomiclearning.com/storyboardpro

http://www.newfreedownloads.com/find/storyboard.html

Indeed it seems you need to search for film creation tools to get anything like what you want. When will people learn Games aren't Films? :P
> 3 votes

---
Tags: storyboard
---


title: Scaling a game view with letterboxes?

text:
# Question
Title: Scaling a game view with letterboxes?
I'm creating an Android game and I want everyone who plays it -- no matter the size or shape of their screen -- to see the same 480x800 playfield but, depending on the actual resolution of their screen, scaled to fit their screen while maintaining the correct aspect ratio using letterboxing or black bars on the edges of the screen to fill in the gaps on the sides/top/bottom.

I'm using Canvas to develop my game but I don't know where to start, or have any idea of best practices for accomplishing this. Could someone enlighten me?

UPDATE: What I had in mind was using different image resources from hdpi/ldpi/mdpi resource folders and drawing them so bigger screens are restricted to the aspect ratio still but will be higher resolution. So drawing to a 480x800 bitmap won't work in my situation.

# Answer
> 7 votes
**Math**

First calculate your ideal screen ratio: 480 / 800 = 0.6

Then calculate the ratio of your users screen.

If the ratio is larger than 0.6 you know your game will have space to the left and right side of the game area. You would scale the game area by the users screen height/800. To calculate the horizontal position of the game area you'd do: (screen width/2) - (game area width/2)

If the ratio is less than 0.6 the game will have space at the top and bottom of the game area. You would scale the game area by the users screen width/480. To calculate the vertical position of the game area you'd do: (screen height/2) - (game area height/2)

**Practical Example**

The Users screen resolution is 3000X1600. This gives a ratio of 1.875, which is greater than 0.6 so space will be to the left and right of the game area. The scaling factor will be 1600 / 800 = 2. The horizontal position of the game area will be: (3000/2) - (960 /2) = 1020

**Android Specifics**

To position and scale the game area, you can apply a matrix to offset your drawing operations (Canvas.setMatrix). Another approach would be to draw your game screen into a 480x800 bitmap and then scale it afterwards, using Bitmap.createScaledBitmap or Canvas.drawBitmap.

---
Tags: java, android, resolution
---


# Question
Title: How to calculate the vector of an interception?
Given are a twodimensional space, and 1 friendly spaceship standing still, one foe is moving NOT directly to the friendly ship with known actual position, speed and direction.

The friendly ship wants to get itself into firing range to battle the foe.

Actually I am setting just a direct vector to the actual position moving ship, and recalculate it every frame, resulting in some kind of "round" flightpath.

What I want is to set a direct and straight path to the position that the foe will (presumably) will have when firing distance will be reached, assuming that foe will not change course until then.

As a first and "simple" implementation it would be enough if we assume the friend can speed up from 0 to max in no time.

Preffered implemantation would be one that considers the acceleration capabilities of the friend, and knows when interception is impossible because of the speed. It should work for every starting speed, not only from stand still. A plus would be if it even considers braking (battling at lightspeed is very energy inefficient in the given universe)

# Answer
If I understand your question, you do not want the ship to steer to the target, but rather to fly in a straight line that happens to intercept the target. I'm making a tower defense game that basically has the same need for a tower's bullet, a tower wants to fire a gun such that the bullet will intercept a moving target as long as it doesn't change speed/direction. The way I solved it was by using a quadratic equation. Here is some pseudo code:

```
Vector totarget =  target.position - tower.position;

float a = Vector.Dot(target.velocity, target.velocity) - (bullet.velocity * bullet.velocity);
float b = 2 * Vector.Dot(target.velocity, totarget);
float c = Vector.Dot(totarget, totarget);

float p = -b / (2 * a);
float q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

float t1 = p - q;
float t2 = p + q;
float t;

if (t1 > t2 && t2 > 0)
{
    t = t2;
}
else
{
    t = t1;
}

Vector aimSpot = target.position + target.velocity * t;
Vector bulletPath = aimSpot - tower.position;
float timeToImpact = bulletPath.Length() / bullet.speed;//speed must be in units per second

```

I found this to work so well I did not need collision detection for the shot... I was able to count on every shot hitting a bulls eye regardless of distance/direction/speed of target as long as those factors remained steady.
> 6 votes

# Answer
I suggest you look into steering behaviors. Especially pursuit. Source-code can be found in the OpenSteer implementation or look up a book like "Programming game AI by example" (ISBN 13: 978-1556220784)
> 6 votes

---
Tags: 2d, mathematics, path-finding, vector
---


# Question
Title: what is the standard solution to pathfinding towards a moving target?
I am working on a 2D RTS like game, basic A\* works perfectly for moving a unit from point A to point B.

But now I facing the continuous path-finding problem, like A attack a moving object B, call A\* at each frame once Object B's position changed seems inefficient.

so what is the standard method to this problem?

# Answer
> 17 votes
From what I know, you could take a look at the D\* algorithm which stands for "Dynamic A\*". This algorithm is used to compute pathfinding for dynamic environment, here with a moving target.

Here's a paper using D\* for moving target path finding : Moving Target D\* Lite

# Answer
> 10 votes
One option is to only make a new path once every few frames. If you did it once or twice a second rather than 60+ times a second then the user is unlikely to notice unless they are both two very fast moving objects

# Answer
> 8 votes
You can use the "dog curve" approach which dogs apparently uses when hunting down someone. They calculate where the impactpoint will be "in the future" and sets of straight to that position.

A simple approximative way could be something along the lines :

A = NPC

B = Target

T = time to get to B:s position (B:s initial position)

Calculate where B will be in 'T' time (if B continues at the same speed / angle) and go there instead.

This is not the perfect way as the distance changes but much simpler than making a perfect solution and much better than just trying to get to 'B'.

# Answer
> 3 votes
A agree with Kylotan that there isn't a *standard* method.

One method I have seen work was to assume the target continues moving in the same direction and change the goal position as you run through your path finding algorithm. This does mean you have to hold two metrics in your A\* nodes (cost and time as opposed to just cost).

To do better than that is very difficult. Unless you actually have knowledge about the unwavering path of the target, you're heading into the land of quite hard AI because you'll have AI's second guessing or simulating the target behaviour in order to guess where they will be and path towards that. This kind of AI is a real-time AB-game from game theory, an area that's not *standard* in any 3D game AI toolkit.

# Answer
> 2 votes
One way to do dynamic path finding is have the entity predict where the target is going and go there.

One way of doing this is using a Taylor series.

I'll call the path of the target over time the function S(t) where S is the position and t is the current time and the approximation to the path is A(f) and f is the date in the future one is approximating.

Then the simplest and most stupid approximation is A(f)=0.

The next simplest is A(f)=S(t) where t is the current time and f is the future. This is predicting the target simply stops in place.

The third simplest is A(f)=S'(t)\*f+S(t) where S' is the derivative of S with respect to time. This is predicting the target continues on at a constant speed with no acceleration.

The fourth simplest is A(f)=S''(t)\*f^2/2+S'(t)\*f+S(t). This is predicting the target is accelerating at a constant speed like a falling ball.

I know this can be rephrased in terms of change in time which is probably more convenient for a game. Now S can be anything. It could be an X coordinate, it could be a Y coordinate, it could be the distance between the objects, it could be an angle. Also there's probable better methods of predicting the future path of an object so I'd look around a bit.

# Answer
> 1 votes
If the terrain is reasonably open and the target isn't too far from the pursuer, then you could use the intercept steering behavior. Essentially, you take the position and velocity of the target to calculate a position out in front of the target that isn't too far, and not too close, and you steer the pursuer towards that point (calculated each at regular intervals).

---
Tags: path-finding
---


# Question
Title: WebGL rendering performance and frustum culling
When I render five boxes in WebGL with one texture for all of them, the app runs at 60 FPS, nice. But when I render 70 boxes the performance decreases to ~40fps... but only 5 of the boxes are visible.

I have debugged the app and all 70 boxes are using per fragment shaders when there is no need because 65 of them are out of frustum. I thought that setting the GL viewport clipped out-of-view polygons, but apparently not.

I would like to know if I can use frustum culling techniques to avoid this? How can I activate frustum culling? Is there any WebGL command or I have to do it manually?

Thanks in advance,

# Answer
Remember that FPS is not a great metric for performance: it's not a linear measure. 60 FPS is ~0.016 seconds per frame, whereas 40 FPS is 0.025 seconds per frame. That's a different of only 0.009 seconds for *fourteen times* as much render throughput. Timing rendering (which executes on the GPU) is not as straightforward as timing CPU operations. See this guide, which covers D3D specifically, but explores some concept that will apply to GL as well.

60 FPS for almost no objects sounds like you have v-sync enabled. In that scenario, you don't need too much more stuff to be rendered before you can hit a threshold where you have to block for a while waiting for the (modern equivalent of the) vertical blank interrupt before you can continue. This can make your FPS appear to drop dramatically. If you disable v-sync you may notice a much less severe drop.

All that being said, all the GPU will do for you is clip triangles outside of the viewport. It will not do frustum culling for you, which means every bit of geometry you submit will make it all the way through the vertex transformation pipeline into clip space at the least. The fragment shader should not run on primitives that have been clipped out.

If you implement frustum culling yourself (the API will not do it for you), you can boost your performance in general by not having to even submit out-of-view geometry to the card.
> 3 votes

---
Tags: webgl, frustum
---


# Question
Title: Left-Hand and Right-Hand Coordinate Systems
In Blender and other 3D modeling tools, the coordinate system is right-handed, while in Unity 3D and Orbiter Space Flight Simulator, they are left-handed, why this could happen? Why they don't simply use the right-hand coordinate system all the time to make things easier? Why don't all programs that deal with 3D graphics use Z+ as up?

```
 Y         |  Z
 ZX        |  YX
RIGHT-HAND | LEFT-HAND
TOP VIEW   | TOP VIEW

```

(fortunately, Unity3D converts from Blender coordinate system to Unity3D coordinate system)

# Answer
It's just tradition. Neither system is objectively better than the other, so you just have to get used to using both and switching between them from time to time!

Right-handed coordinates are traditional for *modelling* where one imagines the XY-plane to be horizontal, and the Z-axis to be vertical.

Left-handed coordinates are traditional for *cameras* where one imagines the XY-plane to be vertical (corresponding to screen coordinates if the camera is upright), and the Z-axis is into the screen (corresponding to the Z in the Z-buffer).

So modelling applications like Blender often use right-handed coordinates and game development toolkits like Unity often use left-handed coordinates. But some systems go the other way: RenderMan is left-handed, and OpenGL is right-handed (or at least early versions were, it's fairly agnostic now).

---

Another reason why handedness can differ is because of different conventions about the direction of the Y axis in two dimensions. Back in those far-off days when computer displays used cathode ray tubes, the display was scanned from top to bottom and left to right by the electron beam. So it was convenient to have the Y axis running down the screen, with the coordinate origin in the top left. On the other hand, it's conventional in mathematics for the Y axis to point upwards, with the coordinate origin in the bottom left. When you add a Z axis, these conventions give rise to three-dimensional coordinate systems of different handedness.
> 11 votes

# Answer
Simple answer, because *there is no strict rule about following a certain convention*.

You can even create a new coordinate system for your application. And people, who will be using it, will have to get used to with the new thing. No question.
> 3 votes

# Answer
Neither left nor right handed convention is objectively better than the other and similarly, no choice for which axis should be "up" is objectively better than the other. Different applications will have different requirements and for them, one particular choice may be more ideal. But that's not true in general.

Besides, it is a straightforward operation to convert between coordinate systems.
> 0 votes

---
Tags: unity, coordinates, blender
---


# Question
Title: What are some good mobile devices (phones, tablets, etc.) for tinkering?
I'm looking for a good coder's device to experiment with graphics programming. I'm sure a lot of you must have favorites. It'd be a great help if we can compile a list of these devices.

Just to be clear, I'm interested in devices which are easy to hack. There are good devices like the iPhone, for example, but you can't use a custom WebKit build with it to test WebGL.

So, what are some good 'coder's mobile device's?

# Answer
My best guess would be to look into the Android system : the OS is open source, and lot's of custom ROM are available online. You can also find a lot of Open Source application (including the default browser based on WebKit).

Then if you choose Android, be carefull of which hardware you choose as some manufacturer / carrier make their custom OS fork with limitations (which won't be a problem if you install a custom ROM). My first choice would go to the "official" Google phone
> 1 votes

# Answer
I've gotten good results from a Nook Color running Android 2.3 (specifically, Cyanogen Mod 7) from an SD card. When the card is in, it's basically a rooted Galaxy Tab; when the card is out, it's an unmodified Nook still under its warranty!
> 1 votes

---
Tags: graphics-programming, mobile
---


# Question
Title: What can I use to make my unique music ideas a reality?
I have several different music ideas for my game BGMs, but I do not have the musical skills nor the equipment to make them. The most I can do is beat-box them or make a drum beat (had I a drum). Is there a program or some other way to make my music real?

For instance, I've recently been trying GarageBand's Musical Keyboard to create the music but they don't have the exact beats I'm looking for, like a particular tap of a drum for example.

# Answer
> 2 votes
For creating your music, the first thing I am going to recommend is of course FL Studio. I mean, it's really nice, and as flexible as you would need it to be. It comes pre-loaded with all kinds of sample instruments and getting more is as simple as loading a VST.

---

Now to answer the broader question here. "I have an idea for music, but I don't know how to make it happen" there is a growing market with a (currently limited, but growing) selection of tools.

First off **UJAM**. It's insanely fun to play with, and with the proper work it can make some really decent tracks. It's as simple to use as **singing** or humming the tune that you want. From there you can convert it into a variety of instruments\* and use a number of (last I check) growing effects to mix and 'master' the track.

Then, if you have one, I recommend looking at **Garage Band on the iPad**. While not as full featured as it's sibling. It definitely makes creating music quickly a priority. It has a variety of smart instruments that can be used to quickly put together a track with limited effort. And if you check the link, it has drum kit's built in that just might solve your current issue (I was able to get rim shots out of it, and I think there is minor tonal differences when you strike in different locations).

There are no doubt more, but those three together let me put together all of my proto-music for all the prototypes that I work on.

# Answer
> 6 votes
I am no music guy. But, have you heard of FL Studio & its free alternate LMMS - Linux MultiMedia Studio

Sorry, dont know much about it. Its better if you talk to musician.

You can give it a try here http://music.stackexchange.com

# Answer
> 3 votes
I think you need something like Ableton Live, it's very easy to get started with and it comes with a massive supply of loops, instruments and effects.

www.ableton.com

I'd say https://video.stackexchange.com/ is a better place to post this question. Also, there are multitudes of sample packs available, you can utalise these in conjunction with a good sequencer such as Ableton, Logic, Cubase, Reaper, Fruity loops, or even garage band.

Google "sample packs" along with the genre your interested in, so something like classical strings, Jazz trumpets, hip-hop drums etc...

# Answer
> -3 votes
The world needs a game with beatbox music as a backing track, make it! (I made my sound effects orally to get started in development faster.)

---
Tags: music
---


title: Why do many games have “timeouts”?

text:
# Question
Title: Why do many games have “timeouts”?
I noticed that many social games have the concept of "timeouts". In farm games etc. it obviously makes sense (stuff grows, etc.). But I also noticed that angry birds introduced this as well. Individual angry bird games are pretty much stateless, so it doesn't seem to make a lot of sense at first glance (and some users are upset because of this).

What is the purpose of this? Does it bring more money somehow? Does it help retaining the users? Is this a new concept? Does it have any other applications, particularly in non-game realms?

# Answer
> 16 votes
There's a lot of questions here, I'll try to answer as many as I can to the best of my ability.

**First**: Is this a new concept? No. A lot of web games use "timeouts" in the form of terms, action points, or limiting the total amount of actions a player can do at once to a low number. This was true 13 years ago with the online game Utopia, and is still true in many web games today, where you get x action points per hour, and different things cost different amounts of points. This mechanic is used in board games and card games, as well, though it's usually along the lines of "you can play X cards on your turn", and is usually a way to keep the game moving.

**Second**: What's the purpose of this? In most online games, the purpose, as Josh pointed out in his answer, is usually to balance players, and prevent someone from having an advantage just because they have more time. If one player can dominate because they can spend 20 hours a day in the game, then no one else can have a chance at winning (or having fun). There are other reasons though. It can spread the content of the game out, so players don't reach the end in a few hours (this is especially useful in MMOs, where games tend to launch without much content). In the case of web games, it can decrease bandwidth usage (bandwidth is no longer an issue, but it was a concern in the early days of the web, and that's probably part of the reason for the convention). Josh also mentions laws in some countries to prevent extended play sessions, as well as encouraging players to return to the game later. These are both valid points.

**Third (and forth)**: Does it bring in money or help retain users? It can. The quote "Leave them wanting more" comes to mind. Forcing users to stop playing will *hopefully* make them want to come back, or at least give them a reason to participate in the "community" side of games ("I've used up all my points for today, let's read the forums for a bit and talk about the game"). It can also be a source of income. "Buy 100 action points for $10" Of course, this can upset the game balance by letting the rich people with free time dominate.

**Finally**: Does it have other applications? Hard to say. TV shows have been doing this sort of thing for years (soap operas excel at it), and TV took the idea from radio dramas ("Tune in next time to see if our hero escapes!"). Prior to that, books were often published in serial format, including Charles Dicken's novels. The wiki article about serial literature includes other examples. How to apply this idea to something that isn't entertainment is an exercise I'll leave to you.

# Answer
> 3 votes
Having never played the \*Ville games, a "Timeout" sounds an awful lot like a "cooldown period", which is not a new concept - all sorts of games have cool down periods (rpgs, mmo, fps, etc). The cooldown period may just be longer for \*Ville games. The other replies mention reasons why.

As for Angry Birds.. particularly Rio - I seem to recall that when the game came out, they specified when you can expect to unlock/play other levels (ie Stage 2 in May, Stage 3 in June, etc). When the level 2 update came out, they removed this timeline completely. And now that the third Stage is out, only half of it is available. I don't know if this is part of their marketing scheme but it seemed to me that they had some trouble meeting deadlines..

Also in the first Angry Birds, I don't remember seeing levels being unlockable after some time. It seemed more like, they issue an update and now there's a new level added (without mentioning it existed in the first place). - Then again, I downloaded the first one months after it came out..

In either of the two angry birds, I don't see how it would bring any *more* revenue seeing as how I play the free version and it updates for free.

# Answer
> 2 votes
One possibile explaination is to encourage players to return to the game later, presumably because it can produce more ad revenue (for ad-supported games, possibly depending on the terms of the ad contract), increased mindshare, or a more diverse social population. The latter is especially important for games with a strong social component.

Another explaination is to keep people *away* from the game. Some countries have laws that involve limiting (or penalizing) a player in certain scenarios if they play for too long. Some games don't want to allow players with vastly more time available to have such an unfair advantage over those with a more casual block of time (this is what the FF 14 developers claimed as the reason the game limits XP gain after eight hours of play, for example).

I'm not too familiar with Angry Birds but it doesn't sound like either of these reasons would really apply to it, so I'm afraid I can't help you there.

---
Tags: social
---


# Question
Title: For timed levels, how do you determine time steps that are less than 1/(frames per second)?
I have made a simple HTML5 racing game. The laps are timed. I am running the game are 40 frames per second, each frame represents 40 milliseconds. There for my timer will increase in 0.025 increments.

My question is how can I get my timer to record lap times more accurately, without running at 100 frames per second! How do other games do it? Could it be to do with gauging the distance from the car to the finish line in the frame before and after it crosses the finish line?

# Answer
> 5 votes
Your own proposed answer is spot on; to determine the finish time for a car, you take its position on the frame before finishing and its position on the frame after finishing, and determine at what point during that frame it actually crossed the finish line.

If (for example) it crossed the finish line at 40% of the way from its previous position to its next position, then you only add 40% of the timestep value to determine the finishing time.

Assuming that your finish line is a straight line, and treating the player's movement from one frame to the next as a straight line, you can easily find where (and then, when during the frame) they crossed by solving a line intersection test.

# Answer
> 0 votes
Okay first off, I don't know how you think you are running 40 frames per second with each frame being 40 milliseconds. 1 second = 1000ms. 40ms per frame gives you an FPS of 25. If you want to actually be at 40 FPS you are going to need to have a timestep of 25ms per frame.

Most racing games run with the car physics at a really high frame rate. One example would be Forza 3, it more sim like than most games, and its physics runs at 360 hertz.

So using a frame rate that is higher than your update rate could work, although with java-script you may be limited with performance.

**If you really need to run at 40 FPS, I see no problem with creating a function that you can plug in the current time, and the distance, and have it return an estimated time.**

---
Tags: javascript, html5, timer, racing, fixed-timestep
---


# Question
Title: Integrating an AI state machine with actions that take more than 1 tick
**Background:** I'm having a problem conceptualising something which seems to be pretty fundamental. We have, what I believe to be, a traditional 'game loop', which runs at 60 fps and iterates through each entity calling it's update method (and later on its draw method). Although probably irrelevant, we're developing the game in Objective-C (for iOS / OSX). Currently an 'Entity' can be assigned a 'Controller', and the controller's 'update' method is called every frame. We would like to introduce a state machine for our AI system.

I understand the concept of having events trigger changes in the current state and we have a base state object with the following methods (heavily inspired by Mat Buckland's AI Book);

```
@interface KTBaseState : NSObject {
    -(void)enter;
    -(void)update;
    -(void)exit;
}

```

The chapter suggests that the 'enter' method might involve entering a mine, and the execute method involves mining. However, we're developing a real time game, and 'entering a mine' is not an immediate action - it might take a few animation frames showing the guy disappear. Equally, it suggests that, on a state transition you call;

```
[oldState exit];
[newState enter];

```

But I would also envision exiting the mine to take a few frames, after which I guess the 'enter action' of the new state would then be allowed to enter / start (say, putting the bag of gold on his shoulder). When the guy's started walking - it's easy to push him around in the state's update method.

Any advice on how best to implement these 'actions' that take longer than the state transition would be greatly received. I thought about implementing some kind of action queue, but I'm not sure exactly how that would work...

1. Some actions would be 'immediately interruptable' (walking -\> being hit) but others wouldn't (mining -\> walking around).
2. You could end up with a massive queue of actions - when all the guy needs to do is run away!
3. In the walking state 'update' method, I would really just want to call "moveTo(destination);" every frame - would you implement this as another 'action', or just push the sprite around the screen?

Sorry for the long text with no specific list of questions. I'm seeking advice on how to approach this problem and I wanted to make sure I was clear in describing what's not clear in my head!

# Answer
The basics are there, but I think you want to break them down a little bit more.

```
State - Find Something To Do
 Enter - Nothing
 Execute - Pick something to do from a big list of options weighted however for this AI personality
 Exit - Transition to new state (For this example its 'Enter Mine')

State - Enter Mine
 Enter - Start playing an enter animation
 Execute - While animation is playing, wait. If Failure, transition to new state 'Find Something To Do' (To figure out how to react to what happened) else Exit
 Exit - Done playing the enter animation - Transition to new state 'Mining'

State - Mining
 Enter - Find something to mine
 Execute - Transition to state 'GoTo', If successful Mine
 Exit - Transition to 'Find Something To Do'

State - GoTo
 Enter - Calculate path to location
 Execute - Move towards path, validate path
 Exit - If made it, return successful event, if didnt make it return failure

```

Now clearly I could keep breaking this down, and just for reference say the 'Find Something To Do' was at the top of it all and one of the random things it picked to do was go mine something..

The point is to break enter/execute/exit down to a complete task, whatever it may be, and build up the overall logic that you want.. Also note that when dealing with animations you may want to break out the animation logic from the AI logic. For instance the enter mine state would OnEnter start the animation, OnExecute Check if the animation is running still and if it is done, then go to OnExit which would then look for something to mine.

EDIT: To address 2), As with anything that can be in a queue or a stack you are going to want a way to wipe it out. Example would be being attacked. Regardless of what you were going to do, you will want to survive and react to being attacked in whatever way possible. Generally with a state machine this shouldn't be a problem as you are just moving from state to state, some of which can be interrupted and others that should not be able to. But if you do want to put in a queue or stack of some sort, do include a logical way for wiping it out when the situation arises.

I hope this helps.. If not feel free to comment and I will try to tailor this more to what you are trying to understand.
> 10 votes

# Answer
As has been said, decoupling the AI logic from the visual logic would be a good thing, because while they are related, they definitely don't want to be closely tied. There are certainly situations where you don't want to move to a new AI state until some visual things have happened, but that is a specific case of the more general problem: that you don't always want to be doing something every frame.

Most times you start out coding AI in an immediate way: every tick you ask the entity what it would like to do this tick, and it considers all its options and makes its decision (keep moving, accelerate, turn around, fire, etc.). You'll quickly run into the limitations of that. In general, you want your AI state machine to be able to simply (and cheaply) do nothing, until 'something else' happens. That might be a timer elapsing, an animation completing, or some other trigger (perhaps from other entities in the world).

Moving to a state machine is the first step towards a more flexible system. But in general I think you want to get away from the notion of 'per-tick' updates for your higher level logic. Higher logic doesn't tend to operate in terms of a regular update cycle like that. It works in terms of events and actions. Actions will very rarely take only one frame to complete. Some may be instantaneous, some may take many ticks. Your systems shouldn't care, and should support all types. It should be possible to tie actions to events occurring, so that your actor can make new decisions based on the fact that an event has occurred.

A queue of some sort is a good way for the actor to maintain memory of 'what am I doing/thinking' between ticks. That's not to say it must blindly work its way through the queue though. It should regularly be looking at its immediate circumstances and re-evaluating. Some circumstances might cause it to junk everything in its queue and replace it with a new set of actions ("Run away!"). Sometimes it might just want to slot in a high priority action at the head of the queue ("bend over and pick up this thing that just landed at your feet, then continue"). Other times it might put in the new action at the end of the queue.

So don't think of a queue like a list of orders to be followed, think of it like a prioritised to-do list that the actor wants to tackle. There are lower level subsystems that put each order into practice (e.g. the queue holds 'go to A'), and a lower level path-finding system actually translates that into a 'how do I move this tick'.
> 0 votes

---
Tags: ai, state, fsm
---


# Question
Title: What are good puzzle game interface design principles?
I'm building a prototype puzzle game at the moment. I'm just curious as to the principles behind building graphic interfaces within games. At the minute I'm looking at designing the graphics for an interface in something like Illustrator. I'm looking at one graphic (650 x 650 px) that incorporates the play area (400 x 550 px) as a blank square, with a nice border on the right hand side (vertically down the screen) and a border along the bottom too. I'm leaving a "blank" rectangle on the vertical border to incorporate a timer into it, and three "blank" squares along the bottom to incorporate icons to represent lives or power-ups or something, which I'll design later and animate later. Is this an acceptable/sensible approach?

# Answer
The first thing you need to design should not be how the game looks like but how you play it, and what the player will need to do (and how).

If you already have these things set, then your approach seems sensible. The idea is to make a fake ingame screen to see how the different interface elements should be placed, so that they give the correct information to the player and not mask any important element in the game.

Then your approach may need some changes according to what the puzzles are ?
> 1 votes

---
Tags: graphics, animation
---


title: Problem drawing text in a for loop

text:
# Question
Title: Problem drawing text in a for loop
```
for (int i = -5; i < 5; i++)
{
    Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);
    spriteBatch.Draw(foregroundTexture, screenRectangle, Color.White);

    Rectangle backGroundRectangle = new Rectangle(x + screenWidth * i, 0, screenWidth, screenHeight);
    spriteBatch.Draw(backgroundTexture, backGroundRectangle, Color.White);

    spriteBatch.DrawString(font, "Variable i:  " + i, new Vector2(0, 0), Color.Brown);
}

```

I want to show on the screen when I'm running the game the counting of `i` like: -5 , -4 , -3...but not in a line, just like a timer. -5 then overwrite it and show -4 overwrite it and show -3 and so on...like seconds of a clock.

The problem is I'm getting a strange painting near the numbers like its repeating and painting something there all the time.

# Answer
This won't work because in your for loop, the *command list* is never actually executed, this happens **only** at the end of the `Draw` function in your `Game` class; this is effectively where the frame ends and is drawn to your screen.

So what you see happening is all your stuff being drawn on the same, single frame, which is what causes the garbage on-screen.

For it to work proplerly, your variable *i* must be outside of the `Draw(GameTime gameTime)` function, and incremented outside of the function also.

At the start of `Draw()` you must call clear and then call your function to draw your backgroud/foreground and text **without** the for loop.

For example :

```
Initialize() {
    i = -5;
}

Update(GameTime gameTime) {
    if(i < 5) ++i;

    base.Update(gameTime);
}

Draw(GameTime gameTime) {
    graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

    Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);
    spriteBatch.Draw(foregroundTexture, screenRectangle, Color.White);

    Rectangle backGroundRectangle = new Rectangle(x + screenWidth * i, 0, screenWidth, screenHeight);
    spriteBatch.Draw(backgroundTexture, backGroundRectangle, Color.White);

    spriteBatch.DrawString(font, "Variable i:  " + i, new Vector2(0, 0), Color.Brown);

    base.Draw(gameTime);
}

```
> 8 votes

---
Tags: xna, c#, xna-4.0
---


title: Physics for Android Game

text:
# Question
Title: Physics for Android Game
I'm making a 2D game for the Android phone, one that involves falling balls. I want to use a physics engine to properly simulate the balls falling and hitting other objects. I'm currently using Phys2D, but when the game runs in the emulator it doesn't look natural; slow and rough. Course, I don't know if this is because of the emulator or Phys2D seeing as how I don't own an Android phone (A real drawback not being able to test on the actual phone, I know, but I can't afford a smartphone).

Anyways, do you think the game would run faster and smoother on an actual android phone, or is it the engine I'm using, or how I'm using it. If it's the engine, any recommendations on Java physics engines?

UPDATE: If you want to test the game yourself, you can find the rough prototype here: http://bpcp.angelfire.com/BallDrop.apk

# Answer
> 3 votes
Emulators can be fairly slow. You'd want to test on real hardware first. Maybe release a free demo and see what kind of feedback you get, or ask a friend to try it?

Even with just an emulator, you can profile your code to see what eats up the most time. Rendering can be a major bottleneck, so that'd be a place to look.

Physics aren't likely to take a lot of time unless you're doing something strange with them or simulating them way too precisely. e.g. if you're simulating 3-inch balls bouncing around, you don't need to be precise to 1/1000th of an inch. Games often sacrifice accuracy in both rendering and physics for speed - nobody's really going to notice or care about slight inaccuracies most of the time.

# Answer
> 1 votes
Of course it depends on how you use the engine. But if you have an demo of your app, I can run it on my smartphone and tell you how it runs.

When you run your game on the emulator, the whole game runs laggy and slow or just part with the falling balls?

# Answer
> 0 votes
How about JBullet? I haven't used it myself, but I've heard good things about it. It's a port of the C++ Bullet Physics Library, so the documentation is pretty good.

---
Tags: android, physics
---


# Question
Title: Are there well-known algorithms for fitting a polygon to an arbitrary shape?
I'm using the Chipmunk physics engine to make the levels for a 2D C game. I'd like to be able to fit a polygon to an arbitrary shape to serve as the collision mask. Given a black and white collision mask for an arbitrary level object like this:

Are there any well-known algorithms for getting this:

I could then use the red polygon to create a physics object to go with the image.

# Answer
This is known as generating a concave hull, and is in the general case pretty complicated (much more so than the convex hull).

One commonly-recommended method is using alpha shapes.

There are more good resources on the problem here, here, and here.
> 8 votes

---
Tags: collision-detection, physics, algorithm
---


# Question
Title: What to focus on in developing a game demo for an interview?
In other threads on this very website, it has been repeatedly stressed that having a game demo to showcase at a job interview is of paramount importance, so I decided to have a go and write my own game demo.

**I would like to know what is typical for interviewers to focus their attention on while reviewing your game demo**.

I shall clarify that I don't have a specific opening available to me right now, but that I would probably target **gameplay and/or AI programming positions**. Because of this I can answer by myself in terms of broad categories: "fancy graphics" shouldn't be my priority focus while "computer's players behaviour" should... Yet - having no direct experience of this industry - I would like to know if there are less obvious stuff I should pay attention to:

* How important is code modularity?
* How important is to showcase a typical algorithm implementation?
* How important is to include novel features?
* How important is playability?
* Should I privilege code readability or code optimisation?
* How important is code documentation?
* etc...

Mind that the above are **just examples to illustrate the level of detail** I would appreciate in the answer, they are not specific subquestion that I would necessarily like to be addressed (unless you think it's relevant to discuss some of them).

Thanks in advance for your time and expertise.

# Answer
> 13 votes
Don't write a demo *for* an interview if you can avoid it; submit existing code or projects if you can.

Demos and code samples are important for a lot of reasons (which vary by reviewer), but mostly they are about showing potential employers the kind of code you write in the wild and the kind of problems you are interested in solving. They also help demonstrate your level of interest in the craft of software development.

It's much better to submit some code you've already written for a previous project or game you've written that you are proud of, or that demonstrates a clever solution to a problem -- anything that is interesting or difficult or that can serve as the basis for a good discussion.

Writing code explicitly to submit as sample code tends to come across as contrived and fake; it can be surprisingly easy to tell, for example, that a programmer thought that a potential employer would want to see "well documented" code and thus put really detailed comments on everything, striving for what they believe to be perfection. Real code isn't perfect, it has warts and rough edges, and when you write code explicitly for demo submission you tend to polish it so much that it becomes obvious you didn't write this because you loved the writing of it. You just wanted a job.

That said, if you don't have any work you can submit -- either because you haven't written any yet or because your previous job prevents you from submitting any of the code (under NDA) -- you don't have a lot of options but to write something new. In that scenario I would encourage you to focus on *writing the thing for its own sake*, and forget about what employers "want." Write a game because you want to write a game. Write a cool tech demo because you want to explore that tech, because that's what you are interested in.

> * How important is code modularity?
> * How important is to showcase a typical algorithm implementation?
> * How important is to include novel features?
> * How important is playability?
> * Should I privilege code readability or code optimisation?
> * How important is code documentation?

The answers to all these smaller questions are, unfortunately, "it depends" (except for the readability thing -- I think you should favor readability in general, especially for "demo code"). Some employers may want to see you reimplementing quicksort. Others may not care. Others will just ask you to reimplement quicksort on a whiteboard at the interview anyhow.

**Don't focus on what you think employers want**, because different employers and even different people who may review your code will want different things. **Focus instead on what you want to showcase about yourself**, because you have far more control over that and it will benefit you more in the long run.

---
Tags: game-design, career, jobs, demo
---


# Question
Title: How to load and render a 3D model? C++ SDL, OpenGL
I have been learning C++ for long time (but only learning game development for eight days) and I have made a simple game using 2D textures.

I was thinking of starting on 3D game development. I wanted to begin by loading and rendering a 3D model on the program, but I dont know how.

Can anybody tell me if this function could be changed to output 3D model:

```
GLuint loadTexture( const string &fileName )
{
SDL_Surface *image = IMG_Load( fileName.c_str() );

SDL_DisplayFormatAlpha(image);

unsigned object(0);

glGenTextures(1, &object);

glBindTexture(GL_TEXTURE_2D, object);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image -> w, image -> h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, image -> pixels);

//Free surface
SDL_FreeSurface(image);

```

Also what format should I use for this? I am using Blender, and I have seen it can export to a variety of formats. I don't know which would be the best for this kind of stuff and for serious game development.

# Answer
> 3 votes
Be warned that the transition into 3D graphics from 2D is much more difficult than the transition into 2D graphics initially. It is much more important to understand the fundamental mathematics involved in 3D graphics, lest you end up breaking your code in ways that won't seem to obvious. I would recommend you familiarize yourself with basic linear algebra, matrices and vectors. If you have the resources, purchasing the books "A Geometry Toolbox" and/or "Fundamentals of Computer Graphics, 3rd Ed," would be great.

That said, it sounds like the crux of your specific question has to do with loading 3D models. You won't really be able to adapt your existing texture loading function for that purpose (although you will still find texture loading useful when you want to apply textures to your models).

Blender can indeed export a variety of formats -- there is no such thing as the "best" choice here, as all options have pros and cons. Some, however, have more of one or the other. Starting out, I would recommend you try to parse and load the .obj file format. It's very straightforward, and you should be able to find a variety of example code and tutorials online to help you load it if you get stuck.

There's also the .smd file format, which is only slightly more complex and supports animation.

If you prefer to avoid writing the loaders yourself, you can use a 3rd party library like the Open Asset Importer Library.

# Answer
> 1 votes
This function (`loadTexture()`) appears to be for loading textures, not rendering 3D models.
Here is a tutorial on C++ OpenGL, it starts out basic, but goes into 3D rendering farther on in the tutorial

---
Tags: opengl, c++, sdl, 3d-meshes, file-format
---


# Question
Title: Warcraft 3 Editor - Not triggering the Wait action?
Ok so this is mind boggling to me. Every time I've used something similiar before it works. I added messages to be displayed before everything happened to see where it would, and it never got past the wait.

```
Events
     Unit - A unit Begins casting an ability
Conditions
     (Ability being cast) Equal to Berserking Power [E]
Actions
     Unit Group - Add(Triggering unit) to heroSpellUG[(Player number of (Owner of (Triggering unit)))]
     -Unit Group - Pick every unit in heroSpellUG[(Player number of (Owner of (Triggering unit)))]
           Unit - Add Berserking Power Damage to (Picked Unit)
           Unit - Set level of Berserking Power Damage for (Picked Unit) to (Level of Berserking Power [E] for (Picked Unit))
           Wait (5.00 + (Real((Level of Berserking Power [E] for (Picked Unit))))) game-time seconds
           Unit - Remove Berserking Power Damage from (Picked Unit)
           Unit Group - Remove (Picked Unit) from heroSpellUG[(Player number of (Owner of (Picked Unit)))]

```

So I guess my question is, why is the Wait not completing. I had it display what the time to wait was and it said 6 seconds at level one. Any help would be appreciated.

# Answer
Umm, i have a few things to mention here ...

First you're using GUI which is in WC3 really weak and not useful, try to learn Jass and vJass they're more powerful

Second, there are plenty of forums made for Wc3 the best i know is a wc3c. They can help you better than we can do.

Third, it seems that you are trying to do something like a berserk skill, you should try to create a dummy unit add it an ability with the buff and the duration you want and let it cast the ability on all units u want to have the buff.

Forth, waits in picks are stupid, because they will go like this: First unit gets buffed - 6 seconds wait - debuff - Second unit gets buffed - 6 seconds wait - etc. I guess you don't want it to happen like this
> 1 votes

# Answer
Not sure what you're trying to accomplish, but that doesn't look right at all:

* You are calling a `wait` inside the loop, meaning if there are two units in the `heroSpellUG` group, the second unit will not get the `Berserking Power Damage` attribute until *after* `Berserking Power Damage` has been added and removed from the first unit (~ 6 seconds later)
* Because this is being called asynchronously (every time a unit casts `Berserking Power`), and you are adding and removing from a unit-group inside a loop, you are almost certainly opening yourself up to race conditions that occur when two units cast `Berserking Power` at the same time.

It's been a while since I've done any WC3 scripting, but what you probably want to do is add the ability to *only* that unit, then create a timer which takes away the ability when it expires.
> 1 votes

# Answer
Try it with just one unit triggering the effect. When multiple units trigger the effect the they will only receive your buff sequentially. Also unit groups and picks will create memory leaks, try to avoid them. Also try it with a static time, and add a message at the very end of the script to debug it.
> 0 votes

# Answer
What do you mean by "not completing"?
Does it never end?
Does it never happen?

You might wanna ask on www.hiveworkshop.com where your chances to get an answer are 100000 times greater than on www.wc3c.net...

Edit: Seshiro said

```
Forth, waits in picks are stupid, because they will go like this: First unit gets buffed - 6 seconds wait - debuff - Second unit gets buffed - 6 seconds wait - etc. I guess you don't want it to happen like this

```

This is true, but also during the wait the trigger may run again, so the first unit in the group (`UnitGroup`s are queues) will get the effect lots of times and the others will get it slowly...
> 0 votes

---
Tags: modding
---


# Question
Title: What do these STATE_CREATION warnings mean in the DX11 debug output?
So I've been fighting my way through learning the DirectX 11 API with what little documentation there is out there and noticed some new D3D11 warnings in my debug output. (Atleast I think they are new, been rearranging my draw calls to try and solve another problem I'm experiencing at the moment) Anywho, with some Google-fu I've been unable to find any documentation on the error codes or anything but the general consensus of forums seems to be that the COM objects aren't properly being released.

Now the question is, if that is indeed what the warnings mean, what else do I need to do to kill these things other then call their Release() functions? And is there somewhere this kind of information is posted? I sure can't find it on MSDN or Google. Just lots of confused DX11 post with unanswered questions.

Here is the debug output.

```
D3D11: WARNING: Live Device: Name="unnamed", Addr=0x004C6488, ExtRef=5 [ STATE_CREATION WARNING #2097297: LIVE_DEVICE ]
D3D11: WARNING: Live Texture2D: Name="unnamed", Addr=0x04552E94, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097235: LIVE_TEXTURE2D ]
D3D11: WARNING: Live Buffer: Name="unnamed", Addr=0x04552A64, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097229: LIVE_BUFFER ]
D3D11: WARNING: Live Buffer: Name="unnamed", Addr=0x04566ECC, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097229: LIVE_BUFFER ]
D3D11: WARNING: Live InputLayout: Name="unnamed", Addr=0x0455280C, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097265: LIVE_INPUTLAYOUT ]
D3D11: WARNING: Live PixelShader: Name="unnamed", Addr=0x004CDDE4, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097262: LIVE_PIXELSHADER ]
D3D11: WARNING: Live VertexShader: Name="unnamed", Addr=0x04553944, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097250: LIVE_VERTEXSHADER ]
D3D11: WARNING: Live RenderTargetView: Name="unnamed", Addr=0x0455269C, ExtRef=0, IntRef=0 [ STATE_CREATION WARNING #2097244: LIVE_RENDERTARGETVIEW ]
D3D11: WARNING: Live Texture2D: Name="unnamed", Addr=0x04552214, ExtRef=4294967295, IntRef=1 [ STATE_CREATION WARNING #2097235: LIVE_TEXTURE2D ]
D3D11: WARNING: Live Query: Name="unnamed", Addr=0x004C84AC, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097280: LIVE_QUERY ]
D3D11: WARNING: Live Sampler: Name="unnamed", Addr=0x004C8274, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097268: LIVE_SAMPLER ]
D3D11: WARNING: Live RasterizerState: Name="unnamed", Addr=0x004C804C, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097277: LIVE_RASTERIZERSTATE ]
D3D11: WARNING: Live DepthStencilState: Name="unnamed", Addr=0x004C7E24, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097274: LIVE_DEPTHSTENCILSTATE ]
D3D11: WARNING: Live BlendState: Name="unnamed", Addr=0x004C7C6C, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097271: LIVE_BLENDSTATE ]
D3D11: WARNING: Live Context: Name="unnamed", Addr=0x0453006C, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097226: LIVE_CONTEXT ]
D3D11: WARNING: Live Device Child Summary: Device Addr=0x004C6488
Using ID3D11Debug::ReportLiveDeviceObjects with D3D11_RLDO_DETAIL will help drill into object lifetimes. Objects with ExtRef=0 and IntRef=0 will be eventually destroyed through typical Immediate Context usage. However, if the application requires these objects to be destroyed sooner, ClearState followed by Flush on the Immediate Context will realize their destruction.

```

Note: Clearing and Flushing the device context doesn't seem to affect anything.

Thanks in advance!

**Solution**

A slight tweak in my code prevented objects from being shut down and releasing their COM objects.

# Answer
> 15 votes
The warnings are informing you of live (unreleased) objects, as you've discovered. Releasing the objects you retain references to is the proper way to clean them up, but you have to release the right objects. There are several ways you can get help tracking down which objects are being retained and from there you can follow the lifetime of those objects through your code and determine where you are missing calls to decrement the COM reference count.

The first thing to do is look at the `ExtRef` and `IntRef` columns. `IntRef` refers to the number of internal references to the object, within D3D itself. These aren't your responsibility to free, but they are an indicator that you're probably holding an external reference to something that is itself holding an *internal* reference to those objects.

The `ExtRef` column indicates the number of references that your holding. In this case, you appear to have five outstanding references to the D3D device itself, and the device is probably holding references to all the objects with internal reference counts, leaking them. Tracking down where you need to add additional calls to `Release` on your device will probably solve most of your problems. You also appear to have outstanding references to some shader and buffer objects.

You can also, as the last line of the output suggests, use the ID3D11Debug interface's ReportLiveDeviceObjects method to get more information on where these objects are coming from and what might be holding on to a reference to them.

Finally, take a look at this post by Chuck Walbourn which details giving your objects unique names to replace the "unnamed" strings in the output, which may also help narrow down the problem.

Without code -- and I presume you have too much of it to reasonably post here -- it's hard to provide more specific direction, unfortunately.

Two other notes:

* The message's talk of clearing and flushing refers to objects with zero internal *and* external references -- most of the objects in your report wouldn't be cleaned up by doing that, as you've discovered.
* "STATE\_CREATION" is one of the predefined message categories used by the D3D11 InfoQueue class. I don't know for sure why this category is used for leak messages instead of the seemingly more appropriate "CLEANUP" category; I suspect it's a bug.

---
Tags: directx11
---


# Question
Title: Separating logic/update from render/drawing code in a single thread using sleep
I've read that the speed of game objects should not be hindered by FPS but instead should be based on time. How can I seperate the update/draw code to maximize performance without limiting the drawing rate and provide a constant logic update rate based on time?

My current pseudo code is as follows

```
loop
{
    draw();
    if (ticksElapsed() > 100)
    {
        update();
        ticks+= ticksElapsed();
    }
}

```

The problem is the drawing code hinders the performance of the update() rate. And it consumes 100% cpu because if sleep is thrown in, it throws off both drawing/logic functions.

I am also using SDL and it doesn't seem to have a vsync option. I've also heard of the terms fixed and variable time-stepping however I'm not sure how that can be done with sleep()

# Answer
In your code snippet it looks like you're trying to run your game in fixed-time step mode by busy-waiting if your drawing and updating took less then 15ms (60fps). This is possible and you guessed right that this can't be done using a sleep call because you don't exactly know how long you're going to sleep. The busy-waiting-loop is the good solution.

However consider the case where your updating and drawing exceed 15ms, you now have the game drawing and updating to slow. You can now do either two things: detect this state and drop frames (skip drawing and go straight to updating until you are in sync again) however if the computer is just to slow it will never catch up.

An other solution is to make your update logic fixed-time independent. You don't need a separate thread for this, you just have to respecify how fast things should move. Instead of 5pixels per tick, you should use 50pixels per second. You would need a high precision timer to achieve this, and all your update logic should be able to access the timer to see how much time passed since last update.

Basically you go from:

```
void UpdatePlayer()
 player.x += 10;

```

To

```
void UpdatePlayer(float elapsedSeconds) //the total seconds elapsed since last update
 player.x += walkspeed * elapsedSeconds;

```
> 3 votes

---
Tags: sdl, frame-rate, logic, fixed-timestep
---


title: Point Light Soft Shadows

text:
# Question
Title: Point Light Soft Shadows
How to implement soft shadows for omni directional (point) light. We use typical shadow mapping technique. Depth is rendered to texture cube and addresing is pretty simple then. Just using vector from light to fragments world position. It works perfectly. Until you want soft shadows. In our engine we use PCSS technique for spot lights. But for point light there begins troubles.

How to sample in 3D?

I developed technique when orthonormal basis is created from a direction and upvector (0,1,0). And then multiply sampling vector (something like this (1.0,i/depthMapSize,j/depthMapSize) with this basis. But this (of course :)) looks pretty bad for vectors near (0,1,0) and (0,-1,0).

I will appreciate any help on this.

# Answer
> 2 votes
Well as a simple hack on your current technique, you could choose between two up-vectors based on whether your view vector is tending towards parallel with one.

It'd just be an abs, compare, and select in shader terms, so not much overhead - especially considering the sampling and blending...

# Answer
> 0 votes
You are using a cube map to represent a point light's shadows.

In this case, it is roughly equivalent to having 6 spot lights joined together.

You need to perform the PCSS blocker search on each of the 6 shadow maps, to find a penumbra value for each shadow map (in the same way that it is done for a single spot light).

Then you simply blend between each penumbra value as you already do for the shadow mapping step that you have already implemented.

This can be optimized because a receiving object can be blocked by an object in at most 3 shadow maps -- so really only three PCSS blocker searches are required. However, get the simpler version working first.

---
Tags: directx, shadows, shadow-mapping
---