# Question
Title: What should I keep in mind when developing a game to be multiplayer?
I am making 2d game, and it will be a game where players can move on in a 2D world and there will be physics with projectiles and such.

So far, I don't have much, just a tile engine a few other things.

But this game is going to be fully multiplayer, and I've never made a multiplayer game before. Obviously I can't be making multiplayer as I develop the game, I kind of have to make it and then hope it works once I add multiplayer.

So my question is, is there anything I should keep in mind when developing this game to be multiplayer? I'm not asking, how to make it multiplayer, thats a whole other question. I just don't want to have to re-develope everything because I did something wrong that does not work with multiplayer?

Edit: Also, as a side question, do you have any advice on what general order to create the game, and when to add multiplayer?

# Answer
> 9 votes
I think the basic answer here *is* to expect to "have to redevelop everything" when you add networking.

**Adding networking will touch almost every part of your game - both *code* and *design*.**

A lot of the difficulty comes down to dealing with latency (there's also things like packet-loss and out-of-order packets). If your game is real-time, you'll want to "hide" these network realities from the user.

Code-wise, this (in an *extremely* abstract sense) means making your simulation tolerant of inconsistencies - and then introducing a bunch of them. I can't really get any more specific than that without going into a very long and detailed discussion of how game networking works.

That that basically describes the same dilemma that you face: You can't guess at how to make your simulation network-ready without having a full understanding of how game networking works (and how it relates to your game specifically). And the way to fully understand it is to implement it.

Design-wise it's a similar story. There are several classes of gameplay ideas that will not work due to latency. Just one example is any competition where one player can be first, with immediate feedback and split-second timing. Player A might be 100ms slower than player B to hit a button - but because they are separated by 400ms of latency - they both think they won. So if your gameplay contains any scenarios like that, you would have to re-design them.

To summarise: It's perfectly valid to write a single-player game first and then add multiplayer later. One benefit of this strategy is that you get a working single-player game earlier. However, if you go down this route, then expect to have to treat your single-player game like a throw-away prototype when it comes time to make a networked version.

(Trying the opposite path - trying to account for networking without actually implementing it - is a gross violation of YAGNI.)

It's worth finishing by pointing out that making a networked game is easily an order of magnitude more difficult than making non-networked game.

# Answer
> 3 votes
There are generally two ways to implement networking on a high level: Either, you always get the perfect status of every object in your proximity, or you get the actions objects want to perform.

First one can easily be described by using MMORPG as example. You have a character, and the server always tells you what's going on. This means constantly getting positions and state for *all* objects around you. So the player's end is just a dumb client showing everything. While this will seem much easier than the solution presented below, this have some major drawbacks. This will use a huge amount of network traffic if not planned and executed properly. This will also easily allow cheating if you don't verify the data by the user's somewhere. If you have client/server architecture the clients can be dumb and just show what's given by the server. But the server will either need to apply the technique below for the data received by the players, or verify that their actions are legal. If this is used in a P2P situation, you will have a much harder time detecting cheating.

The second one is how they did the Age of Empires. See this link for some good reading. In this case, each user is sent what the other user's are trying to do. For instance in AoE, each frame sending over the position and state of thousands of units would be a bad idea. If you instead are sent the actions taken by the player it will be much less data. As this will only be some actions per second. Then you will have to take those actions and apply them to your running game. Here you will need good planning to not make the games on different computers get out of synx.

You **should** fix your timestep if your game has physics or some kind of simulation that depends on it. Otherwise the game will go out of sync fast. Remember that even the slightest difference in the beginning can be huge in the end. The Butterfly Effect. For instance, a can being thrown landing a bit shorter on one of the player's running game. This again will affect the AI on his end, and suddenly he is playing a different match than the others. Read this article about fixing your timestep.

For a big MMO like World of Warcraft this second solution would be bad, as each player has to be running his own server and get the actions for every person logged on. But for games like FPS and RTS with P2P this rocks.

Gafferon has also some good tutorials on networking for game programmers, check them out. Just note that some of his arguments only hold for the kind of game he is talking about. There's a big difference in MMORPG networking and FPS networking.

---
Tags: xna, multiplayer
---


# Question
Title: Is there any reason not to save skinning animation data in texture?
I have thought about saving animation data in texture. I think I can save shader parameter setting and interpolation cost in CPU, and also enable animated instancing.

But I couldn't find no text mentioning about this, so I think there's some obvious reason people don't do this. Which I'm missing.

Can I know what I missed? Or is this just widely known technique?

# Answer
> 2 votes
The main reason to *not* do skinned mesh instancing is that the vertex shaders texture fetch is fairly slow compared to other instructions (not sure to what degree), however you need to compare this with doing an extra draw call per instance instead.

To tell if you gain or lose on using instancing you would have to measure your particular code, in most cases you will probably gain on it as long as your rendering more than a trivial number of models.

Skinned Model Instancing has some nice information, its targeted towards XNA but has a section on performance which would be applicable.

---
Tags: opengl, animation, textures, opengl-es2
---


title: Multi-textured Terrain?

text:
# Question
Title: Multi-textured Terrain?
How would I accomplish multi-textured terrain? I need to know how to write the HLSL shader for it. The world already UV maps itself and I can get it to do 1 texture at a time. But I want more than 1 texture being displayed on my screen.

Here is my vertex declaration.

```
D3DVERTEXELEMENT9 Decl[] =
    {
        {
            0,
            0,
            D3DDECLTYPE_FLOAT3,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_POSITION,
            0
        },
        {
            0,
            0,
            D3DDECLTYPE_FLOAT3,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_TEXCOORD,
            0
        },
        {
            0,
            0,
            D3DDECLTYPE_FLOAT3,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_TEXCOORD,
            1
        },
        D3DDECL_END()
    };

```

I am also using D3DFVF\_XYZ and D3DFVF\_TEX2

My variables for for each vertex are X, Y, Z, U1, V1, W1, U2, V2, W2

# Answer
> 2 votes
In principle multitexturing is as simple as performing multiple texture fetches in the pixel shader and then blending the two colors together using some formula (average, min, max, etc).

For greatest control you can use multiple UV coordinates (using TEXCOORD0, TEXCOORD1, etc) and having multiple textures set to the effect, but you can also use a single UV coordinate and simply scale it when working with terrain, especially if you generate the terrain.

A quick search on "hlsl multitexturing" gave me this tutorial which might be a good start for you.

---

> I need it so that 1 part of my terrain has a certain texture and the only part needs a completely different texture. Not mixing 2 textures together.

Assuming your textures are both 128x128 what you can do is make a new image that is 256x128 (or 256x256), copy your first texture into the (top) left part of the new image, and the second texture into the right part.

Now you modify your UV coordinates on the mesh, the parts that want the first texture get their U halved (so it goes into the left part of the 256x128 texture) and the ones that want the second texture are halved and get 0.5 added (so it goes into the right part of the combined texture).

Your terrain should now render with 2 textures. You may notice some artefacts where you go from one to the other texture, this can be fixed by duplicating the vertices at the seam, so that the triangle that wants the left texture does not share any vertices with the triangle that want the right texture.

This wouldn't be referred to as multitexturing, seeing as how your only using one texture (which just happens to be a texturemap with multiple textures in it).

**To solve it with actual multitexturing** you would use two Vector3 UV coordinates, the z component would be used for weight, two textures (which can be your original two textures) and then a hlsl pixel shader that blends the two.

Since you can chose the weight of both textures you can chose to make a quick transition by changing z from 0 to 1 and vice versa for the second texture. This option has the benefit of allowing you to slowly blend textures in places when you want to, but the drawback of requiring a special shader which does twice the work of the single texture one (in terms of texture fetches).

```
float4 col1 = tex2d(texture1, uv1.xy)
float4 col2 = tex2d(texture2, uv2.xy)

float4 color = (col1 * uv1.z) + (col2 * uv2.z) / (uv1.z + uv2.z)

```

**You can also split the mesh** into multiple parts, this allows you to use the same textures as in the multitexturing version, with the same shader as in the single texture version. But requires two draw calls instead of a single draw call.

Simply go through each vertex and if it needs the first texture, add it to the first mesh, and if it needs the second vertex, add it to the second mesh. Make sure that the edge vertices, between the two textures, are duplicated so that you do not get any holes in your terrain.

This is the simplest option, but making a texturemap would have better performance and multitexturing would be more flexible (such as going from all grass to gravel can be done smoothly instead of having a sharp line, where you chose to do so)

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


title: Where is my memory leak coming from?

text:
# Question
Title: Where is my memory leak coming from?
This is a long shot ... but I'm going to paste in my code to see if anyone can figure out where my memory leak is coming from.

It's a lot of code... so I advise you NOT to bother answering this unless you're really bored/really kind :D

```
#include "SDKsound.h"
#include "Nig.h"
#include "DXUT.h"
#include "DXUTgui.h"
#include "DXUTmisc.h"
#include "DXUTCamera.h"
#include "DXUTSettingsDlg.h"
#include "SDKmisc.h"
#include "SDKmesh.h"
#include "resource.h"
#include "Thing3D.h"
#include "Thing3DObj.h"
#include "AllThings.h"
#include "Fire.h"
//#include "D3DEnumeration.h"
#include <list>
#include <sstream>

//#define DEBUG_VS   // Uncomment this line to debug D3D9 VERTEX shaders
//#define DEBUG_PS   // Uncomment this line to debug D3D9 pixel shaders

    HWND              m_hWnd;              // The main app window
CFirstPersonCamera          g_Camera;               // A model viewing camera
CDXUTDialogResourceManager  g_DialogResourceManager; // manager for shared resources of dialogs
CD3DSettingsDlg             g_SettingsDlg;          // Device settings dialog
CDXUTTextHelper*            g_pTxtHelper = NULL;
CDXUTDialog                 g_HUD;                  // dialog for standard controls
CDXUTDialog                 g_SampleUI;             // dialog for sample specific controls

// Direct3D 9 resources
extern ID3DXFont*           g_pFont9;
extern ID3DXSprite*         g_pSprite9;

// Direct3D 10 resources
ID3DX10Font*                g_pFont10 = NULL;
ID3DX10Sprite*              g_pSprite10 = NULL;
ID3D10Effect*               g_pEffect10 = NULL;
ID3D10InputLayout*          g_pVERTEXLayout = NULL;
ID3D10EffectMatrixVariable* g_pmWorldViewProj = NULL;
ID3D10EffectMatrixVariable* g_pmWorld = NULL;
ID3D10EffectScalarVariable* g_pfTime = NULL;
LPD3DXFONT                  m_font;

EffectForAbstractThing3D *g_p_Effect;
Thing3DObj              *box;
Thing3D                 *gameFloor;

Thing3D                 *character;
Thing3D                 *leftWing;
Thing3D                 *rightWing;

AllThings               *all;
Fire                    *shoot;
//Camera                    *cam;
bool        fire                    = false;

//Amount of boxes destroyed in the game
int         boxCount        = -1;
int         frameCount      = 0;
int         difficulty      = 16;
//Thing3D                  *floor;
float       camRotateY     = 0.0;
float       boxTimer     = 0.0;

bool        g_b_WButtonDown         = false;    //Status of keyboard.  Thess are set
bool        g_b_SButtonDown         = false;    //in the callback KeyboardProc(), and
bool        g_b_AButtonDown         = false;    //are used in onFrameMove().
bool        g_b_DButtonDown         = false;
bool        g_b_QButtonDown         = false;
bool        g_b_EButtonDown         = false;
bool        g_b_ShiftButtonDown     = false;
bool        g_b_SpaceButtonDown     = false;
bool        g_b_ReturnButtonDown    = false;

bool        startScreen             = true;

//Define the Keyboard keys for game play
#define VK_W              0x57
#define VK_S              0x53
#define VK_A              0x41
#define VK_D              0x44
#define VK_Q              0x51
#define VK_E              0x45

bool        g_b_CameraOnThing      = false;

// Wing Movements
bool flapDown = false;
bool leftFlapDown = false;

float leftFlap;
float rightFlap;
float flap;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
#define IDC_TOGGLEFULLSCREEN    1
#define IDC_TOGGLEREF           2
#define IDC_CHANGEDEVICE        3
#define IDC_TOGGLEWARP          4

//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
                          void* pUserContext );
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );

extern bool CALLBACK IsD3D9DeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat,
                                             bool bWindowed, void* pUserContext );
extern HRESULT CALLBACK OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice,
                                            const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext);
extern HRESULT CALLBACK OnD3D9ResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
                                           void* pUserContext );
extern void CALLBACK OnD3D9FrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime,
                                        void* pUserContext );
extern void CALLBACK OnD3D9LostDevice( void* pUserContext );
extern void CALLBACK OnD3D9DestroyDevice( void* pUserContext );

bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType,
                                       DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
                                      void* pUserContext );
HRESULT CALLBACK OnD3D10ResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain,
                                          const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
void CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext );
void CALLBACK OnD3D10DestroyDevice( void* pUserContext );

void InitApp();
void RenderText();
void setStaticCameraPosition();
void setDynamicCameraPosition();
void flapWings(float fElapsedTime);
int randomm(int min, int max);
void onClose();
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
    // Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

    // DXUT will create and use the best device (either D3D9 or D3D10)
    // that is available on the system depending on which D3D callbacks are set below

    // Set DXUT callbacks
    DXUTSetCallbackMsgProc( MsgProc );
    DXUTSetCallbackKeyboard( OnKeyboard );
    DXUTSetCallbackFrameMove( OnFrameMove );
    DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );

    DXUTSetCallbackD3D9DeviceAcceptable( IsD3D9DeviceAcceptable );
    DXUTSetCallbackD3D9DeviceCreated( OnD3D9CreateDevice );
    DXUTSetCallbackD3D9DeviceReset( OnD3D9ResetDevice );
    DXUTSetCallbackD3D9DeviceLost( OnD3D9LostDevice );
    DXUTSetCallbackD3D9DeviceDestroyed( OnD3D9DestroyDevice );
    DXUTSetCallbackD3D9FrameRender( OnD3D9FrameRender );

    DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable );
    DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice );
    DXUTSetCallbackD3D10SwapChainResized( OnD3D10ResizedSwapChain );
    DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10ReleasingSwapChain );
    DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice );
    DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender );

    InitApp();
    DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params
    DXUTSetCursorSettings( true, true );
    DXUTCreateWindow( L"David Sigley - 10173065" );
    DXUTCreateDevice( true, 640, 480 );
    DXUTMainLoop(); // Enter into the DXUT render loop

    //Delete things

    delete g_p_Effect;
    delete box;
    delete gameFloor;
    delete character;
    delete leftWing;
    delete rightWing;
    delete all;
    delete m_hWnd;
    //delete g_pTxtHelper;

    //delete g_pFont9;
    //delete g_pSprite9;
    //delete g_pFont10;
    //delete g_pSprite10;

    delete shoot;

    _CrtDumpMemoryLeaks();
    _CrtSetBreakAlloc(0x00823C20);

    return DXUTGetExitCode();
}

//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
void InitApp()
{
    g_SettingsDlg.Init( &g_DialogResourceManager );
    g_HUD.Init( &g_DialogResourceManager );
    g_SampleUI.Init( &g_DialogResourceManager );

    g_HUD.SetCallback( OnGUIEvent ); int iY = 10;
    g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 );
    g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 );
    g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22, VK_F3 );
    g_HUD.AddButton( IDC_TOGGLEWARP, L"Toggle WARP (F4)", 35, iY += 24, 125, 22, VK_F4 );

    g_SampleUI.SetCallback( OnGUIEvent ); iY = 10;
}

//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
void RenderText()
{
    g_pTxtHelper->Begin();
    g_pTxtHelper->SetInsertionPos( 5, 5 );
    g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
    g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
    g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() );
    g_pTxtHelper->End();
}

//--------------------------------------------------------------------------------------
// Reject any D3D10 devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType,
                                       DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
    return true;
}

//--------------------------------------------------------------------------------------
// Create any D3D10 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
                                      void* pUserContext )
{
    HRESULT hr;

    V_RETURN( D3DX10CreateSprite( pd3dDevice, 500, &g_pSprite10 ) );
    V_RETURN( g_DialogResourceManager.OnD3D10CreateDevice( pd3dDevice ) );
    V_RETURN( g_SettingsDlg.OnD3D10CreateDevice( pd3dDevice ) );
    V_RETURN( D3DX10CreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
                                OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
                                L"Arial", &g_pFont10 ) );
    g_pTxtHelper = new CDXUTTextHelper( NULL, NULL, g_pFont10, g_pSprite10, 15 );

    //**********************************************************************//
    // We use the camera object to store the View and Projection matrices.  //
    // The projection matrix is created in OnD3D10ResizedSwapChain().       //
    // Setup the camera's view parameters here, which creates the view      //
    // matrix.                                                              //
    //**********************************************************************//

    setStaticCameraPosition();

    //**********************************************************************//
    // Create a new thing and create a shader effect and a mesh to go with  //
    // it.                                                                  //
    //**********************************************************************//

    g_p_Effect = new EffectForAbstractThing3D(pd3dDevice, L"Thing3D.fx");

    g_p_Effect->lightDirection       = D3DXVECTOR4(0, 1, -1, 1);
    g_p_Effect->lightDiffuseColour   = D3DXVECTOR4(1, 1, 1, 1);

    //**********************************************************************//
    // Create a new thing and plug the shader effect and various other stuff//
    // into it.                                                             //
    //**********************************************************************//
    //HWND hWnd;

    shoot = new Fire();
    shoot->AddAll(pd3dDevice, g_p_Effect);
    //shoot->initSound("Media\\Sounds\\fire.WAV", m_hWnd);

    gameFloor               = new Thing3D(pd3dDevice);
    gameFloor->setEffect(g_p_Effect);
    gameFloor->createMesh(L"Media\\Stolen\\TankScene.sdkmesh");
    gameFloor->setInitialDirection(0, 0, -1);
    gameFloor->setScale(50, 50, 50);
    gameFloor->moveTo(0, -50, 0);

    //thing      = new Thing3DObj(pd3dDevice);
    box      = new Thing3DObj(pd3dDevice);
    character      = new Thing3D(pd3dDevice);
    leftWing      = new Thing3D(pd3dDevice);
    rightWing      = new Thing3D(pd3dDevice);
    //all               = new AllThings(character, leftWing, rightWing);
    all             = new AllThings();

    all->body = character;
    //all->bodyObj = box;
    all->leftWing = leftWing;
    all->rightWing = rightWing;

    character->setEffect(g_p_Effect);
    character->createMesh(L"Media\\Tiger\\tiger.sdkmesh");
    character->setInitialDirection(0, 0, -1);
    character->setScale(1, 1, 1);
    character->setGravity(true);
    character->rotateBy(0, 3.14, 0);

    box->setEffect(g_p_Effect);
    box->createMesh(L"Media\\\Stolen\\Box\\WoodenBoxOpen02.obj");
    //box->createMesh(L"Media\\\wateringcan_obj\\wcan.obj");
    box->setInitialDirection(0, 0, -1);
    box->setScale(1, 1, 1);
    //box->setGravity(true);

    leftWing->setEffect(g_p_Effect);
    leftWing->createMesh(L"Media\\Wing\\wing.sdkmesh");
    leftWing->setInitialDirection(0, 0, -1);
    leftWing->setScale(1, 1, 1);

    rightWing->setEffect(g_p_Effect);
    rightWing->createMesh(L"Media\\Wing\\wing.sdkmesh");
    rightWing->setInitialDirection(0, 0, -1);
    rightWing->setScale(1, 1, 1);

    return S_OK;
}

//**************************************************************************//
// Create any D3D10 resources that depend on the back buffer.  This         //
// includes creating the projection matrix, which is stored in the camera.  //
//**************************************************************************//

HRESULT CALLBACK OnD3D10ResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain,
                                          const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
    HRESULT hr;

    V_RETURN( g_DialogResourceManager.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
    V_RETURN( g_SettingsDlg.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );

    float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height;
    g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 1000.0f );
   // g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
    //g_Camera.SetButtonMasks( MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON );

    g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
    g_HUD.SetSize( 170, 170 );
    g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 );
    g_SampleUI.SetSize( 170, 300 );

    return S_OK;
}

void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
{
    D3DXMATRIX matWorld;
    D3DXMATRIX matView;
    D3DXMATRIX matProjection;

    float ClearColor[4] = { 0.176f, 0.196f, 0.667f, 0.0f };
    ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView();
    pd3dDevice->ClearRenderTargetView( pRTV, ClearColor );

    // Clear the depth stencil
    ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView();
    pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 );

    // If the settings dialog is being shown, then render it instead of rendering the app's scene
    if( g_SettingsDlg.IsActive() )
    {
        g_SettingsDlg.OnRender( fElapsedTime );
        return;
    }

    //Text Render constants (set to display text in the middle of the screen
    RECT r;
r.top = 100;
r.bottom = 600;
r.left = 70;
r.right = 700;
HRESULT hr;

    if (boxTimer < 0){
           int No = boxTimer;
            std::wstringstream StrStream;
            StrStream << L"\n\n\n\n\n\nGame Over, better luck next time!!\n " << L"\nYou Collected " << boxCount << " Box(es) \n\n\n Press Return to try again or esc to quit";
            std::wstring messageString = StrStream.str();

            hr = g_pSprite10->Begin(0);
            hr = g_pFont10->DrawTextW(g_pSprite10, messageString.c_str(), -1, &r, DT_LEFT | DT_TOP, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
            //hr = sprite->Flush();
            hr = g_pSprite10->End();
            pd3dDevice->OMSetBlendState(NULL, 0, 0xffffffff);
            return;
    }

    if(startScreen){

            hr = g_pSprite10->Begin(0);
            std::wstring left = L"\nWelcome to my game \n\nJerry is just a typical flying tiger who loves smashing boxes .. \noh, and shoots mini tigers out his mouth\n\n The aim of this game is to smash as many boxes as you can within the time limit. \n Don't forget to keep an eye on the time, because the more boxes you smash, the less time\n you will get between boxes \n\n\n\n Controls:\n S = up. W = Down. Q = Left. E = Right\n A = Rotate Left. D = Rotate Right\n Space Bar = Fire. Left Shift = Fly Forward.\n\n\n\n Press Return to begin!!";
            //hr = g_pFont10->DrawTextW(g_pSprite10, left.c_str(), -1, &r, DT_LEFT | DT_TOP | DT_CALCRECT, D3DXCOLOR(0.0f, 1.0f, 4.0f, 1.0f));
            hr = g_pFont10->DrawTextW(g_pSprite10, left.c_str(), -1, &r, DT_LEFT | DT_TOP, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
            hr = g_pFont10->DrawTextW(g_pSprite10, left.c_str(), -1, &r, DT_LEFT | DT_TOP, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
            //hr = sprite->Flush();
            hr = g_pSprite10->End();
            pd3dDevice->OMSetBlendState(NULL, 0, 0xffffffff);
            return;
    }

    //**********************************************************************//
    // Get the projection & view matrix, which are now hidden in the the    //
    // camera class.                                                        //
    //**********************************************************************//

    matProjection = *g_Camera.GetProjMatrix();
    matView       = *g_Camera.GetViewMatrix();
    //matProjection = g_cam.getProjectionMatrix();
    //matView       = g_cam.getViewMatrix();

    //**********************************************************************//
    // Pass the light direction and colour to the shader.  It seems silly   //
    // to do this every frame, but I suppose the light might have moved..   //
    //**********************************************************************//

    g_p_Effect->pLightDirectionInShader->SetFloatVector(       (float *) &g_p_Effect->lightDirection);
    g_p_Effect->pLightDiffuseColourInShader->SetFloatVector(   (float *) &g_p_Effect->lightDiffuseColour);

    //**********************************************************************//
    //  Perform Game Logic                                                  //
    //**********************************************************************//
    if (boxCount >= 0) difficulty = 16;
    if (boxCount >= 5) difficulty = 11;
    if (boxCount >= 10) difficulty = 6;

    if ((!character->intersectsWith(box)) && (!shoot->intersectsWith(box))) {

    box->matView       = matView;
    box->matProjection = matProjection;

    box->render();

    } else {
        //Call axploding box.

        //increment count and display it
            box->moveTo(randomm(1, 30), randomm(1, 30), randomm(1, 30));

        // reset box in another place and reset timer.
            boxTimer = difficulty;
            boxCount++;
    }

    //**********************************************************************//
    // Render the thing3D.                                                  //
    // Note, the Thing3D creates its own world matrix.  But it needs to know//
    // the other matrices to pass to its own shader.                        //
    //**********************************************************************//

        if(fire){
            if(frameCount < 50){
        shoot->Shoot(character->returnWorldMatrix(), matView, matProjection);

        frameCount++;
            } else {
                fire = false; frameCount = 0;
            }
        }

    gameFloor->matView       = matView;
    gameFloor->matProjection = matProjection;
    gameFloor->render();
    character->matView       = matView;
    character->matProjection = matProjection;
    leftWing->matView       = matView;
    leftWing->matProjection = matProjection;
    rightWing->matView       = matView;
    rightWing->matProjection = matProjection;

    //**********************************************************************//
    // Render the thing if the camera isn't on it, otherwise get a tiger's  //
    // eye view of the world.                                               //
    //**********************************************************************//

    //flap wings

    if (!g_b_CameraOnThing) {
        all->render();
        //setStaticCameraPosition();

        D3DXVECTOR3 viewerPos;

        viewerPos.x = character->x;   viewerPos.y = character->y;
        viewerPos.z = character->z;

        D3DXVECTOR3 newDir, newDirNorm, lookAtPoint( 0.0f, 1.0f, 5.0f  );
        D3DXVec3TransformCoord(&newDir, &lookAtPoint,
                &character->matWorld);

        D3DXVec3Normalize(&newDirNorm, &newDir);

        D3DXVECTOR3             vecEye = newDir;
        D3DXVECTOR3             vecAt = viewerPos;

        g_Camera.SetViewParams ( &vecEye, &vecAt);
        // Set the Camera parameters
        g_Camera.SetProjParams ( D3DX_PI/4, 5.5, 30.0f, 30.0f);
        g_Camera.SetResetCursorAfterMove ( true);
        g_Camera.FrameMove(fElapsedTime);

    }
    else
    {
        all->render();
        //setDynamicCameraPosition();
        g_Camera.FrameMove(fElapsedTime);
    }

    boxTimer -= fElapsedTime;

    //****************************************************************************//
    // Box timer - This calculates and displays a count down from 10              //
    //****************************************************************************//

   int No = boxTimer;  // Or you can use float No = 10.5f
   std::wstringstream StrStream;
    hr = g_pSprite10->Begin(0);

   StrStream << L"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nTime Remaining - " << No << L"\n\nBoxes Collected - " << boxCount;
   std::wstring messageString = StrStream.str();

        //hr = g_pFont10->DrawTextW(g_pSprite10, left.c_str(), -1, &r, DT_LEFT | DT_TOP | DT_CALCRECT, D3DXCOLOR(0.0f, 1.0f, 4.0f, 1.0f));
        hr = g_pFont10->DrawTextW(g_pSprite10, messageString.c_str(), -1, &r, DT_LEFT | DT_TOP, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f));
        //hr = sprite->Flush();
        hr = g_pSprite10->End();
        pd3dDevice->OMSetBlendState(NULL, 0, 0xffffffff);

    //****************************************************************************//
    // And finally, render the DXUT buttons and the thing which grandly calls     //
    // itself a HUD (Head Up Display).                                            //
    //****************************************************************************//

    DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
    RenderText();
    g_HUD.OnRender( fElapsedTime );
    g_SampleUI.OnRender( fElapsedTime );
    DXUT_EndPerfEvent();

    }

//--------------------------------------------------------------------------------------
// Release D3D10 resources created in OnD3D10ResizedSwapChain
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext )
{
    g_DialogResourceManager.OnD3D10ReleasingSwapChain();
}

//--------------------------------------------------------------------------------------
// Release D3D10 resources created in OnD3D10CreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D10DestroyDevice( void* pUserContext )
{
    g_DialogResourceManager.OnD3D10DestroyDevice();
    g_SettingsDlg.OnD3D10DestroyDevice();
    SAFE_RELEASE( g_pFont10 );
    SAFE_RELEASE( g_pEffect10 );
    SAFE_RELEASE( g_pVERTEXLayout );
    SAFE_RELEASE( g_pSprite10 );
    SAFE_DELETE( g_pTxtHelper );
    SAFE_DELETE( g_pTxtHelper );

    SAFE_DELETE( g_pmWorldViewProj );
    SAFE_DELETE( g_pmWorld );
    SAFE_DELETE( g_pfTime );
    SAFE_RELEASE( m_font );

}

//--------------------------------------------------------------------------------------
// Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
    if( pDeviceSettings->ver == DXUT_D3D9_DEVICE )
    {
        IDirect3D9* pD3D = DXUTGetD3D9Object();
        D3DCAPS9 Caps;
        pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, &Caps );

        // If device doesn't support HW T&L or doesn't support 1.1 VERTEX shaders in HW
        // then switch to SWVP.
        if( ( Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) == 0 ||
            Caps.VertexShaderVersion < D3DVS_VERSION( 1, 1 ) )
        {
            pDeviceSettings->d3d9.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
        }

        // Debugging VERTEX shaders requires either REF or software VERTEX processing
        // and debugging pixel shaders requires REF.
#ifdef DEBUG_VS
        if( pDeviceSettings->d3d9.DeviceType != D3DDEVTYPE_REF )
        {
            pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
            pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE;
            pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
        }
#endif
#ifdef DEBUG_PS
        pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF;
#endif
    }

    // For the first device created if its a REF device, optionally display a warning dialog box
    static bool s_bFirstTime = true;
    if( s_bFirstTime )
    {
        s_bFirstTime = false;
        if( ( DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) ||
            ( DXUT_D3D10_DEVICE == pDeviceSettings->ver &&
              pDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_REFERENCE ) )
            DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver );
    }

    return true;
}

```

# Answer
You got this code in main function:

```
//Delete things

delete g_p_Effect;
delete box;
delete gameFloor;
delete character;
delete leftWing;
delete rightWing;
delete all;
delete m_hWnd;
//delete g_pTxtHelper;

//delete g_pFont9;
//delete g_pSprite9;
//delete g_pFont10;
//delete g_pSprite10;

delete shoot;

```

some of them should be in `DXUTSetCallbackD3D9DeviceDestroyed()` or `DXUTSetCallbackD3D9DeviceLost()` or `DXUTSetCallbackD3D10SwapChainReleasing()` or `DXUTSetCallbackD3D10DeviceDestroyed()`, because you are allocating memory in Create/Reset functions and these functions are called many times.

Anyway, instead of `SAFE_DELETE( g_pfTime );` it should by `SAFE_RELEASE( g_pfTime );`, I think, there is a lot of similar errors.
> 2 votes

---
Tags: c++, directx10
---


# Question
Title: Problem with SDL_Mixer/MikMod playing XM files properly
Some of the music I've made for my game have note bends in them (1xx Portamento up)...The problem is that when they play in my game, the note bends and then goes right back to original note instead of staying at the new tone it bends into.

I believe this to be an issue with SDL\_Mixer and not with the XM file itself since it plays just fine in any tracker program I load it into. Is there anything in the SDL\_Mixer loading/playing functions that I could do to fix this?

# Answer
> 1 votes
Unfortunately, the module formats (family which XM format is part of) are not perfectly specified, and various replay routines play them slightly differently.

There's really nothing you can do, apart from "fixing" the replay routine (to which you probably have no source) or modifying the XM itself (so it plays "wrong" in the XM editor, but "right" with your replay routine of choise).

# Answer
> 1 votes
MikMod is, for lack of better words, often horrible. It is likely the root cause for your misrendering. The mixing in SDL\_mixer doesn't know anything about notes or effects, it just mixes together one or more streams of audio.

I asked some friends of mine with extensive experience in module quirks and they recommend using a more sane module rendering library, like DUMB (no affiliation), which I've used in the past in my software.

---
Tags: sdl, music
---


# Question
Title: How should I handle collectable/droppable/stackable items in an inventory?
I am working on a game with an inventory system, but am trying to figure out the best way of doing it. I have read the post about adding WorldItems or InventoryItems to a list, which is fair enough and I figured that out myself anyway.

However, perhaps I add two SwordItems to this list (for example). I want the game to show that I have quantity 2 of these, not two individual items. What is the best way to achieve this with a List based inventory structure. I think I saw a GroupBy method, where I could GroupBy item type Sword. Is this a good way to achieve this? Or can you suggest a better alternative?

# Answer
Build your inventory as a list of item *stacks*, and not items. Individual items (or items that cannot be stacked) are simply a stack of one. For example:

```
class ItemStack {
  Item item;
  int count;

  // ...public methods here...
}

```

This allows you to treat your inventory as a simple homogeneous `List<ItemStack>` or similar, and also allows you the flexibility to support multiple stacks of a particular item -- for example, you can support splitting a stack of items in this system, whereas in one where you tried to `GroupBy()` might get pretty cumbersome.

It will require a little more work on your part to deal with consumption of items or their removal from the stack, but it's not that big of a deal.
> 6 votes

# Answer
The method you are suggesting isn't optimal, but it will work. However, every access to the inventory, it will try to tally up the counts. If you store your counts directly, no extra counting has to be done. Use something like a `System.Collections.Specialized.OrderedDictionary` where the keys are your item IDs (for example, all identical items of a specific type would have the same item ID) and the values are the counts.
> 3 votes

# Answer
Ok after digging around with various ways to do this, I think I have another solution.

Using an arraylist to hold all the items, you can add any item type. To get the count of a certain type of item (class) you can use generics.

For example:

```
private ArrayList inventory = new ArrayList();

public int getInventoryQuantity<T>()
{ return inventory.OfType<T>().Count<T>(); }

```

There you can just pass in the type of object you want to get the count of and it will return the in value.

Of course you can add other methods to return say all of the required items as a collectable if you wanted too, without having to nest lists etc.
> 1 votes

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


# Question
Title: Is the series of books "GPU Gems" still good for a modern OpenGL 3.0+ approach?
I noticed that this series of free books from Nvidia is really popular and well know in the devs world, the problem is that is simply old; you would recommend to read those 3 books to a developer that wants to improve his skills with a programmable pipeline and is starting to do so in the 2012 ?

# Answer
> 6 votes
The articles in the GPU Gems are more about techniques and not really about the technical abilities of the GPU offered through a revision of one graphics library or another. Some of those gems are really gems: explaining a concept that is still of interest, both in the means of approaching the problem and in implementation details. Before this gems series, I think there was another one focused on assembly language shader code. Much of those techniques were converted to a more readable higher shader language form and are still popular if not central today.

Technically, the GPU gems offer ideas for developers using HLSL up to 3.0 (DirectX 9.c) (the code is actually in Cg, a good dialect of HLSL). Equivalently, in OpenGL 3+, most core techniques are programmed the same way, using the same ideas and concepts. So, if you're not into getting the latest techie implementations running and want to get a good solid knowledge base, they're still a nice reference.

*UPDATE*

If not restricted to OpenGL, a newer series is the follow-up of ShaderX: the **GPU Pro** series (if you tolerate the DirectX approach and can translate the techniques to OpenGL).

---
Tags: shaders, books, gpu, nvidia
---


title: a 96kb 3d first person shooter

text:
# Question
Title: a 96kb 3d first person shooter
There was a game that look like Quake-3 graphics but is only 96kb. What was its name?

In the game, there were spider-like creatures and i was shooting at them. I forgot the name.

When the executable file was run, it loaded for 5-minutes before started working.

I didnt have internet connection when i ran the executable. How come it is only 96kb but worked like a hundred-megabyte?

Thanks.

# Answer
> 5 votes
That's probably .kkrieger by .theprodukkt.

And yes, the answer to how is: extremely-efficient procedural generation. Wikipedia has some more details for you.

---
Tags: first-person-shooter
---


title: Can I dynamicaly modify 3D objects?

text:
# Question
Title: Can I dynamicaly modify 3D objects?
I am new to OpenGL, I am able to render a model object (a human model) that is using .obj and .mtl file in iOS.

Now I want to make a modification to the loaded model. For example, I want to change the height, or change the shoulder width, stomach size, et cetera.

Is this possible ? If so, how do I go about it?

# Answer
> 1 votes
> Now I want to make a modification to the loaded model. For example, I want to change the height, or change the shoulder width, stomach size, et cetera.
>
> Is this possible ? If so, how do I go about it?

Yes, it is possible.

The "How" depends a lot on what exactly you're after. Altering height can be done simply by applying a scaling transform matrix before rendering. The other things you mentioned require more work, and there are several ways to go about it.

One way would be to make several versions of the mesh and interpolate between the desired features (like stomach size). Interpolating between two meshes is straightforward, but if you have several features you want to alter (like stomach size and hip width), it gets a bit more complicated. One way to solve this is to somehow "paint" weights to the vertices (through, for example, vertex colors in modelling programs) and use those when interpolating, in order to avoid the change of one thing affecting some other thing.

Or maybe you just want to apply some kind of "space modifier" to the mesh, where you just specify that "within this area, scale things outwards" or some such.

It all.. depends. =)

# Answer
> 0 votes
If it is a model you make yourself you could add bones to it and adjust their transform (probably the scale in your case) in the gamelogic. I think this would be best if done using Jari's method assigning weights through vertex colors.

---
Tags: opengl-es, ios
---


title: Is learning OpenGL2.1 today a bad idea?

text:
# Question
Title: Is learning OpenGL2.1 today a bad idea?
> **Possible Duplicate:**
> Is learning OpenGL 2.1 useless today?

This question was asked around 2 years ago and i have well read the answers to it, but that was 2 years ago, i would like to know if it's a bad idea for me to learn OpenGL2.1 today.

I bought the OpenGL superbible (4th edition) and not the 5th because some user in the ratings said that it was much better and i believed him. But now i'm affraid that was a long time ago.

Thanks for all your feedback!

# Answer
> 1 votes
The short answer:

No. Learning OpenGL 2.1 is a good idea, even today, as long as you learn the "good parts".

The Long answer:

OpenGL can essentially be divided in two parts: "The good parts" and "Legacy functions".

Honestly, I don't see much benefit in learning legacy functions (the "fixed function"). However, a substantial portion of OpenGL 2.1 (the good parts) are still available today with relatively minor changes.

As such, learning some parts of OpenGL 2.1 can be beneficial. In particular, OpenGL ES 2 is very popular these days, and ES 2 is *mostly* (but not exactly) a subset of OpenGL 2.1. For 3D programming in smartphones, OpenGL ES 2 is a must.

So what's "good"? Essentially anything that is in OpenGL 3.1 "core profile" (as opposed to "compatibility profile") and/or in OpenGL ES 2.

* Vertex and fragment Shaders: Learn them
* Textures: Still good.
* Matrixes: Knowing how they work is beneficial, but `glLoadIdentity` and that sort of functions are outdated and should be avoided
* Light: Knowing how light can be simulated in computer graphics is useful, but `glLightfv` and other fixed function light functions should be avoided.
* Array buffers: Good
* `glBegin`, `glVertex`, `glColor`, `glEnd`: Avoid them. Might be good for quick experimentation, but there are other better ways to do the same.
* Display lists: Avoid

# Answer
> 0 votes
I don't believe it is a bad idea. A lot of GL concepts span across all versions of OpenGL and will still ultimately help you. I have a number of OpenGL books from 10 years ago that still help today. I would say that if you are new to OpenGL and there are some better books that are older, you will learn plenty and the code should still work. Most of OpenGL is backward compatible (I believe).

# Answer
> 0 votes
In my opinion, I think it would be a good idea to go through the book. Until OpenGL 3.1, OpenGL was upgraded by **adding new features only**, whereas from OpenGL 3.1 onwards the Khronos group (which manages OpenGL) decided to deprecate some features. This is why a majority(like 95%) of OpenGL will be the same. Therefore, I would suggest you read the book, then read about those features of OpenGL 2.1 that were removed/replaced in OpenGL 3.1

---
Tags: opengl
---


# Question
Title: Should I use XNA or Unity to build a video game?
My friend and I are planning to make a video game (like Slender) where the character is stuck in a building, when lightning strikes, and the lights go out and your objective is to find the back-up generators and turn the lights back on. The game will be pretty small.
We are now wondering whether we should use Unity or XNA to build it. I have no experience in either, and I will mostly be writing in C# (which both have that capability). My friend will be drawing the images, and we want to import the images into the game. Which software should we use? What are the pros and cons of each? Thanks in advance.

# Answer
If that is your first project, use Unity. It is easy to learn and will get your project done much faster.

Compared to Unity, XNA is little more than a managed wrapper for DirectX. With XNA you have to do everything yourself, what Unity already implements seamlessly, there are of course libraries for almost everything specifically targeting XNA, but integrating that together is not always easy.

For a complete list see the Unity webpage, but some things you would have to implement from scratch or find libraries for:

* Rendering, especially animations and lightning
* Physics
* Editor
* Scripting
* Serialization
* Camera system
* Path finding

Unity also has a big and organized asset store with many free plugins available, that cover a lot of frequent requirements like AI or procedural content generation.
> 8 votes

---
Tags: xna, c#, 3d, unity, gui
---


title: jQuery game - collisions

text:
# Question
Title: jQuery game - collisions
Please take a look at the picture below:

It is and attempt in creating a "game" only with the DOM and jQuery.

The blue boxes are "obstacles" and the user can move his pointer (not drawn in screen in the picture", which is a single point, by clicking where he wants it to go.

The problem I am facing now, it to create a collision detection in the DOM itself with jQuery only. I am not using a pathfinding: that means that if a user wants to go across an obstacle, he has to click all the way around it. Now, how do I check if there will be a collision BEFORE the pointer actually collides? Another problem that might arise from this is if a user clicks on the opposite side of the obstacle, the collision would be checked and just walk past by.

Any ideas?

Thanks in advance.

# Answer
> 1 votes
I think the fact that you're using jQuery and DOM aren't really relevant. It all depends on how you store your data. For example you could store all rectangles (as objects with `width`, `height` and `x`, `y`) in an array and just use jQuery and DOM to render the objects to screen.

Nothing stops you from implementing a path-finding algorithm such as A\* in JavaScript, but you'll need a graph of nodes you can apply the A\* search to. To create such a graph you could use a flood-fill algorithm that creates nodes in fixed intervals (eg. every 20 pixels).

If your world looks similar to the image you posted, you could probably skip path-finding entirely and just use steering-behaviors. A combination of obstacle avoidance and arrival should work well (C++ sources of these steering behaviors can be found via opensteer.sourceforge.net).

# Answer
> 0 votes
Project the course of the player before enacting it by n step increments and do your boundary checks within this 'test move' function.

---
Tags: collision-detection, path-finding
---


# Question
Title: XNA Content Loading works on my machine but not others
I'm using `XNAWinForm` series 2 from App Hub for some task that needs 3d rendering. It works fine on my PC, but I have problems in running this code on other machines.

I installed XNA framework redistributable on that machine, I tried 32 and 64bit computers and still its not working. Even the code on app hub is not working on other machines.

What should I do?

# Answer
You need to have the **full XNA game studio** installed on every machine that will use your tool. From the WinForms2 sample page you linked to:

> Note also that the XNA Framework redistributable installer doesn't include the Content Pipeline. This sample will run only on computers that have the XNA Game Studio installed.

You also aren't allowed to distribute the full XNA studio installer in your install package, so if you are creating a tool to be distributed with your game the content pipeline isn't a great fit. It's likely not reasonable to expect end-users to install a developer tool to be able to use your custom tool.
> 5 votes

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


title: outline object effect

text:
# Question
Title: outline object effect
How can I achieve an outline effect similar to the ones found in League of Legends or Diablo III?

Is it done using a shader? How?
I would prefer answers that are not tied up to any particular engine but one that I can adapt to whatever engine I'm working on.

# Answer
> 19 votes
**You *will* have to render the object twice at some point.** You can get away with rendering just the faces facing the camera once and the faces facing *away* from the camera once, but it has its trade-offs.

The most simplest common solution is done by rendering the object twice in the same pass:

* You use a vertex shader to invert the normals of the object and "blow it up" by the size of the outline and a fragment shader to render it in the outline colour
* Over that outline render, you render the object normally. The z-order is usually automatically right, more or less, since the outline is made by the faces which are in the "back" of the object while the figure itself is made up of faces facing the camera.

This is simple enough to build and implement and avoids any render-to-texture tricks, but has a few noticeable drawbacks:

* The outline size, if you don't scale it by the distance from the camera, will vary. Objects further away will have a smaller outline than those nearby. Of course, this might be what you actually *want*.
* The "blow up" vertex shader doesn't work very well for complex objects like the skeleton in you example, easily introducing z-fighting artefacts to the render. Fixing it requires you to render the object in two passes, but saves you from reversing the normals.
* The outline and the object might not work very well when other objects are occupying the same space and are in general a pain to get right when combined with reflection and refraction shaders.

The basic idea for such a shader looks like this (Cg, for Unity - the code is a slightly modified toon shader I found somewhere and didn't note the source, so it's more badly-written proof-of-concept than a ready-to-use shader):

```
Shader "Basic Outline" {
    Properties {
        _Color ("Main Color", Color) = (.5,.5,.5,1)
        _OutlineColor ("Outline Color", Color) = (1,0.5,0,1)
        _Outline ("Outline width", Range (0.0, 0.1)) = .05
        _MainTex ("Base (RGB)", 2D) = "white" { }
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        Pass {
            Name "OUTLINE"
            Tags { "LightMode" = "Always" }
CGPROGRAM
#pragma exclude_renderers gles
#pragma exclude_renderers xbox360
#pragma vertex vert

struct appdata {
    float4 vertex;
    float3 normal;
};

struct v2f
{
    float4 pos : POSITION;
    float4 color : COLOR;
    float fog : FOGC;
};
float _Outline;
float4 _OutlineColor;
v2f vert(appdata v)
{
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    float3 norm = mul ((float3x3)UNITY_MATRIX_MV, v.normal);
    norm.x *= UNITY_MATRIX_P[0][0];
    norm.y *= UNITY_MATRIX_P[1][1];
    o.pos.xy += norm.xy * _Outline;
    o.fog = o.pos.z;
    o.color = _OutlineColor;
    return o;
}
ENDCG
            Cull Front
            ZWrite On
            ColorMask RGB
            Blend SrcAlpha OneMinusSrcAlpha
            SetTexture [_MainTex] { combine primary }
        }
        Pass {
        Name "BASE"
        Tags {"LightMode" = "Always"}
CGPROGRAM
#pragma fragment frag
#pragma vertex vert
#pragma fragmentoption ARB_fog_exp2
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"

struct v2f {
    float4 pos : SV_POSITION;
    float2    uv            : TEXCOORD0;
    float3    viewDir        : TEXCOORD1;
    float3    normal        : TEXCOORD2;
};

v2f vert (appdata_base v)
{
    v2f o;
    o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
    o.normal = v.normal;
    o.uv = TRANSFORM_UV(0);
    o.viewDir = ObjSpaceViewDir( v.vertex );
    return o;
}

uniform float4 _Color;

uniform sampler2D _MainTex;
float4 frag (v2f i)  : COLOR
{
    half4 texcol = tex2D( _MainTex, i.uv );

    half3 ambient = texcol.rgb * (UNITY_LIGHTMODEL_AMBIENT.rgb);
    return float4( ambient, texcol.a * _Color.a );
}
ENDCG
    }
    }
    FallBack "Diffuse"
}

```

The other common method renders the object twice as well, but avoids the vertex shader fully. On the other hand, it can't be easily done in a single pass, and needs render-to-texture: Render the object once with a "flat" outline-coloured fragment shader and use a (weighted) blur on this render in *screen space*, then render the object as usual on top of it.

There's also a third and possibly easiest to implement method, though it taxes the GPU a bit more and will make your artists want to murder you in your sleep unless you make it easy for them to generate: Have the objects have the outline as a separate mesh all the time, just fully transparent or moved somewhere where it's not seen (like deep underground) until you need it

# Answer
> 4 votes
In addition to Martin Sojkas answer, for static objects (or sprites) you can get away with something simpler.

You can save the same sprite but with the outline into your texture atlas or another texture entirely, which makes switching easy. This will also allow you to do custom outlines that are more visually appealing or just look different.

The other method is to save the sprite as a one color shape that is slightly larger and render that just before the sprite itself is rendered. This will give you the ability to easily change the color of the selection, and you might not need as much different color shapes as you would need outline sprites with method #1.

Both will increase your memory footprint though.

# Answer
> 4 votes
As pointed out in the comments to Martin Sojka's answer, a similar effect can also be achieved by utilizing the stencil or depth buffer, as detailed by Max McGuire on FlipCode:

http://www.flipcode.com/archives/Object\_Outlining.shtml

It's basically drawing a wireframe version of the model you want outlined with increased line width (or in case this is not possible, as in D3D for instance, using camera facing quads for lines) while setting the stencil buffer to a constant value.

This aproach might be a little dated using today's OpenGL and in order to have the object outline applear blurred, rendering to texture will still be necessary.

---
Tags: shaders, rendering, effects
---


# Question
Title: Why do my pyramids fade black and then back to colour again
I have the following vertecies and norms

```
GLfloat verts[36] = {

-0.5, 0, 0.5,
 0, 0, -0.5,
0.5, 0, 0.5,

0, 0, -0.5,
0.5, 0, 0.5,
0, 1, 0,

-0.5, 0, 0.5,
0, 0, -0.5,
0, 1, 0,

0.5, 0, 0.5,
-0.5, 0, 0.5,
0, 1, 0

};

GLfloat norms[36] = {

0, -1, 0,
0, -1, 0,
0, -1, 0,

-1, 0.25, 0.5,
-1, 0.25, 0.5,
-1, 0.25, 0.5,

1, 0.25, -0.5,
1, 0.25, -0.5,
1, 0.25, -0.5,

0, -0.5, -1,
0, -0.5, -1,
0, -0.5, -1
};

```

I am writing my fists Open GL game, But I need to know for sure if my Normals are correct as the colours aren't rendering correctly. my Pyramids are coloured then fade to black every half rotation then back again.

---

My app so far is based on the boiler plate code provided by apple. heres my modified setUp Method

```
 [EAGLContext setCurrentContext:self.context];

[self loadShaders];

self.effect = [[GLKBaseEffect alloc] init];
self.effect.light0.enabled = GL_TRUE;
self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f);

glEnable(GL_DEPTH_TEST);

glGenVertexArraysOES(1, &_vertexArray); //create vertex array
glBindVertexArrayOES(_vertexArray);

glGenBuffers(1, &_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts) + sizeof(norms), NULL, GL_STATIC_DRAW); //create vertex buffer big enough for both verts and norms and pass NULL as data..
uint8_t *ptr = (uint8_t *)glMapBufferOES(GL_ARRAY_BUFFER, GL_WRITE_ONLY_OES); //map buffer to pass data to it
memcpy(ptr, verts, sizeof(verts)); //copy verts
memcpy(ptr+sizeof(verts), norms, sizeof(norms)); //copy norms to position after verts
glUnmapBufferOES(GL_ARRAY_BUFFER);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); //tell GL where verts are in buffer
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(verts))); //tell GL where norms are in buffer
glBindVertexArrayOES(0);

```

And the update method.

```
- (void)update
{

float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);

self.effect.transform.projectionMatrix = projectionMatrix;

GLKMatrix4 baseModelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f);
baseModelViewMatrix = GLKMatrix4Rotate(baseModelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f);

// Compute the model view matrix for the object rendered with GLKit
GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.5f);
modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f);
modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix);

self.effect.transform.modelviewMatrix = modelViewMatrix;

// Compute the model view matrix for the object rendered with ES2
modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 1.5f);
modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f);
modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix);

_normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL);

_modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);

_rotation += self.timeSinceLastUpdate * 0.5f;
}

```

But providing I understand this correct one pyramid is using the GLKit base effect shaders and the other the shaders which are included in the project. So for both of them to have the same error, I thought it would be the Norms?

# Answer
> 1 votes
Found the answer: it was the Normals:

GLfloat norms\[36\] = {

```
0, -1, 0,
0, -1, 0,
0, -1, 0,

1, 0.25, -0.5,
1, 0.25, -0.5,
1, 0.25, -0.5,

-1, 0.25, -0.5,
-1, 0.25, -0.5,
-1, 0.25, -0.5,

0, 0.5, 1,
0, 0.5, 1,
0, 0.5, 1
};

```

These are the correct ones. For some reason the maths I used produced some numbers that were negative when they shouldn't have been. thanks for all the help! GC

---
Tags: 3d, opengl-es, ios, xcode
---


title: android game-logic for shooter

text:
# Question
Title: android game-logic for shooter
Im creating a 2d game for android.

I'll just get right to it. I have a sprite controlled by a joystick that needs to shoot, sofar Ive managed to get direction and movement on my bullet, but then I get stuck.

First of I need a delay for my bullet, cus right now its shooting like 10 bullets/sec, and you prolly know how that looks, like a beam of bullets.

Second there is a problem with the way I update the location for my bullet, my bullet position gets updated every time my sprite-position gets updated. This means that every time I move my character the previous bullets I've fired stop moving, so to be clear, the direction and speed of my bullet is fine, but the way it spawns and updates the old bullets when I move my sprite ( dragging gets set to true ) is really buggy. Maybe every element in my arraylist need a boolean for when its created?

Ill post some relevant code here:

Code for sprite/bullet positon, direction and speed:

```
    if (dragging) {

        // get the pos
        touchingPoint.x = (int) event.getX();
        touchingPoint.y = (int) event.getY();

        angle = Math.atan2(touchingPoint.y - inity,
                touchingPoint.x - initx) / (Math.PI / 180);
        spriteAngle = Math.atan2(touchingPoint.y - inity,
                touchingPoint.x - initx) / (Math.PI / 2) + 2;

        pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                * (touchingPoint.y / 90);
        pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (touchingPoint.y / 90);
        bulletPos.y = pointerPosition.y; //this is what messes up my bullet-position, if I move sprite, the existing bullets stop, so I cant move and shoot
        bulletPos.x = pointerPosition.x;

    if (event.getAction() == MotionEvent.ACTION_DOWN && (int) event.getX() > 650 && (int) event.getX() < 750
            && (int) event.getY() > 300 && (int) event.getY() < 400 ){
        shooting = true;

    }

    if(shooting){
        bulletPos.y += Math.sin(angle * (Math.PI / 180)) //!!!What I removed: * 5;
        bulletPos.x += Math.cos(angle * (Math.PI / 180)) //!!! here to: * 5;
    }

```

Code for drawing my bullet:

```
    private void shootingControl(Canvas canvas){ //is called in drawing-method
    if(controls.getShooting() == true){
         bullets.add(new Bullets(bullet, controls.bulletPos.x, controls.bulletPos.y));
         }

    for(int i = 0; i < bullets.size(); i++){
     bullets.get(i).update(); //!!!!added this
        bullets.get(i).draw(canvas);
    }

}

```

Code for bullet-class:

```
    public Bullets(Bitmap bitmap, int x, int y) {
    this.bitmap=bitmap;
    this.X=x;
    this.Y=y;
}

    //!!!What I tried adding!!!
    public void update(){
    X *=5;
    Y *=5;

public void draw(Canvas canvas){
    canvas.drawBitmap(bitmap, X, Y, null);
}

```

I've gotten some help from here alrdy regarding some of this, and I kinda feel bad for asking again, but I cant find anything anywhere and I cant figure it out on my own, really tired of being stuck here.

Ive seen some people using gametime in their bullet-positions and alot of people use vectors. Or if you can redirect me to a good tutorial. I just want to get past this stage of my game!

Thank you!

# Answer
> 2 votes
Your game should have a global delta time. If not you can create it yourself by checking the time between the last frame and current frame. Your shooting method should look like:

```
if(shooting)
{
   delayAcc += delta;
   if(delayAcc > shootDelay){
        delayAcc = 0;
        //Do shooting here.
   }

}
else{
    delayAcc = shootDelay+1; // Makes sure player shoots when button is pressed.
}

```

I wonder why you aren't just moving the velocity of the bullet to its own class? You could simply create a base object that has the position and velocity. And an update function that adds the velocity to the position. This update method is then called in an update loop ( obviously with an array of bullets) Use an object pool to reuse these objects when you "destroy" them. The update method could probably come from an interface to allow polymorphism.

I have the feeling your velocity is lost once it goes out of scope or is overridden. And therefor your old bullets don't budge because they were depending on it.

Try having a central point, like a factory, that creates objects for you. Don't let the player create objects directly. Instead it should call a different object that returns an object for the player, or directly passes it onto your managers (and by managers I mean the objects that handle things such as your bullets ).

You can do everything with the x and y variables as you could with a vector. The only difference is probably that the Vector class has many functions already implemented. But for a simple movement, adding the velocity to the positions x and y would be sufficient.

Your class name Bullets should be Bullet btw. Bullets implies something else than a single bullet =).

---
Tags: 2d, android, physics, vector
---


# Question
Title: Composition heavy OOP vs pure entity component systems?
I admit, I have made the sin of overusing, and even abusing inheritance. The first (text) game project that I made when I was taking my OOP course went as far as "Locked door" and "unlocked door" from "Door" and "Room with one door", "Room with two doors", and so on from "Room".

With the (graphical) game I worked on recently, I thought I had learned my lesson and put a limit on using inheritance. However I noticed the problems soon beginning to appear. My root class was beginning to bloat more and more, and my leaf classes were full of duplicate codes.

I thought I was still doing things wrong, and after looking it up online I discovered that I wasn't the only one with this problem. It's how I ended up discovering Entity systems after some thorough research (read: googlefu)

When I began reading on it, I was able to see how clearly it was able to solve the problems I was having with the traditional OOP hierarchy with components. These were in the first readings however. When I stumbled upon more… “radical” ES approaches, such as the one at T-machine.

I began disagreeing with the methods they were using. A pure component system seemed either overkill, or rather, unintuitive, which is probably the strength of OOP. The author goes so far as to say that ES system is the opposite of OOP, and while it may be usable along OOP, it really shouldn’t. I'm not saying it's wrong, but I just didn't feel like a solution I would like to implement.

So to me, and to solve the problems I was having at the beginning of the post, without going against my intuitions, is to still use a hierarchy, however it won’t be a monolithic hierarchy like the ones I used before, but rather a polylithic one (I couldn’t find a word opposite to monolithic), which consists of several, smaller trees.

The following example shows what I mean (this is inspired by an example I found in Game Engine Architecture, Chapter 14).

I would have a small tree for vehicles. The root vehicle class would have a rendering component, a collision component, position component etc..

Then a tank, a subclass of vehicle would inherit those components from it, and be given it's own "cannon" component.

The same goes for the Characters. A character would have it's own components, then the Player Class would inherit it, and be given an Input controller, while other enemy classes would inherit from the Character class and be given an AI controller.

I don't really see any problems with this design. Despite not using a pure Entity Controller System, the problem with the bubbling up effect, and the large root class is solved by using a multi-tree hierarchy, and the problem of the heavy, code duplicating leafs is gone since the leafs don't have any code to begin with, just components. If a change needs to be done to the leaf level, then it's as simple as changing a single component, instead of copy pasting the code everywhere.

Of course, being as inexperienced as I am, I did not see any problems when I first started using the single hierarchy, inheritance heavy model, so if there are problems with the model that I'm currently thinking of implementing, I wouldn't be able to see it.

Your opinions?

P.S: I am using Java, so using multiple inheritance to implement this instead of using normal components is not possible.

P.P.S: Intercomponent communications will be done by linking dependent components to each other. This will lead to coupling, but I think it's an ok trade off.

# Answer
> 8 votes
Consider this example:

You're making an RTS. In a fit of complete logic, you decide to make a base class `GameObject`, and then two subclasses, `Building` and `Unit`. This works just fine, of course, and you end up with something that looks like this:

* `GameObject`
    + `ModelComponent`
    + `CollisionComponent`
    +
* `Building`
    + `ProductionComponent`
    +
* `Unit`
    + `AimingAIComponent`
    + `WeaponComponent`
    + `ParticleEmitterComponent`
    + `AnimationComponent`
    +

Now every subclass of `Unit` you make already has all the components you need. And as a bonus, you have a single place to put all that tedious setup code that `new`s up a `WeaponComponent`, connects it to an `AimingAIComponent` and a `ParticleEmitterComponent`—wonderful!

And of course, because it still factors logic out into components, when you eventually decide that you want to add a `Tower` class that's a building but has a weapon, you can manage it. You can add an `AimingAIComponent`, a `WeaponComponent`, and a `ParticleEmitterComponent` to your subclass of `Building`. Of course, then you have to go through and dig out the initialization code from the `Unit` class and put it somewhere else, but that's no big loss.

And now, depending on how much foresight you had, you may or may not end up with subtle bugs. Turns out there might've been some code elsewhere in the game that looked like this:

```
if (myGameObject instanceof Unit)
    doSomething(((Unit)myGameObject).getWeaponComponent());

```

That silently doesn't work for your `Tower` building, even though you really wanted it to work for anything with a weapon. Now it has to look something like this:

```
WeaponComponent weapon = myGameObject.getComponent(WeaponComponent.class);
if (weapon)
    doSomething(weapon);

```

Much better! It occurs to you after changing this that *any* of the accessor methods you've written could end up in this situation. So the safest thing to do is strip them all out, and access *every* component via this one `getComponent` method, which can work with any subclass. (Alternately, you can add every single kind of `get*Component()` to the superclass `GameObject` and override them in subclasses to return the component. I'll assume the first one, though.)

Now your `Building` and `Unit` classes are pretty much just bags of components, without even accessors on them. And no fancy initialization either, because most of that needed to be dragged out to avoid code duplication with your one special-case other object somewhere.

If you follow this to the extreme, you *always* end up making your subclasses completely inert bags of components, at which point there isn't even any point having the subclasses around. You can gain almost all the benefit of having a class hierarchy with a *method* hierarchy that creates the proper components. Instead of having a `Unit` class, you have a `addUnitComponents` method which makes an `AnimationComponent` and also calls `addWeaponComponents`, which makes an `AimingAIComponent`, a `WeaponComponent`, and a `ParticleEmitterComponent`. The result is that you have all the benefits of an entity system, all the code reuse of a hierarchy, and none of the temptation to check `instanceof` or cast to your class type.

# Answer
> 2 votes
Composition over Inheritance is the OOP terminology (at least the way I learned/was taught it). To chose between composition and inheritance you say out loud "Car is a type of wheel" (inheritance) and "Car has wheels" (composition). One should sound more correct than the other (composition in this case), and if you can't decide, default to composition until you decide otherwise.

# Answer
> 1 votes
When it comes to integrating components based systems to existing games based on game objects there is an article at cowboy programming http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ which might give you some pointers on the way the transition can be made.

As to issues, your model will still need to handle the player differently from another enemy. You won't be able to switch status (ie player becoming AI controlled) when a player disconnects or in special cases without handling him differently from the other characters.

Apart from the heavy reuse of components across diferent entities, the idea of component based games is the uniformity of the entire system. Each entity has components that can be attached and detached at will. All the components of the same kind are handled exactly the same way with a set of calls established by the interface (base component) of each kind (position, rendered, script...)

Mixing game objects inheritance with a component based approach brings you some advantages of the component based approach with drawbacks from both approaches.

It can work for you. But I woudn't mix both outside of a transition period from one architecture to the other.

P.S. written on a phone so I have a hard time linking to external resources.

---
Tags: java, component-based, entity-system, oop
---


title: Collision rectangle response

text:
# Question
Title: Collision rectangle response
I'm having difficulties getting a moveable rectangle to collide with more than one rectangle.

I'm using SFML and it has a handy function called `intersects` which takes 2 rectangles and returns the intersections. I have a vector full of rectangles which I want my moveable rectangle to collide with. I'm looping through this using the following code (p is the moveble rectangle).

`IsCollidingWith` returns a bool but also uses SFML's `intersects` to work out the intersections.

```
while(unsigned i = 0; i!= testRects.size(); i++){
   if(p.IsCollidingWith(testRects[i]){
        p.Collide(testRects[i]);
   }
}

```

and the actual `Collide()` code:

```
void gameObj::collide( gameObj collidingObject ){

 printf("%f %f\n", this->colliderResult.width, this->colliderResult.height);

if (this->colliderResult.width < this->colliderResult.height) {
    // collided on X
    if (this->getCollider().left < collidingObject.getCollider().left ) {
        this->move( -this->colliderResult.width , 0);
    }else {
        this->move( this->colliderResult.width, 0 );
    }

}

if(this->colliderResult.width > this->colliderResult.height){
    if (this->getCollider().top < collidingObject.getCollider().top ) {
        this->move( 0, -this->colliderResult.height);
    }else {
        this->move( 0, this->colliderResult.height );
    }

}

```

and the `IsCollidingWith()` code is:

```
bool gameObj::isCollidingWith( gameObj testObject ){
if (this->getCollider().intersects( testObject.getCollider(), this->colliderResult )) {
    return true;
}else {
    return false;
}

```

This works fine when there's only 1 `Rect` in the scene. However, when there's more than one `Rect` it causes an issue when working out 2 collisions at once.

Any idea how to deal with this correctly? I have uploaded a video to youtube to show my problem. The console on the far-right shows the width and height of the intersections. You can see on the console that it's trying to calculate 2 collisions at once, I think this is where the problem is being caused.

Finally, the image below seems to illustrate my problem nicely:

# Answer
Your image illustrates one of the many problems with trying to use convex shapes - particularly rectangles - to simulate a flat surface like a floor. The algorithm leads to characters getting stuck on inner edges of the shapes making up the floor.

A simple fix for that is to check for vertical collision only, correct that, then check again for horizontal collision. Unless you're falling and trying to slide down a wall, in which case you want to check for horizontal collisions first. How do you know when to check which first? You could do it based on which component of your velocity is larger (if horizontal movement is greater, check vertical collisions first, otherwise check horizontal collisions).

What can be even simpler - and more performant - is to instead generate a list of edges for your world. That is, for your boxes making up the floor, set a flag indicating that only their top edge is actually collidable, and then ignore collisions with the other edges. You will not be able to use SFML's collision routine for that, but honestly simply box collisions is possibly the easiest bit of code you'll ever write in a game. This technique works particularly well if your world is aligned to a grid. I would check out the excellent Metanet tutorials (http://www.metanetsoftware.com/technique.html/) for that technique.

You're going to run into many others problems trying to build a simple 2D platformer game like you are. By far, the best resource I've seen latel for that is the following one, which you should read, and then read again:

http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/
> 3 votes

# Answer
Maybe a simple solution would be to check for collisions with every rectangle and move back, in the opposite direction of movement, until no collisions are detected. If that solves the problem, the implementation should be quite simple too.
> 1 votes

# Answer
I don't think having 2 collisions calculated is a problem, only a performance issue. In order for the collision to be handled correctly it may have to be tested twice. Using your diagram think if A is tested against B first, then it will need to be tested against the other boxes as well, and may well collide with another.

Hope that is helpful?
> 0 votes

# Answer
This isn’t really an optimal method, you should be trying to determine there earliest time *when* or the first point along the moving objects path *where* collisions occur and move the objects to that position (or the position at the calculated time), attempting to correct based on the penetrating positions after movement is very problematic, but you can use your current process with a small change. Just keep checking for collisions until there are none.

```
bool collided = true;
while(collided) {
   collided = false
   while(unsigned i = 0; i!= testRects.size(); i++){
      if(p.IsCollidingWith(testRects[i]){
         collided = true
         p.Collide(testRects[i]);
      }
   }
}

```

Note that there are situations where this will lead to an **Infinite Loop** (think of a situation where moving the box out of a collision results in another collection, and moving the box out of that collision moves it back into the same colliding position as before)
> 0 votes

---
Tags: c++, collision-detection, collision-resolution, sfml
---


# Question
Title: Calculating angle between two vectors to steer towards a target
I have been trying to implement a path following steering behaviour for AI in a 2D racing game.

I have two vectors: `futurePosition` represents the predicted future position given the car's current heading. `futurePathPosition` represents the nearest point on the path to the predicted future position.

By working out the relative orientation of these two vectors, I should be able to determine whether the car needs to turn left or right in order to head towards the centre of the path.

I've tried different calculations, but I just can't get it to follow the path consistently. Occasionally the car will turn the wrong way and get "stuck".

I am currently determining the angle using the cross product, as suggested here.

```
var a = Vector2D.normalize(this.futurePathPosition);
var b = Vector2D.normalize(this.futurePosition);
var d = Vector2D.cross(a, b);

if(this.futureDistanceFromPath > this.trackRadius) {
  if(d > 0)
    this.steerLeft();
  else if(d < 0)
    this.steerRight();
  else if(d == 0)
    this.steerAngle = 0;
}
else
  this.steerAngle = 0;

```

Any tips on what might be causing this bug would be appreciated.

Also, I wondered if axis orientation affects how calculations are performed on vectors? In canvas the y axis faces "south", but in the vector tutorials I have read I haven't seen axis orientation mentioned.

# Answer
Shouldn't you be performing the vector crossing on the heading vectors, rather than on the positions? Positions could be any set of values.

I think the two vectors should be

```
// direction from current to intended
a = Vector2D.Normalize(this.futurePathPosition - this.position);
// direction from current to next point along heading
b = Vector2D.Normalize(this.futurePosition - this.position);

```

My signs might be off. Switch left/right as required.
> 5 votes

# Answer
Cross products don't make much sense 2d. Or at least, they don't produce useful results (2d vectors are always on the xy plane, right, so if you cross any two, the result always contains only a z component).

To determine the angle between two unit vectors, you can take the arc-cosine of the dot-product of them. The dot-product gives you a scalar which is the cosine of the angle * the product of their magnitude.

To work out whether to steer left or right, you can use a dot-product between the desired azimuth, and a vector pointing "right" from your vehicle. If the result is \>0, then you need to steer right, otherwise left.

The "right" vector can be obtained by trivially rotating the "forward" vector by 90 degrees (multiply it by a matrix of (0,1),(-1,0) )
> 0 votes

---
Tags: mathematics, physics, javascript, vector, html-canvas
---


# Question
Title: Can't get simple OpenGL texture working using SDL2 and FreeImage3
I created a simple OpenGL program that display a quad with texture, but it doesn't seem to be working as it only displays a white quad. What could possibly be wrong? I checked everything I could think of that could cause the issue. The bitmap is also 256x256. Any clues?

Here's the source code: http://pastebin.com/5nVbMPVp

I'm also on Linux if that helps. Thanks!

# Answer
Let's debug it one step at a time.

**Set the parameters for the texture object**

Right now you're not setting these and it may be why you're not getting anything on the screen. Try this:

```
GLuint texId;
glGenTextures( 1, &texId );
glBindTexture( GL_TEXTURE_2D, texId );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, imageWidth,
    imageHeight, 0, GL_RGB,
    GL_UNSIGNED_BYTE, imageBits );

```

**Can you fill the texture with red?**

Let's try to fill the texture with red instead of loading it from a file:

```
imageWidth = 128;
imageHeight = 128;

GLuint texId;
glGenTextures( 1, &texId );
glBindTexture( GL_TEXTURE_2D, texId );

GLubyte* image_data_temp = new GLubyte[imageWidth * imageHeight * 3];
GLubyte* dst_image = image_data_temp;
for (unsigned int i = 0; i < imageWidth * imageHeight; i++)
{
    // this will fill the texture with red (0xFF0000)
    // ... unless I've flipped the byte order, in which case it will be blue
    dst_image[0] = 0xFF;
    dst_image[1] = 0x00;
    dst_image[2] = 0x00;
    dst_image += 3;
}
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, imageWidth,
            imageHeight, 0, GL_RGB,
            GL_UNSIGNED_BYTE, image_data_temp );

// if you have a "new", you must have a "delete" too!
delete [] image_data_temp;

```

Is the screen red now? Then you know it has to do with your image not loading right.

If the screen is black then let's continue to the next thing to try:

**Can you render anything at all?**

Instead of rendering a textured quad, try rendering a line instead:

```
glBindTexture( GL_TEXTURE_2D, 0 ); // unbind the texture
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glColor3f(1.f, 0.f, 0.f);
glBegin( GL_LINES );
    // top-left to bottom-right
    glVertex2f( 0.0f, 0.0f ); glVertex2f( imageWidth, imageHeight );
    // top-right to bottom-left
    glVertex2f( imageWidth, 0.0f ); glVertex2f( 0.0f, imageHeight );
glEnd();

```

Do you see a red x? If so, then you know your matrices are correct. If not...

**Try manipulating the modelview with the keyboard**

I'm just gonna hardcode everything here.

```
float camera_rotation[3] = { 0.f, 0.f, 0.f };
float camera_position[3] = { 0.f, 0.f, 0.f };

while ( SDL_PollEvent(&event) )
{
    switch ( event.type )
    {
        case SDL_KEYDOWN:
        {
            switch ( event.key.keysym.sym )
            {
                // move left and right
                case 'A':
                    camera_position[0] -= 3.f;
                    break;
                case 'D':
                    camera_position[0] += 3.f;
                    break;
                // move forwards and backwards
                case 'W':
                    camera_position[2] += 3.f;
                    break;
                case 'S':
                    camera_position[2] -= 3.f;
                    break;
                // move up and down
                case 'Q':
                    camera_position[1] -= 3.f;
                    break;
                case 'E':
                    camera_position[1] += 3.f;
                    break;

                // look left and right
                case SDLK_LEFT:
                    camera_rotation[0] -= 3.f;
                    break;
                case SDLK_RIGHT:
                    camera_rotation[0] += 3.f;
                    break;
                // look up and down
                case SDLK_UP:
                    camera_rotation[2] += 3.f;
                    break;
                case SDLK_DOWN:
                    camera_rotation[2] -= 3.f;
                    break;

            }

            break;
        }
        case SDL_QUIT:
        {
            running = false;
            break;
        }
    }

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotate3f(camera_rotation[0], camera_rotation[1], camera_rotation[2]);
    glTranslate3f(camera_position[0], camera_position[1], camera_position[2]);

    // render stuff here
}

```

**That didn't work either**

Well then I'm stumped too.
> 6 votes

# Answer
A few things you could try to help you (and us) find the problem:

* glGetError
* attach the actual image you are trying to load
* attach the program output - what does `fprintf( stdout, "%u %u %p\n", imageWidth, imageHeight, imageBits )` print out?
> 1 votes

---
Tags: opengl, textures, sdl
---


# Question
Title: Multiple images written and read from one meta-file?
Short version:

I need a way to store multiple image files in one bigger file, to be used using C#, preferably easily compatible with XNA. The files will be read, written to, but also adaitional files will be added during run-time.Is there an easy way to do that?

Long version:

I'm currently working on a small student project. It's a top down RPG-strategy and we decided to make the map dynamic, meaning that portions of it will be loaded/unloaded in the background while the player character moves around.

I reckon the best way to do this is to load/generate chunks as the player comes close to them and unload them when the player goes farther. I reckon the best way to do this is to save chunk as raster graphics and then use the colour information (RGBA) to store information.

The problem is that I want certain chunks to be saved once generated so I need a way to save images, in the same way I read them, but preferably all in a single file, so as not to have the folder bloat in size with a lot of files.

# Answer
> 2 votes
You can use a container instead of a directory, storing multiple files inside it. System.IO.Packaging.ZipPackage provides one such container, starting from .NET Framework 3.0, which means you'll have to search for other implementations if you want to use such with XNA on the XBox (which only supports .NET 2.0). DotNetZip or SharpZipLib might work, but I didn't try out either yet.

The other solution would be to use an image format which supports multiple images by default, like TIFF. There is a LibTiff.Net available, which works for .NET 2.0 as well.

---
Tags: xna, c#, 2d, image
---


title: Including sprite file  for mobile games

text:
# Question
Title: Including sprite file  for mobile games
I'm making a simple online RPG for Android & IOS using HTML5 & Phonegap and was wondering: should I include sprite file with the game for downloads (because of bandwidth)? What should I do when I modify the sprite file in the future? (i.e. forced update).

# Answer
> 1 votes
Short Answer: Of course; just include all your assets. Make sure you use proper texture compression and a good file format for your needs and file sizes shouldn't be a problem for a low scale RPG.

Long Answer:

Distribute your app as just a wrapper around your HTML5 game and make life a bit easier that way. You can have your HTTP server and the browser handle the sprite caching, the browser will download new assets for you as required. If there's a major update, you can always order a cache purge to have all users up to date. This way, the updates will be near instant and you won't have to worry about shipping out huge updates.

On startup, it may be a good idea to preload content and tell the user roughly how much data is needed. This prevents confusion and angry players - it has the added bonus of a smoother game experience when completed, too.

# Answer
> 1 votes
The user will have to download the sprite at some point in order to see it on their device. Whether it's at the initial download or later is a design consideration.

I recommend you use a combination of both. Package the sprite with your game and also have the game check your server to see if there is a newer version of the sprite. Only download from your server if there is a newer version.

---
Tags: graphics, javascript, sprites, html5
---