# Question
Title: How can I handle versioning changes when saving assets?
I've been working on an RPG now for a while and I use two of different serialization techniques.

* Enemies, Weapons, items are as saved as XML.
* Maps and events are saved as "controlled binary" (every class get a save/load method and they decide what they want to save/load).

But I have started to question my choice for maps and events. My concerns:

* I have created a map editor but I still miss being able to change small things by just opening the file.
* Changes mess so much up. Say that I want to add a variable to a class, if I don't load/save every map again it break later.

The first concern is hard to get around without changing my technique. I thought about changing to JSON, but it's a lot of work. I also think it look pretty ugly with \[DataContract\] and \[DataMember\] attributes everywhere.

That leave me with my second concern and I wonder how I can deal with it? Do you create a small program that loop through all maps and re-save them with the new variable? Because I start to get a couple of maps now and I still do it manually. It make me think twice everytime I want to do some changes as it create a lot of extra work.

# Answer
> 5 votes
There are lots of ways to handle the versioning problem; you can do it by having one load function per version, you can try to automate process by describing (via attributes usually) the transformation of the asset structure over time, you can do version-specific checks inside the load/save functions, et cetera.

I like the "describe the changes" approach but find that trying to do it via attributes gets awkward *fast*. I'd use functions instead; implement a function that transforms data in version `N` to data in version `N + 1` for all your appropriate version. On load, check the version against the latest and if it isn't, run the data through all the appropriate versioning functions. Always save out the latest version.

This works best if you do the transformation when the data is still in a runtime key-value form. This means you will probably want to implement a representation for your data that is a "runtime bag of properties" approach, because you can't use the underlying key-value form of JSON or XML if you've got your own binary format. If you don't do this, you *also* may need to keep old class definitions around, which gets ugly. Being able to have your assets in this property bad format is also *tremendously* useful for game editor development.

During development as you iterate on your data it will naturally bubble up to the latest version and you can eventually delete the old versioning functions. This is more or less the same high-level approach that we used to version art assets (such as the maps) in Guild Wars 2.

---

Now, all that said, I think it's useful to support both text and binary serialization for assets. During development, keep all your data in a human-readable format based on XML or JSON. This can increase your iteration ability a lot because you don't need to build such complex tools around editing the data. You can return to being able to make simple quick tweaks by hand.

Second, assuming you even still want a binary format for shipping the game (which can improve file size or file IO times, so it's a valid desire), design your serialization and deserialization APIs to handle versioning. Versioning *is* still useful in a shipping context, because as some point you may want to ship updates or bug fixes. There are some documents describing the versioning abilities of .NET serialization and Boost's serialization that you may find interesting. If you *are* going to support both text and binary formats, make sure you test them occasionally (or build automated tests to do so, even better).

# Answer
> 1 votes
Use a markup language with attribute-value pairs like XML or JSON.

The parser can just ignore any attributes it doesn't understand or use defaults for any it doesn't find, which makes backward- and forward compatibility quite easy. Also, the format is human-readable so you can easily edit it with a text editor.

When you use an established language like XML or JSON you will also notice that many scripting languages support it, so when you still need to write a script to edit a large number of files, you will find it much easier to do.

The drawback of most of these languages is that they are quite verbose. That means the resulting files are much larger than they would need to be with an optimized binary format. Nowadays, file size doesn't matter too much in most situations. But in those where it does matter, the filesize can often be significantly reduced by compressing the file with a stock algorithm like zip.

Markup languages often don't allow random access unless the whole document is read from the hard drive and parsed. But in practice this doesn't matter that much, because hard drives are fastest with sequential reads. Randomly seeking multiple times to different parts of the same file can often be much slower than just reading the file in one go, even when it means that you read more data than you need to.

# Answer
> 1 votes
you can use protobuf. https://code.google.com/p/protobuf/ It gives you the advantages of json/xml, that you can easily extend it while beeing backwards compatible, plus the advantage of being binary. The workflow is, that you create a data format description in the protobuf language and then generate source code for serialization and deserialization. Source can be generated for several languages. Also it is a big advantage that you have a clear specification of your serialized data, in contrast to json where the specification is done implicitly in reading/writing.

---
Tags: c#, rpg, serialization, binary
---


title: 3D-Physics of a Rubber Ball (Squash)

text:
# Question
Title: 3D-Physics of a Rubber Ball (Squash)
I'm trying to simulate the environment on a Squash Court on Android with my own physics and using OpenGL for visualization. Basically, its about a **rubber ball** bouncing around in 3d, not just on the floor but also on the walls.

What I'm not quite sure about is what kind of physical concepts are altering the movement of the ball or *how much* they are.

* Obviously there's **gravity**...
* Also, **air friction**, but I'm not sure how to calculate air friction of a rubber ball that is roughly 40mm in diameter. I've tried different formulae but I wasn't happy with them (eg. some were linear to speed and some were quadratic lol) and I was missing some material-dependant constants.
* Then there's the **normal force** applied from the solid shape on which the ball bounces. I don't think I need to alter any values as the normal force is "taken into account" by changing the ball's direction. I mean, if the solid shape where the ball bounces is vertical, normal force is zero but the ball still changes direction. Correct?
* Now, every collision **reduces the kinetic energy** as it emits sound and warms the ball. I assume that this reduction is greater if the ball hits the solid shape on a tighter angle. Is there a way to quantify it? So far, all I could do was use values "to make it look like it might be".
* Furthermore, I suspect that the angle at which the ball hits the shape is not equal to the **angle in which it leaves the ball**. Obviously, if the ball hits at 90° (orthogonal), then it will leave at 90°. On the other hand, if the ball hits at, say, 45°, it might leave at 30° (compared to the solid shape eg. the floor).
* There is **spin** which I have not spend much thought on but if anyone knows where I might find something about that I'd be greatful.
* Other forces/effects on the trajectory of the ball...??

Thanks in advance :)

Edit: To summarize, I am looking for (1) an applicable formula that represents air friction with possible constant values depending on the rubber-ball-scenario, for (2) a confirmation that my way of handling normal force is correct, that (3) a way of quantifying energy loss of the ball in a collision, (4) how (if) the angle after the collision is altered, with regard to the incoming angle, and lastly (5) how to handle spin.

# Answer
That this question is quite broad makes it quite difficult to answer, but the basic physics that would go in to it could be summarized as:

1. **Gravity** \- As long as the ball stays within moderate height (within the squash court), this could be treated as a constant.
2. **Air Resistance** -

> Also, air friction, but I'm not sure how to calculate air friction of a rubber ball that is roughly 40mm in diameter.

This is not an issue since smaller objects having smaller surface areas does not suffer much air resistance. But this does have an effect in the long run. Below is an example of a bullet (much higher velocity than a squash ball). While bouncing on the ground, air resistance will reduce the horizontal range of the ball (its parabolic trajectory) and will effect the game!
The equation connecting velocity of motion to the force (linear) is as follows:
rho is the density of the medium, Cd is the drag coefficient and A is the drag area ().
3. **Collisions** \- Refer to inelastic collision in 2D and extend it to 3D. You'll simply need to calculate energy loss from this collision. Sound, and heat effects are a bit of an overkill. Sound is pre-set in the game anyways, and heat is visible in the expansion of the material, and for a 40 mm ball that is next to nothing.
4. **Spin** \- believe it or not, spin could be one of the most toughest things to calculate compared to other parameters above. We know angular momentum isn't conserved when there is a torque. Thus, inorder to calculate the rate of change of ang.momentum (ang. acceleration), we'd need to calculate moment of inertia and thereby the torque, or forget Newton's method and set up the whole thing with Lagrange's equations instead(Makes it a lot easier). But, if you could build a system of spin for the ball itself, then it would be quite easier to keep track of it while it touches a surface (at any angle) and calculate the torque right away.
Note: There is something called a Magnus effect that you might want to look in to (overkill).
5. **Rolling** \- Similar to spinning, but a much simpler equation depending on the rolling-friction and moment of inertia of the ball. (I can't give a link due to lack of reputation)
> 4 votes

---
Tags: 3d, physics
---


# Question
Title: What does the hull shader attribute "patchsize" do?
What does the hull shader attribute `[patchsize(12)]` do? MSDN fails to mention it. Do I have to use it? Should I use it?

# Answer
> 4 votes
`patchsize` appears to describe the number of control points per patch, and seems to be largely ignored (as unnecessary) by the actual compiler. It's possible that at one point it was used as an optimization hint, but doesn't seem to have much practical use.

All real-world examples I can find eschew the attribute. The fact that it appears to only be referred to in the documentation here suggests that the tech writer who created that documentation was given an old bit of example code.

I'd say it's safe to ignore it.

---
Tags: hlsl, directx11
---


title: Units, Layers, and Isometric Ordering

text:
# Question
Title: Units, Layers, and Isometric Ordering
I'm currently using LibGDX and Tiled map editor to render isometric maps. I'm having a two related difficulties.

The first issue is, when do I render units that will end up changing position often and to which layer? At first I thought that I would render units with a wall layer so that walls behind of and in front of the unit are drawn correctly. However, the problem with this is that if a unit (i.e. a character) steps in front of say an object in some sort of top-level decoration layer, part of that object will be drawn on top of the unit.

The second issue is how to deal with layers that have static objects that units will often be stepping in front of or behind. Let's say you have a decoration layer where you will place trees. The problem with this layer is that depending on where some objects are placed in the layer, they will overlap inconsistently. For example, the following:

I know this is related to painter's algorithm, but I'm using LibGDX's tile map renderer so the extent to which I have control over drawing the map is rendering different layers at a time and switching out cells/tiles in a layer.

# Answer
Generally for isometric games, you have to constantly be switching the draw order of images based on their respective tile's y-position (in a game where you have objects all at the same 'z' index, ie not have characters that can jump up to higher levels and such). This means do a sort on the y-position of every tile image (consider storing all the tiles in an array), and then draw these tiles to the screen in that order (lowest y-position to highest y-position).

The only times when you can modify the amount of times you re-order the drawing of the objects, is when you have a constant (can't go below) front layer or a constant (can't go up above) back layer. For anything that can be walked behind or in front of, that object should be drawn as its own tile, and be ordered just like all the other objects.

Another optimization you could do, in cases where, say you have a set of wall tiles that are ordered the same way each render call, but a character which may have moved from behind to in front of an object, is to keep the last frame's ordering for the draw and only insert the non-static tile values into the order.

To be more specific, order the wall tiles once, and keep that array from frame to frame. Then for each frame, clone the ordered wall array, and add in a character at the correct index for its y-position. Then draw that order.
> 2 votes

---
Tags: libgdx, tiles, isometric
---


title: Is OpenGL appropriate for 2D games?

text:
# Question
Title: Is OpenGL appropriate for 2D games?
I have been teaching myself the OpenGL library for a while now, and want to start making a game. However, for an easier introduction, I want to start with something 2D, such as a top down Pokemon-style game.

Is this a good plan, or is OpenGL made specifically for 3D?

# Answer
OpenGL is quite appropriate for 2D games. Although it is generally used for 3D, the same functionality can be used for 2D games. That is to say, anything you can do with 3D OpenGL will be applicable with "2D" OpenGL.

Some further information can be found at this location.

2D OpenGL is achieved in the same manner that 3D OpenGL is. 2D OpenGL is only the application of a technique, that is, rendering the scene on a flat plane, then using and orthographic projection instead of a perspective projection, which, depending on your setup, could distort the scene.

An example:

(a) is a scene in an orthographic projection. (b) is the same scene, using a perspective projection. In a 2D game, this can cause mis-positioning of sprites if their depth is altered (which, depending on how you go about development, may be the case). Using a perspective projection also makes aligning things in screen coordinates more difficult.

In addition, OpenGL carries many, many, **many** benefits with it. Primarily, hardware acceleration is a huge plus. There's also a much finer degree of control over what the graphics card does and how it goes about it, allowing for case-specific optimizations
> 48 votes

# Answer
OpenGL as the name states is a graphics library. Although it is developed with 3d in mind, there are no hardcoded assumptions in the library that you'll be using 3d. Moreover, thanks to it's 3d capabilities, several things that would be hard to do in a strictly 2d approach are trivial. Examples:

* Z-sorting is simplified by using 3d coordinates the depth buffer (watch out for transparency though)
* sprite rotation and scaling is basically for free as you're using textured quads that are independent of the resolution
* if you're willing to restrict yourself to OpenGL 2.0 capable graphics cards you can take advantage of shaders, which will simplify writing special effects a lot (blurs, particle effects, image manipulation, color substitution) -- not to mention that it will be a lot faster than done CPU-side

This is only a few advantages that come from the top of my head, I guess there are several others.
> 23 votes

# Answer
While OpenGL is a 3D API, you can still use it to make 2D games. You can fake a 2D environment in 3D through various techniques, such as contraining data to a plane.

However, there is limited support in the actual API for doing this in an obvious fashion (there's no "turn on 2D mode" function, for example). The ways in which you'd simulate it (which you can find in many tutorials online) may be difficult to fully understand without some understanding of the 3D pipeline that is actually being used under the hood.

It sounds like you have been looking at OpenGL for a while and so probably have a decent grasp of those fundamentals. However, if you feel shaky on them you may want to start with your game by using a 2D library that is built on top of OpenGL, such as cocos2d. It will give you some experience with what 2D APIs generally should look like and still gets you the benefits of a hardware-accelerated 3D back-end, if you feel like you aren't quite ready to tackle the whole thing on your own.
> 17 votes

# Answer
Many 2d graphic libraries like SDL or SFML make use of OpenGL hardware acceleration. This gives you the performance benefit of OpenGL, but abstracts the nasty low-level details behind a much simpler API.
> 5 votes

# Answer
Unity3D uses OpenGL, and I use it for 2D and 2.5D platformers. Unity3D is essentially a 3D Gaming Engine, but is also is used for 2D and 2.5D games as well. You can have x, y, z planes and only limit the movement or rotation to 2 of those planes, creating a 2D atmosphere in essentially a 3D world.
> 0 votes

# Answer
I now have a lot of experience in OpenGl programming, and I can tell you it is a pain. In the past when I started programming I was very productive in simple environments like BlitzBasic. Then I started to go into the next step with learning C++ and OpenGl. And when you do not have a good teacher or people to ask, you will permanently run into the black screen. The biggest problem is the state hell of OpenGl. There are tons of switches that you can swap to change the state of opengl. And some switches depend on other switches. for example glGet(GL\_TEXTURE\_BINDING\_2D) depends on glGet(GL\_ACTIVE\_TEXTURE). And the documentation which state depends on which other state is not the best. Many operations like texture loading requires you to change this state which very often leads to the breakage of other code that requires the old state. And then there is this problem that OpenGl as implementation dependant behavior, so that your program runs on your machine but on the other machine all you see is black. All you can do here is guessing what is wrong in your 10000 lines of code. So if you like frustration then yes use OpenGl for 2D things. To all other people, don't do it if you don't need it. You can get productive in OpenGl, but it will cost you a lot of your time and nerves. Propably more than you want to spend.
> 0 votes

---
Tags: opengl, 2d
---


# Question
Title: Collision detection in seemingly random locations
I have a square that moves around with user input and should return to top left of screen when it collides with one of the rectangles on the screen. It works fine when the the rectangles are not moving; however, whenever the rectangles oscillate up and down, the square will randomly return to the top left of the screen as if it collided with a rectangle. What is even more strange is, it only does it on the right sides of the rectangles.

I've been trying to figure this out for forever and have finally turned here for help, please do! Its c++ and SDL.

Here is the code:

```
#include "SDL/SDL.h"
#include "SDL_image/SDL_image.h"
#include <string>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
const int FRAMES_PER_SECOND = 20;

const int SQUARE_WIDTH = 20;
const int SQUARE_HEIGHT = 20;

SDL_Surface *square = NULL;

SDL_Surface *background = NULL;
SDL_Surface * message = NULL;

SDL_Surface *screen = NULL;

SDL_Event event;
SDL_Rect wall;
SDL_Rect wall2;
int wallVel = 5;

class Square
{
    private:
        SDL_Rect box;
        int xVel, yVel;
    public:
        Square();
        void handle_input();
        void move();
        void show();
};

class Timer
{
    private:
        int startTicks;
        int pausedTicks;
        bool paused;
        bool started;
    public:
        Timer();
        void start();
        void stop();
        void pause ();
        void unpause();

        int get_ticks();
        bool is_started ();
        bool is_paused();
};

SDL_Surface * load_image (std::string filename)
{
    SDL_Surface * loadedImage = NULL;
    SDL_Surface * optimizedImage = NULL;

    loadedImage = IMG_Load (filename.c_str());
    if (loadedImage != NULL)
    {
        optimizedImage = SDL_DisplayFormat (loadedImage);
        SDL_FreeSurface (loadedImage);

        if (optimizedImage != NULL)
        {
            SDL_SetColorKey (optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB (optimizedImage -> format, 0, 0xFF, 0xFF));
        }
    }

    return optimizedImage;
}

void apply_surface (int x, int y, SDL_Surface * source, SDL_Surface * destination, SDL_Rect * clip = NULL)
{
    SDL_Rect offset;
    offset.x = x;
    offset.y = y;
    SDL_BlitSurface (source, clip, destination, &offset);
}

bool check_collision (SDL_Rect A, SDL_Rect B)
{
    int leftA, leftB;
    int rightA, rightB;
    int topA, topB;
    int bottomA, bottomB;

    leftA = A.x;
    rightA = A.x + A.w;
    topA = A.y;
    bottomA = A.y + A.h;

    leftB = B.x;
    rightB = B.x + B.y;
    topB = B.y;
    bottomB = B.y + B.h;

    if ((bottomA >= topB) && (topA <= bottomB))
    {
        if ((rightA >= leftB) && (leftA <= rightB))
        {
            return true;
        }
    }

    return false;
}

bool init()
{
    if (SDL_Init (SDL_INIT_EVERYTHING) == -1)
    {
        return false;
    }

    screen = SDL_SetVideoMode (SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);

        if (screen == NULL)
        {
            return false;
        }
    SDL_WM_SetCaption ("Move the square", NULL);

    return true;
}

bool load_files()
{
    square = load_image ("SDL Directory/square.bmp");

    if (square == NULL)
    {
        return false;
    }

    return true;
}

void clean_up ()
{
    SDL_FreeSurface (square);
    SDL_Quit ();
}

Square::Square()
{
    box.x = 0;
    box.y = 0;

    box.w = SQUARE_WIDTH;
    box.h = SQUARE_HEIGHT;

    xVel = 0;
    yVel = 0;
}

void Square::handle_input()
{
    if (event.type == SDL_KEYDOWN)
    {
        switch (event.key.keysym.sym)
        {
            case SDLK_UP: yVel -= SQUARE_HEIGHT / 2; break;
            case SDLK_DOWN: yVel += SQUARE_HEIGHT /2; break;
            case SDLK_LEFT: xVel -= SQUARE_WIDTH/2; break;
            case SDLK_RIGHT: xVel += SQUARE_WIDTH/2; break;
        }
    }
    else if (event.type == SDL_KEYUP)
    {
        switch (event.key.keysym.sym)
        {
            case SDLK_UP: yVel += SQUARE_HEIGHT / 2; break;
            case SDLK_DOWN: yVel -= SQUARE_HEIGHT /2; break;
            case SDLK_LEFT: xVel += SQUARE_WIDTH/2; break;
            case SDLK_RIGHT: xVel -= SQUARE_WIDTH/2; break;
        }
    }
}

void Square::move()
{
    box.x += xVel;

    if (box.x <0)
    {
        box.x = 0;
    }
    if (box.x+SQUARE_WIDTH > SCREEN_WIDTH)
    {
        box.x = SCREEN_WIDTH-SQUARE_WIDTH;
    }

    box.y += yVel;

    if (box.y <0)
    {
        box.y = 0;
    }
    if (box.y + SQUARE_HEIGHT > SCREEN_HEIGHT)
    {
        box.y = SCREEN_HEIGHT-SQUARE_HEIGHT;
    }
    if (check_collision (box, wall))
    {
        box.x = 0;
        box.y = 0;
    }
    if (check_collision (box, wall2))
    {
        box.x = 0;
        box.y = 0;
    }
}

void Square::show()
{
    apply_surface (box.x, box.y, square, screen);
}

void wall_move()
{
    wall2.y += wallVel;
    wall.y += wallVel;
    if (wall.y <= 0)
    {
        wallVel = 5;
    }
    if (wall.y+wall.h >= SCREEN_HEIGHT)
    {
        wallVel = -5;
    }

}

Timer::Timer ()
{
    startTicks = 0;
    pausedTicks = 0;
    paused = false;
    started = false;
}

void Timer::start()
{
    started = true;
    paused = false;
    startTicks = SDL_GetTicks();
}
void Timer::stop()
{
    started = false;
    paused = false;
}

void Timer::pause()
{
    if ((started == true) && (paused == false))
    {
        paused = true;
        pausedTicks = SDL_GetTicks() - startTicks;
    }
}

void Timer::unpause()
{
    if (paused == true)
    {
        paused = false;
        startTicks= SDL_GetTicks() - pausedTicks;
        pausedTicks = 0;
    }
}

int Timer::get_ticks()
{
    if (started == true)
    {
        if (paused == true)
        {
            return pausedTicks;
        }
        else
        {
            return SDL_GetTicks() - startTicks;
        }
    }
    return 0;
}

bool Timer::is_started ()
{
    return started;
}

bool Timer::is_paused()
{
    return paused;
}

void game_loop()
{
    bool quit = false;
    Square mySquare;
    Timer fps;
    wall.x = 300;
    wall.y = 40;
    wall.w = 40;
    wall.h = 400;
    wall2.x = 200;
    wall2.y = 40;
    wall2.w = 40;
    wall2.h = 400;

    while (quit == false)
    {
        fps.start();

        while (SDL_PollEvent (&event))
        {
            mySquare.handle_input ();

            if (event.type == SDL_QUIT)
            {
                quit = true;
            }
        }

        wall_move();
        mySquare.move();
        SDL_FillRect (screen, &screen->clip_rect, SDL_MapRGB (screen->format, 0xFF, 0xFF, 0xFF));
        SDL_FillRect (screen, &wall, SDL_MapRGB (screen->format, 0x77, 0x77, 0x77));
        SDL_FillRect (screen, &wall2, SDL_MapRGB (screen->format, 0x77, 0x77, 0x77));
        mySquare.show();

        SDL_Flip (screen);

        if (fps.get_ticks() < 1000/FRAMES_PER_SECOND)
        {
            SDL_Delay ((1000/ FRAMES_PER_SECOND) - fps.get_ticks());
        }
    }
}

int main ( int argc, char* args[])
{

    if (init () == false)
    {
        return 1;
    }

    if (load_files () == false)
    {
        return 1;
    }

    game_loop();

    clean_up();

    return 0;
}

```

If I move my square right here it will collide and return to top left no problem. !(http://imgur.com/49Ec0nw)

From here, though, when I move down only a few more pixels it will return to top left as if it collided with a rectangle. !(http://imgur.com/XiylEXJ)

# Answer
In "bool check\_collision (SDL\_Rect A, SDL\_Rect B) {}" , you have the following:

```
rightB = B.x + B.y;

```

I think you meant to put this:

```
rightB = B.x + B.w;

```

Although I'm not sure I completely understand how you're reproducing the issue, see if that helps.
> 2 votes

# Answer
Wouldn't the detection be

```
if ((bottomA <= topB) && (topA >= bottomB))
{
    if ((rightA >= leftB) && (leftA <= rightB))
    {
        return true;
    }
}

```

not

```
if ((bottomA >= topB) && (topA <= bottomB))
{
    if ((rightA >= leftB) && (leftA <= rightB))
    {
        return true;
    }
}

```

(Inverted \>= and \<= in first if statement)
> 0 votes

---
Tags: c++, collision-detection, sdl
---


# Question
Title: How to architect collision detection in SFML
I have a pretty simple game engine that I'm making for a 2d platformer game. I don't want it to be super advanced, but it does have some basic properties. Most important to this question is a class called Entity. Entities are basically just objects in the game that are drawn to the screen and move around. They all have a square bounding box aroud them. Each different entity inherits from the class Entity (ex. Player and Ground inherit from Entity).

I want a nice, object oriented way to handle collisions between different entities. I'd like to be able to write rules of what happens when two things collide in such a way that I don't have to do a ton of casts or rewrite a lot of code. I was thinking of doing something like

```
class Entity {
    public:
        void collide(Entity* ent);
}

```

But I'm not sure how I would go about getting the type of the argument. Any suggestions on what to do?

# Answer
It sounds to me like you could make use of a 2D jump table. The idea is to store the identity of each entity as an integer, and use this ID to index into a virtual table of function calls.

```
class Entity
{
  enum Type
  {
    eAABB,
    eCircle,
    ePolygon
  };

  Type type;
};

bool AABBtoAABB( Entity *a, Entity *b )
{
  AABB *A = (AABB *)a;
  AABB *B = (AABB *)b;

  // ...
}

bool AABBtoCircle( Entity *a, Entity *b );
bool AABBtoPolygon( Entity *a, Entity *b );
bool CircletoCircle( Entity *a, Entity *b );
bool CircletoAABB( Entity *a, Entity *b );
bool CircletoPolygon( Entity *a, Entity *b );
// ...

CollideArray[][] = {
  AABBtoAABB, AABBtoCircle, AABBtoPolygon,
  CircletoCircle, CircletoAABB, CircletoPolygon,
  // ...
};

bool Collide( Entity *a, Entity *b )
{
  return CollideArray[a->type][b->type]( a, b );
}

```

This style makes you code an N^2 number of functions, where N is the number of different entity types that participate. However some of the entries are just duplicates where the two types are swapped.

This is pretty implementation dynamic dispatch for multiple types, as opposed to how standard C++ often is implemented with a single dimensional jump table for the `virtual` keyword.
> 1 votes

---
Tags: c++, collision-detection, architecture
---


# Question
Title: How can I check the multisample quality level count?
I can check it with `ID3D11Device::CheckMultisampleQualityLevels()`. So to use it I need to create the device: `D3D11CreateDeviceAndSwapChain()`. To call it I need to fill the `DXGI_SWAP_CHAIN_DESC` which, among others, specifies... the multisample quality level. Vicious circle.

Do I have to split `D3D11CreateDeviceAndSwapChain()` into creating the device and the swap chain separately? Or what?

# Answer
If you aren't going to request a multisampling quality value that is guaranteed (certain feature levels require certain levels of multisample quality support), then you need to create the device without the swap chain, check the quality support level, and then create your swap chain.

You should do this anyway, since the "guess and check" method is error prone: you usually don't get enough information about invalid parameters without the debug layer (which you cannot enable in shipping code) to know if it's the MSAA level or feature level that causes a failure when creating the device and swap chain at the same time.
> 3 votes

---
Tags: directx11, multisampling
---


# Question
Title: How do I change rasterizer state properly?
To set the rasterizer state I have to `ID3D11Device::CreateRasterizerState()` and then `ID3D11DeviceContext::RSSetState`. And then I should `ID3D11RasterizerState::Release()` it, right?

* How about when I want to change the state? Do I follow the above 3 steps again?
* When I want to change just 1 setting (i.e. only `CullMode`) do I still have to fill and set whole structure?
* Also, do I have to create and release the state object each time (assuming I don't want to set the exact same state again in the future)?
* How about performance? If I set the exact same state again does it do anything? Is there a difference between changing only 1 setting or most/all of them?

# Answer
> 2 votes
You have to set entire state blocks at a time, even if you want to change only a single value.

You should create all the state blocks you need and hold on to them as long as you may need them. *Don't* create-set-release. That introduces unnecessary resource churn. The API will share redundant state block data under the hood so you shouldn't need to worry about that.

The underlying API will handle state changes for an entire state block efficiently. The debug layer will notify you of entirely redundant state block sets, however.

To improve performance, aim for minimal state change anywhere in a graphics API. That usually means batching operations on geometry that shares needed state. However, don't be afraid to change state when you *need* to.

---
Tags: directx11, state
---


# Question
Title: How to outline a 3D object with a cartoon style stroke?
How could I draw (stroke) the outline of a 3D object in a cartoon style with GLKit?

I'm referring to something like this:

However we can start with a simple line around the object and then try to improve the stroke with a shader.

I'm drawing the object with this code:

```
glBindVertexArrayOES(_vertexArray);
glDrawElements(GL_TRIANGLES, sizeof(Indices)/sizeof(Indices[0]), GL_UNSIGNED_BYTE, 0)

```

As I'm not very familial with GLKit: all the solutions I've found make use of OpenGL APIs not supported by OpenGL ES.

# Answer
I'm not too familiar with what features aren't supported by OpenGL ES but the way I see it you have a couple options.

A quick and easy way to get a black outline effect around an object is to scale the object up slightly and render it completely black. You can then render the regular version of the model again.

Another way would be to use an edge detection post processing effect.

Also you could use N dot V to determine how much of the surface is visible. The below link has an example on that.

http://http.developer.nvidia.com/CgTutorial/cg\_tutorial\_chapter09.html

**EDIT BY DAN:**

This is a solution developed thanks to the answer and comments below. As suggested I've slightly scaled the object up, rendered it completely black (only back faces) and finally rendered the regular version of the model again.

Here's the result:

This is the drawing method:

```
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClear(GL_COLOR_BUFFER_BIT);

    // Set matrices
    [self setupMatrices];

    // Positions
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, cubePositions);

    // Texels
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, cubeTexels);

    // Normals
    glEnableVertexAttribArray(GLKVertexAttribNormal);
    glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0, cubeNormals);

    // Save the current modelview matrix in a temporary variable
    GLKMatrix4 mat = self.effect.transform.modelviewMatrix;
    self.effect.transform.modelviewMatrix = GLKMatrix4Scale(self.effect.transform.modelviewMatrix, 1.02, 1.02, 1.02);

    glDisable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    // Set the material to black
    self.effect.material.ambientColor = GLKVector4Make(0.0, 0.0, 0.0, 1.0);
    self.effect.material.diffuseColor = GLKVector4Make(0.0, 0.0, 0.0, 1.0);

    // Prepare effect
    [self.effect prepareToDraw];

    // Draw the outline
    glDrawArrays(GL_TRIANGLES, 0, cubeVertices);

    // Restore the correct material color
    self.effect.material.ambientColor = GLKVector4Make(251.0/255.0, 95.0/255.0, 95.0/255.0, 1.0);
    self.effect.material.diffuseColor = GLKVector4Make(251.0/255.0, 95.0/255.0, 95.0/255.0, 1.0);

    // Prepare effect
    [self.effect prepareToDraw];
    glEnable(GL_CULL_FACE);

    // Restore the modeview matrix
    self.effect.transform.modelviewMatrix = mat;

    // Prepare effect
    [self.effect prepareToDraw];

    // Draw the object
    glDrawArrays(GL_TRIANGLES, 0, cubeVertices);

}

```

Before scaling the object I save the modelview matrix in a temp variable, which I restore to draw the object in the last step. Any hint to improve the code is really appreciated!

Thanks a lot guys for your help.

Cheers, DAN
> 6 votes

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


title: HTML5 game fps render lag

text:
# Question
Title: HTML5 game fps render lag
I am currently creating a flappyBird-like HTML5 game using Proccessing.js

You can see current work here: http://files.tips4design.com/flappySlothRelease/

The problem is that even though the FPS is 60+ (or constant) there is an obvious shuttering in rendering.

I have read a lot of game-loop articles to solve this issue, but neither with Processing.js draw loop, browser's requestAnimFrame nor constant delta-time the problem was solved.

Now I use the variable deltaTime approach and Processing.js default `draw()` loop.

```
delta = now - lastTime;
...
position = position + velocity * delta

```

I have been stuck for two days with this problem, and ca not really figure out how to fix the shuttering.

Any help would be greatly appreciated!

Thank you!

# Answer
> 4 votes
`requestAnimationFrame` implementation depends on browser solely. Browser will try to reduce framing if it *"believes"* that it will be better for user, and usually does it *"smoothly"* from 60 to 30. But that shift is obviously easy to see. As well once it is some time in 30fps state, it then usually shifts back to 60. The problem here is that this shifting is very bad for player experience, and it is recommended to use persistent FPS rather than shifting.

I personally did benchmarks with canvas, and use `setInterval` solely, as found no actual performance advantage using `requestAnimationFrame` in real game examples.

This will stabilize you frame rate, but you need to handle delta time which is:
`var dt = (now - last) / (1000 / 60);`
Assuming your target FPS is 60. That will give you number around `1.0`, more - is more laggy, and less is over-performing target fps. You will have to multiply your most time based operations by this value.

# Answer
> 0 votes
make sure you are not creating objects in your render-loop this can cause memory leaks as well as stuttering and slow-downs.

I checked your source for data/main.js and it looks like your not doing anything improper besides maybe `var auxDate = new Date();` you could put `auxDate` outside the render loop because each iteration its being re-created and could cause some slowdowns.

---
Tags: javascript, html5, html-canvas, game-loop, frame-rate
---


# Question
Title: How did they make the screen move in Dangerous Dave?
I've made games in BASIC when I was a child, and I was curious about how the graphics were done in the 1988 version of Dangerous Dave made in C++; especially because they didn't have any worthwhile graphics packages those days. Remember how when Dave reached the edge of the screen, the entire screen graphic used to move leftward in a sweeping motion? I remember reading that Romero had used a special technique to do that. I've been wanting to create something like Dave, and was wondering

1. what graphics package/method they used for Dave?
2. and how to make the entire screen graphic move like they did?

# Answer
> 22 votes
My 1988 version of Dangerous Dave was the Apple II version. The scrolling was done by moving all the screen bytes over then drawing a new tile on the edge of the screen - repeat 20 times for a full screen shift. The Apple II version was written all in 6502 assembly language.

On the PC, the 1990 version, I wrote graphics code in 80x86 assembly language for all video modes at the time: CGA, EGA, VGA. Dangerous Dave PC is the only game I know of that has all 3 video modes in it and switchable at any time (F2), even in the middle of a jump!

To scroll the screen quickly, it was all in assembly language and I used a similar technique as I used with the Apple II version - quickly move bytes in video memory and draw a tile on the right side. In EGA it was trickier because to do anything quickly in EGA mode required the use of Latch Mode for memory moves. I remember teaching Todd Replogle how to do that so Duke Nukem 1 would be a fun game (a slow Duke Nukem would not have been cool).

The game code for Dangerous Dave PC was written in C, in the Borland C 3.0 IDE. Most debugging was done in Turbo Debugger on a 12" amber monitor plugged into a Hercules card.

# Answer
> 13 votes
Ah I remember these techniques from my DOS days. Moving the video RAM around with blitting to perform scrolling would have resulted in jerky scrolling. EGA introduced the the vertical and horizontal pixel panning registers which could be used to set the screen origin (where in video memory the video card started displaying data from). Because there is no memory copying going on this is almost instant and can be used for very smooth and fast pixel by pixel scrolling on EGA and VGA if you have direct access to the hardware registers. Most scrollers in DOS would have used this, and this part of the code would probably have been written in assembly language to directly access the hardware registers. These methods aren't really valid anymore though. To achieve a similar effect now, I think on modern graphics hardware you could probably do it fast enough just redrawing the entire screen each frame. The other method I can think of is using OpenGL or DirectX and rendering a texture to a quad twice the width of the screen and moving that. Somehow it doesn't seem as fun as manipulating hardware registers though :)

# Answer
> 4 votes
Edit: Here is a link to an article from Dr. Dobbs that discusses sideways scrolling. It may be the method used for this effect.

http://www.drdobbs.com/184408045

---

It's hard to judge exactly how this was done, but consider that this game was written for a very specific hardware specification - DOS with a EGA video card (640x480 pixels). The code probably is doing some pretty low level manipulations of video memory to make the scroll happen smoothly.

Here is a website that talks about programming DOS graphics that might give you a sense of what it would be like...

http://www.phatcode.net/res/224/files/html/index.html

# Answer
> 4 votes
**Metagun** (game developed by Markus aka Notch aka MineCraft guy) has the same scrolling feel you're looking for.

The game is Open-Source and written in Java.

Hope you'll learn from looking at the code.

# Answer
> 2 votes
I can think of two ways this has been done:

1. Brute force: just draw the scene
2. Mode-X and panning registers. Draw the bit to be scrolled into view and adjust the panning registers to scroll the scene. You would need to redraw the top display area each frame, but that is less work to do than drawing the main play area. You wouldn't need to redraw the bottom area as there was a register in the hardware that would cause the video DACs to read from address 0 at a given scan line (so the bottom area would be at address 0 in video ram and the top would start after the bottom area)<sup>*</sup>.

I'd probably go with 1) as there's not much graphically going on, there may be some self-generated code to blit and clip images at the edges. One possible technique that a collegue of mine was working on back then was self-writing sprites, that is, the sprite data wasn't data, it was code. This meant there were no transparency checks and the data read of the blit was effectively free (this was on a 386 where each instruction was read and then decoded so instead of read code-\>read data-\>write data it was just read code-\>write data). It worked amazingly well - we got lots of huge sprites on multiple parallax layers running at 25fps+.

But we are talking about Romero here and there's probably a bit of exageration going on about the techniques.

* I did actually do this in my first major DOS game, and there's a bug in some hardware whereby the address reset happened a scanline too soon so you'd have a half-height pixel between the two sections.

---
Tags: graphics
---


# Question
Title: Does Unity's "Transparent Bumped Specular" translate to "semi-shiny must be semi-transparent"?
Unity's documentation for the "Transparent Bumped Specular" shader/material-type is simply a concatenation of each of the descriptions for its Transparent and Specular Shaders (and also Bumped, but that doesn't apply to the question):

*Transparent Properties*

*This shader can make mesh geometry partially or fully transparent by reading the alpha channel of the main texture. **In the alpha, 0 (black) is completely transparent while 255 (white) is completely opaque**. If your main texture does not have an alpha channel, the object will appear completely opaque.*

(...)

*Specular Properties*

(...)

*Additionally, the alpha channel of the main texture acts as a Specular Map (sometimes called "gloss map"), defining which areas of the object are more reflective than others. **Black areas of the alpha will be zero specular reflection, while white areas will be full specular reflection.***

To me this translates to:

* I have a mesh representig a car tire
* The texture need to be very shiny on the rims parts, and almost not shiny at all for the rubber parts
* Also since the rim is really complex, (with like cut-out decoretions and such), I will not build that into the mesh, but fake it with transparency in the texture
* I can't do all this using Unity's "Transparent Bumped Specular" shader, because the "rubber" part of the texture will become semi transparent due to me painting the alpha channel dark-grey (because I want it to also be less shiny).

Is this correct? If not, how can I make this work?

# Answer
According to the way the documentation lays out the single alpha channel for both specular and transparency you are correct in your assumption.

If you want full control over the textures my solution would be to separate your tire and rim-hubcap models so you can texture each individually. This would allow you to create a Transparent Bumped Specular on the rims for the cutout and shine control but also allow you to use a Bumped Specular on the tire wheel so you can get a more rubbery look without the transparency.
> 1 votes

# Answer
Warning: Not a unity user, so I wouldn't know if unity offers these techniques. The concepts are simple and applicable regardless. (And this just got bumped)

1. Color keying: Check if the alpha or color is equal to a magic cutout value.
2. Alpha partitions: Obtain separate specular and transparency values using line equations.
> -1 votes

---
Tags: unity, shaders, transparency
---


# Question
Title: What would be the easiest way to keep objects at a constant point on a 2D map, even when off-screen?
Like in Starcraft, where your army units stay put even though your view is moving around the map.

I have a static tiled map that I made using Mappy and I can display that fine, I just want my off-screen objects to stay put while I am moving my view around. At the moment everything is drawn relative to my view instead of at a global (x, y) position and I would like to change this but I am not sure how.

Would I need another array aside from the one to create my map? That seems like a terrible idea to me.

# Answer
> 2 votes
One way to do this is to have a 2D camera.

This way your player can move the camera around in the world and everything in the world is drawn relative to the cameras transformation matrix.

Here I found a camera implemented in XNA with some comments about what has been done that seems relatively straight forward: http://www.dreamincode.net/forums/topic/237979-2d-camera-in-xna/

While the camera implementation I linked is in C#/XNA you shouldn't have any trouble adapting it to C++. When you have your camera you then need to transform an objects position (x, y) to be relative to the cameras view. When you do this you get the position in world cooridnates rather than screen coordinates.

In XNA there is a Vector2.Transform() function which makes it rather easy to use by multiplying a Vector2 with a transformation matrix, so what you'd need to do to use the above example is to implement your own Transform function (or use one if there is one in the framework you are using).

---
Tags: c++, 2d, maps
---


title: Strange collision in Breakout

text:
# Question
Title: Strange collision in Breakout
My Breakout game works fine so far, but I struggle with the collision detection... Well... just with the collision from the ball with the brick... Here's the relevant code:

```
List<Brick> removeList = new ArrayList<>();
for (Brick b : bricks) {
    if (ball.intersects(b)) {
        float x = b.getX();
        float y = b.getY();
        float width = b.getWidth();
        float height = b.getHeigth();

        Line2D.Float left = new Line2D.Float(x, y, x, y + height);
        Line2D.Float right = new Line2D.Float(x + width, y, x + width, y + height);
        Line2D.Float top = new Line2D.Float(x, y, x + width, y);
        Line2D.Float bottom = new Line2D.Float(x, y + height, x + width, y + height);
        Rectangle2D bounds = ball.getShape().getBounds2D();

        if (bounds.intersectsLine(left)) {
            ball.setVelocityX(-ball.getVelocityX());
            ball.setX(b.getX() - ball.getWidth());
        } else if (bounds.intersectsLine(right)) {
            ball.setVelocityX(-ball.getVelocityX());
            ball.setX(b.getX() + b.getWidth());
        } else if (bounds.intersectsLine(top)) {
            ball.setVelocityY(-ball.getVelocityY());
            ball.setY(b.getY() - ball.getHeigth());
        } else if (bounds.intersectsLine(bottom)) {
            ball.setVelocityY(-ball.getVelocityY());
            ball.setY(b.getY() + b.getHeigth());
        }
        removeList.add(b);
    }
}
bricks.removeAll(removeList);
objects.removeAll(removeList);

```

I thought it would work like this, but sometimes the ball does the wrong collision e.g. when the ball comes from down and it hits the brick near the edge it would collide like it hit from the left!

Is something wrong with my code? Maybe it is the wrong approach?

**EDIT**
Like you can see in the code above I'll get the borders `left`, `right`, `top` and `bottom` from the x and y coordinates.
After that I check which border was intersected by the ball and determine from which side the brick was hit.

# Answer
> 1 votes
I see your code uses `else if` for all the intersection checks. If the ball moves at a decent speed, it is very likely that it will collide with several lines (for example, left and top), but your code will only allow it to collide with one side at the time, resulting in erronous velocities from time to time.

Note that errors can still happen even if you remove the `else` before the if, if your ball moves fast enough, so that it can move "through" a brick from loop cycle to loop cycle. To fix that, you will have to "look ahead" in time to determine the time a collision would occur.

---
Tags: java, collision-detection, collision-resolution
---


# Question
Title: How can I center a circle around a point on an HTML canvas?
I've got a job to make an engine and light game for canvas in HTML5. I like the things I make to be centered on the x,y positions I give it, I don't know why, it just helps me think about them clearer. I've got it set up for rectangles, all I had to do was subtract half the hieght and half the width from the x/y supplied like this:

```
c.fillRect(x-width/2,y-height/2,width,height);

```

But I'm rather stumped when trying to do this with arcs. At first I thought it would be simple, I just did this:

```
c.beginPath();
c.arc(x-rad/2,y-rad/2,rad,0,Math.PI*2,false);
c.closePath();

```

But here's how they look when I try them out, 4 rects of increasing width/height and 4 circles of increasing radius. Does anyone know the math needed to calculate the correct offset for arcs?

# Answer
The X and Y positions given to the HTML5 canvas's `arc` method are the center of the desired arc. You don't need to offset them.
> 4 votes

# Answer
Create arc with progressively larger radius and shifting origin see this demo to get an inspiration http://www.tutorialspark.com/html5/HTML5\_Canvas\_Arcs.php
> 0 votes

---
Tags: mathematics, javascript, html5, html-canvas
---


# Question
Title: Do I need a UPC barcode to sell my game?
Is it necessary to register a Universal Product Code for a video game intended for sale offline? What about online?

# Answer
> 10 votes
UPC codes are designed for retail sale in the United States. They aren't legally enforced, but rather a private industry that's been standardized. Per the GS1 website:

> Today, barcodes that use EAN/UPC symbology (including the UPC-A, UPC-E, EAN-13 and EAN-8 barcodes) are the only barcodes allowed for products scanned at retail point of sale.

Therefore if you wanted to sell your game through practically any retailer, you would require a valid UPC for your product. Remember to follow the guidelines of registering your company with GS1 to have valid UPCs if you plan to do this.

Likewise selling a game on your own, whether online or offline, would *not* require a valid UPC. You could sell a million copies online through your own website or a million copies burned to DVDs, and it wouldn't matter.

---
Tags: publishing
---


# Question
Title: Unity UV map, tint / change color of texture
I have an array of vertices with texture coordinates for a UV map in Unity:

```
newUV.Add(new Vector2 (0, 1)); // FACE 1
newUV.Add(new Vector2 (1, 1));
newUV.Add(new Vector2 (1, 0));
newUV.Add(new Vector2 (0, 0));

newUV.Add(new Vector2 (0, 1)); // FACE 2
newUV.Add(new Vector2 (1, 1));
newUV.Add(new Vector2 (1, 0));
newUV.Add(new Vector2 (0, 0));

mesh.uv = newUV.ToArray();

```

It textures my mesh just fine.

How could I go around tinting FACE 1 to a darker color? Let's say the texture is just plain green and I wanted to texture only on FACE 1 to be a darker shade of green.

# Answer
> 1 votes
> Let's say the texture is just plain green and I wanted to texture only on FACE 1 to be a darker shade of green.

I think you have 3 possibilities:

* use a second texture lookup to drive different light intensity on different part of the mesh. Perhaps you want to look at self-illumin shaders built-in in unity. May be that's exactly what you are looking for, if you only want a different light intensity on some area.

Two other way of doing it (probably not suited for your specific case, but useful in more complex scenarios):

* split the mesh into 2 submesh and assign a different material to each submesh (same texture but different shaders of uniform values) =\> (draw back: you'll probably have an additional draw call unless the mesh can be static/dynamic batched)
* encode some additional data into some unused vertex attributes and use that data inside the shader to apply a darker shading (draw back: memory overhead per vertex: if the mesh is you will waste memory for just darkening a potentially small area)

---
Tags: unity, textures, uv-mapping
---


# Question
Title: How do I make a 2D platformer AI aware of its allies?
I'm trying to develop a 2D platformer AI that is aware of its buddies and tries to not overlap with them. However, I always end up with an "snake":

I dont want them to be so robotic, but instead influenced by player's movement.

I also tried to give all "waiting" enemies a chance of walking back, but that ended up in some strange pinball-type movement.

# Answer
> 0 votes
Your question immediately made me think of Pacman -- here you have the ghosts, each kinda doing its own thing. Words from the PacMan guy himself confirmed it:

> “I wanted each ghostly enemy to have a specific character and its own particular movements, so they weren’t all just chasing after Pac Man in single file, which would have been tiresome and flat.” \- Toru Iwatani, Pac-Man creator

Check out this great article for information on how he did it.

# Answer
> 0 votes
How about you try changing the speed of individual enemies? For example, the one closest starts running towards the player and attempting to hit him, while the 2nd enemy continues walking at the same speed it did before.

Also, you say that you don't want the enemies to overlap, but in that image above, they kind of do, have you tried giving them a little more visible distance between each other? After that you could try implementing handlers for overlapping, i.e., whenever an instance of an enemy is about to run into another instance, it should either have a small wait time before continuing moving or perform an altogether different behavior, such as walking backwards. I am not completely sure what your main goal is here, but I am trying to give you some suggestions that you could work on. Furthermore, the enemy on left is exhibiting a strange behavior, why does it stop and do nothing when the player has stopped? Shouldn't it attempt to damage the player before he continues moving forward?

---
Tags: javascript, ai, platformer, behavior
---


# Question
Title: How can I utilize external libraries within an entity system?
I'm implementing an entity system for educational purposes. I wanted to focus on the system itself and don't know much about rendering and physics, so I'm using external libraries for those tasks.

These libraries come with pre-defined classes for their objects (sprites, bodies, etc.) These do not fit into my entity system easily.

How can I utilize existing libraries and classes within an entity system?

# Answer
> 3 votes
> I wanted to focus on the system itself and don't know much about rendering and physics, so I'm using external libraries for this.

An "entity system" should not directly handle rendering and physics anyway; at best it should just have references to objects that are part of the rendering or physics systems, whether or not you wrote those systems yourself.

> These libraries come with pre-defined classes for their objects. (Sprites, Bodies etc.) These do not fit into my entity system easily.
>
> How can I utilize existing libraries and classes within an entity system?

Wrap them in structures that your system can consume.

An entity system really should not be a low-level API, so systems like physics and rendering should not *depend* or even *know about* it. Entity systems are about representing game objects and very high level behavior.

If you're building something akin to the current fad of "entity / component" systems, you'd create a visual component and a physics component that are at the abstraction level of your entity system and which respectively wrap the actual rendering or physics objects necessary. Something like:

```
struct RenderComponent {
  Render::RenderableObject m_renderable;
  Matrix m_transform;
}

struct PhysicsComponent {
  Physics::RigidBody m_body;
}

```

And so on. These act as *adapters* to the rendering and physics systems, and can be written to expose via their public interface the various details of the underlying external library objects that might be relevant to other things within the entity system.

Even if you aren't taking the "component-based" approach, you can still build adapters as above (although exactly what you call them should be informed by the structure of the rest of your API, which you have not specified).

# Answer
> 3 votes
This is one of my issues with entity systems as opposed to other component architectures. Most games do not use the components themselves as data for drawing or physics. Not every component needs all the complexity and problems of strict data-oriented design.

Sticking to the entity system approach, though, you can have these external libraries attached as data like anything else or in a separate array.

Example when treating pointers as any other data for a component:

```
class PhysicsComponent {
  LibraryBody* _body; // points into the physics library you're using
  float3 _centerOfMass;
  float _inverseMass;
};

class PhysicsSystem {
  vector<PhysicsComponent> _components;
};

```

And as separate arrays:

```
class GraphicsConfigurationComponent {
  string _nameOfSprite;
  string _nameOfShader;
};

class GraphicsSystem {
  vector<GraphicsConfigurationComponent> _configs;
  vector<LibrarySprite*> _sprites; // points into the graphics library you're using

  void RegisterConfiguration(GraphicsConfigurationComponent* config) {
    _configs.push_back(*config);
    _sprites.push_back(MakeSpriteFromConfig(config));
  }
};

```

There's not a huge advantage to either approach on their own.

# Answer
> 0 votes
OP's options:

**Using these libs directly** and using (for example) objects of the engine-specific `Sprite` class as an component and rendering it in the system which wraps the engine.

Or

**Using a generic Sprite component**, which defines dimensions/positions and map those, when changed, inside of the system, which wraps the engine, to the engine-specific `Sprite`-class.

---
Tags: entity-system
---


# Question
Title: What are the types of 3rd-person camera called?
I'm struggling with the terminology surrounding different types of 3rd person camera. What are the common 3rd-person camera types called? What are some notable examples of their use?

---

Here's what I think I've got so far:

* **3rd Person Fixed**: This type seems glued to a position behind the character. The camera and character always rotate together.

Example: *Gears of War*
* **3rd Person Free**: The camera can be rotated independently of the character, so the character can continue walking in one direction while the camera is freely rotated around them.

Example: *Assassin's Creed* series
* **3rd Person Fixed-Free**: This is a combination of the two above. The camera can rotate independently while the character is stationary. However, when the character starts moving, they will move in the camera's direction (not the character's direction) and rotate accordingly. Also, if the camera is rotated while the character is moving, the character will also rotate with it, as with the *fixed* type above.

Example: *Max Payne*

Am I right?

# Answer
There are *no standard definitions* for all the various ways in which a 3rd person camera can behave.

Your attempts at definitions are reasonable, but it would also be perfectly acceptable for a camera called a "3rd person free" camera to be entirely unconstrained to the player's location and a "3rd person fixed" camera to be one that is fixed on the player's location but can freely orbit around it.

Each game or game studio will likely use their own variation on these names.
> 4 votes

---
Tags: camera, terminology, third-person-view
---


# Question
Title: How do I pass an object location into a vertex shader?
I am using *Blender Game Engine*. I want to create a large flat plane, and deform it locally near a moving object.

So far (despite being a beginner at shaders) I've written a vertex shader for the plane which moves the vertices to their correct positions (constant positions, for now).

I cannot find a way to swap that constant location with an object's location updated every frame, while the shader is running. I am not even sure if it's possible. I only want to access a specific object's center from the shader.

# Answer
You need to create a variable in your shader that holds this object location. In GLSL, you'd create a uniform variable; this is a variable which has the same value throughout the invocation of the shader (thus, "uniform;" you may see developers more familiar with D3D refer to these kind of variable as a "shader constant" variable as well).

Every time you want to render something with this shader, you'd set the uniform variable to the value you want.

---

That said, however, it looks like you are just using this uniform to displace some object in the world. The more common approach to this is to use a world transformation matrix for the object which is applied in the shader. This is implemented (in modern OpenGL) as a matrix uniform variable, much like your simple vector uniform, but also allows for rotation and scaling and is the more common approach. It will also scale equally well to an instancing scenario where you have several objects sharing the same geometry but in different world positions (as it sounds like, from your comments, you are wanting to have eventually).
> 1 votes

---
Tags: shaders, python, vertex, blender-game-engine
---


# Question
Title: How can I stop the player from drifting due to local input prediction when they stop?
I'm working on a 2D server-client multiplayer game engine (which you can try here). It uses WebRTC `DataChannel`s. (The connections are peer-to-peer, but the host peer still acts as a server.)

The biggest problem (apart from connectivity) is the local input prediction. We do the usual: On key press, players move instantly, tell the host what keys are pressed, receive data back from the host and compare it to the historical position. The position is corrected over time if there is a difference. This works well with low packet loss or PDV, even if the ping is high.

If there is loss or PDV, the deviation can be larger. I think this is because if the first packet indicating a change of input is delayed or dropped, the host finds out later, and starts changing that player later than their local input prediciton shows.

If the player is moving, we crank up the amount of applied correction, since it's less noticable. This seems to cover up gaps when starting to move and while moving. However, any correction is more noticable if they come to an abrupt stop. Then if the PDV or loss means the host thinks they stopped later, the host overshoots, sends back data saying they're a bit further ahead, and the correction makes the player drift a little. On flaky connections, players often noticably drift after coming to a stop.

I've not noticed this in other games. How can this be mitigated?

# Answer
The network layer needs to have an agreed-upon clock. They can agree upon a clock value early in the game (and resync it periodically in case of drift) so the host knows how long any particular packet took to actually arrive and when the client did the action, and vice versa.

See this article for one possible way to synchronize clocks in games. There are others. The specific means don't matter.

The second half of the problem is that the server is applying input past the time the client stopped applying input. This requires a buffer of past movements on the server and some logic on the client to ignore movement inputs from the server past the last known movement.

First, the server buffer. The server needs to keep track of the clock stamp of the last input received from the player. It also needs all movements it applies to a player, the clock stamp of the movement. If an input is received, all recent movements applied with a clock stamp *newer* than the input packet are dropped and all movement is re-applied from the input packet. Hence if the server over-moves the player based on some input, the updated input will cancel out those moves and the player's new position will be based upon the most recent input knowledge the server has.

On the client side, the client knows when it last sent input to the server. Since each player update from the server should have been tagged with the clock of the last input the server knew about, the client can ignore server updates that have an expired input tag and just stick with the client prediction. Eventually new server updates will arrive with up-to-date input and the client can correct against those.

The server needs to validate the input clocks and make sure they're not drifing from expectations too much to prevent cheating. The input clock should not be drastically larger than the half-round-trip time you should be calculating. Clamp any that are to a reasonable range (`[Now-2*RTT,Now]` for instance).

Clients will see a lot of jitter of other players' avatars if latency is high since they'll get updates from the server based on stale input but have no way to know that it's stale and then the server could start sending fairly different locations based on the updated input it received (and its dropping of some portion of its history and replaying it with the new input). This last issue with other players seeing your avatar jitter is not really fixable. Latency sucks and gamers stuck on high-latency connections are going to see a lot of jittering of other players, even if their own player is moving smoothly. The only correction is to play on better connections or with peers/servers with less latency.
> 8 votes

# Answer
I've used reliable UDP messages to indicate button state changes and unreliable UDP messages for position correction. Basicaly, the following articles helped me very much: https://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking

It says about movement prediction by storing player states in constant time intervals according to position correction messages arrival for about 20 or 30 state saves. So it looks like your remote players will live in a not so far "past" actualy by constantly applying prediction technique :) Based on the net message latency you can get your object position approx in time when message was just sent from host.

Current "on-screen" position can be then smoothly translated into the predicted position using Lerp (linear interpolation) math. The idea is to interpolate values in the time gaps between the correction packages. So it looks like that displayed object is always moving towards some predicted position. For interpolation value i take the 1 divided by "medium message latency" divided by "medium frame rendering time" so the movement looks smooth.

In this scenario the game calculates on all of the clients and server corrects the values such as velocity and position from time to time.

The one more thing that helps a lot in this case: optimize your game logic so you can easily negate latency effects by ensuring that server and clients can emulate near similar behaviour based on player input.

I've described the whole scheme i've used in my project so i hope you'll find the answer to your question.
> 1 votes

---
Tags: networking, multiplayer, input
---


# Question
Title: Float-based screen coordinates, higher mouse precision
I wrote 2 weeks ago about problem with motion blur in my engine. When camera moves using keyboard, motion blur is smooth. But when I rotate camera using mouse motion blur is stepping (not sure if I used proper term). Now I rethink my problem and it brings me new questions.

To rotate camera I use mouse delta which is difference between last position and current position. But it is expressed in pixels. Furthermore WinAPI events doesn't have per-pixel precision.

I saw that engines uses it's own screen coordinates which is float-based (http://www.esenthel.com/wiki/index.php?title=Screen\_Coordinates). I checked that and I see that even small movement (smaller than 1 pixel) is detected. I believe that this is the solution to my motion blur problem and also with another further problems (for example different size of GUI components on different resolutions).

And here is my question. How can I get such mouse precision? I read about WM\_INPUT and dividing delta by mouse DPI, but there are two problems - we can't get mouse DPI using WinAPI and mouse event still return value in pixels.

Where can I find some informations or example of solving this problem?

# Answer
> 3 votes
Yes, you should use `WM_INPUT` for things like camera movement. Why? Because it doesn't matter what the mouse's factory DPI is. Pretty much all games give the user a "mouse sensitivity" setting, where they can tweak a custom DPI value (they don't need to know it's the DPI!) to fit their preferences.

When it comes to GUI, you should still use the `WM_MOUSEMOVE` data. This will let the user use an in-game cursor that acts in the exact same way to their cursor outside of the game.

As far as supporting multiple resolutions goes, you can just divide the cursor position by the real screen resolution (and maybe some more transformations) to get normalized coordinates that work regardless of resolution. A good, adaptive UI should already be designed using normalized coordinates so that any resolution is supported flawlessly.

---
Tags: coordinates, mouse, screen, winapi
---


# Question
Title: Weird problem with advect program in fluid simulator
I implemented 2d fluid simulator. Solver runs entirely on GPU. All works fine... on my work PC. But on home PC I have some awful glitches, and I can\`t understand how to fix them. Empirically I discovered that problem is localized somewhere in *advect* program. This is very strange cause at work I have integrated video, and at home — NVIDIA GeForce 9800 GT. Here is the GLSL source of advect program (some lines were dropped for clearness):

```
#version 130

out vec3 value;

uniform sampler2D q;
uniform sampler2D velocity;
uniform float dt;
uniform float inverseSize;

void main()
{
  vec2 p = gl_FragCoord.xy * inverseSize;

  vec2 np = p - dt * texture(velocity, p).xy;

  value = texture(q, np).xyz;
}

```

And some screenshots.

Work PC:

Home PC:

# Answer
Per the OP's response, substituting

```
vec2 np = p - dt * texture(velocity, p).xy;

```

for

```
vec2 np = p - dt * vec2(0.01);

```

solved the problem. The field and density moves *smoothly* in the `(0.01, 0.01)` direction.
> 1 votes

---
Tags: opengl, physics, glsl
---


# Question
Title: How do I implement Breakout's "multiball" powerup?
I'm just starting out and making a breakout clone as my first game. I'm implementing all kinds of powerups, but I'm stuck on *multiball*. The powerup adds additional bouncing balls to the game.

So far, I've implemented powerups by just adding them to the `Ball` class as states. This is easy for increasing speed, making the ball sticky, changing sprites and such. When the ball is in one state it behaves in only one way.

Now, how do multiple balls fit into this? I suppose having more balls is more of a function of the game itself than the `Ball`, so it seems logical to make it a game state instead of a ball state. How would I do this?

# Answer
> 4 votes
I think you are stuck on trying to implement utterly dissimilar powerups using a unified system. That seems like a mistake, and it might become obvious if you thought about the idea of multiple balls outside the context of a power-up: multiple balls are simply more instances of a `Ball` object.

Handling multiple balls in code would not require a "gamestate", and it would not conflict with or complicate your existing "ballstate" logic. There are just more objects in play.

The only difficulty in this method is that you might need to change your update and draw logic slightly. If you have built your code around a single, global `Ball` instance, a good first step would be refactoring to make that code operate on a method argument. For example:

```
/*  the old
Ball globalBall;
void Update() {
    globalBall.Move();
    globalBall.Collide();
}
*/

// the new
List<Ball> allBalls;

// this old code is useful for a single ball; leave it mostly intact.
void UpdateBall(Ball ball) {
    ball.Move();
    ball.Collide();
}

// new code to deal with multiple Ball objects
void Update(){
    foreach (ball in allBalls){
        UpdateBall(ball);
    }
}

```

The gist of it is, don't force your previous solution onto this new concept. Although sticky- and multi- might both be triggered by powerups, they are very different concepts. It's ok to create independent code paths to accomplish different game features.

If you have further difficulties, please edit your question to specify them. That will allow more helpful answers.

# Answer
> 2 votes
**TL;DR**: *Summary is that Multiball should not be a state that you need to track so all you need to do is react when you 'collect' the power up. But no states, game or ball, really need to be changed.*

I have two assumptions, first is that you have a system already capable of rendering more than one ball. If that is not the case then see @SethBattin's response. Secondly, I assume multiball in your game works like it does just about everywhere else in that you simply release more balls into the game but the game play keeps on going as it normally would.

In this case then this is a power up that you do not need to track the state of. All you need to do is when a ball is 'given' the multi-ball power up (or in place of the state change), create X number of balls and give them their starting location/direction or whatever else they need (If you hit a multi-ball while doing a speed powerup do the new balls also need to have that powerup for example).

If Multi-Ball is timed then you are going to get into quite a few more issues and this is probably why it is not done this way... (Or that this comes from pinball games where you could not track which ball was the original ball really). However, you would want to put the new balls that you create into a multi-ball state so you can track which ones have to go away. The reason I would suggest Not doing this is because what happens if they lose the original ball? Is the game just over? Should the game just end when the original ball goes away then instead of when all the balls are one? All of this is up to you if you are doing it this way.

Hope this helps.

# Answer
> 0 votes
I would add all the powerups as game states rather than ball states. If your board/level/game object has references to your ball&paddle objects, it could delegate further if necessary. For instance, a typical powerup would be increasing/decreasing width of paddle, and it will be much easiar for you to generalise it as game-wide states, instead of having powerup A as a state on Ball, powerup B as a state on Paddle, etc.

---
Tags: java, 2d, architecture, powerup
---


# Question
Title: How can I use a char array to store image data?
I am learning the physics engine Chipmunk. In the source code, the example demo "LogoSmash" uses `char` array to store `image_data`, but I don't understand how to do that, it's amazing!

Here is the LogoSmash code in question:

```
static const unsigned char image_bitmap[] = {
  15, -16, 0, 0, ...
}

```

Will someone explain how this works and how I could do this?

# Answer
> 6 votes
In C++, a `char` is an integral data type. It holds numbers, and on most implementations you are likely to encounter, it will be capable of holding 8 bits of data.

The 24-bit RGB color representation (the most common one that does not encode transparency information) uses 8 bits for each red, blue and green channel. Thus, a single `char` can hold a single color channel of data, and three `char` objects can hold a complete RGB pixel. If you include transparency via an alpha channel (RGBA), four `char` objects can completely define a pixel.

Thus, an array of `4 x width x height` `char` objects can hold the pixel information for a image of `width` by `height` pixels. Note that one usually uses `unsigned char`s in practice, since signed `char`s allow negative values which is generally semantic nonsense for color values.

---

Since `char`s are just numbers, it's perfectly possible to encode the image data directly into one's source code as follows:

```
unsigned char image[] = {
  255, 0, 0, 0,  // 1st RGBA pixel, completely red.
  0, 255, 0, 0,  // 2nd RGBA pixel, completely blue.
  // and so on
};

```

It's rather impractical for images of any kind of complexity, since it both requires you to write or find some tool that will save or convert bitmaps into source code, *and* it requires a re-compile to change any part of the image (which is not very good for iteration), but it's a common technique for really simple demos that don't want to confuse the issue being demonstrated with lots of file IO and image read code and whatnot.

However, I wouldn't recommend using this technique in production code (or really, at all, just load the image from a file, there are plenty of libraries to help you with that).

# Answer
> 2 votes
In the case of the Chipmunk demos, I was really trying to cram the image bitmap into as little space as possible in the source code.

Some things:

* It's a 1 bit per pixel bitmap, so each unsigned char in the array actually holds 8 pixels. The funky get\_pixel() function is what unpacks the bits.
* The image\_bitmap array was generated by a Ruby script where I loaded a .png file, packed the bits for the image, and generated the C source code for the array.
* The negative numbers are only there to make the source code a little bit shorter overall.

As Josh says, this isn't really a recommended way to work with bitmaps. Normally you'd load them from a separate file. I only did it that way in the Chipmunk demos because the image was very small and I wanted to avoid using an image loading library for an otherwise simple physics demo.

# Answer
> 1 votes
May I suggest an alternative representation for an image?

Create a class/struct to represent your color in any paradigm you want(32 bit RGBA, 24bit RGB or anything else really). For example:

class Color { uint8 red, green, blue, alpha; }

Now, make sure you use dynamic arrays, and since its a lot of data, prefer the heap over stack. The perfect container will be a std::vector perhaps. So:

std::vector image\_data;

Now you can manage the container to have NxM pixels, and each of its elements represents a pixel within that image. Now you have a dynamic solution, ready to scale to any situation, you can easily convert between representations safely (raw array vs std::vector).

unsigned char\* image\_data\_raw = reinterpret\_cast(&image\_data\[0\]);

Hope it helps. You just need to find what representation your colors have and you're set :)

---
Tags: c++, image
---


# Question
Title: How to create a vertex buffer that provides this pattern?
I have a series of vertices that I want to layout with the following configuration, but I haven't been able to find out how to do this with the square and X pattern. Most of the time I have generally seen a quad split into two triangles usually using triangle lists. I suspect this is using triangle strips but I am not exactly sure how to do it. Could anyone help?

# Answer
> 1 votes
The most obvious way to do this would be to build each subsquare as a triangle fan, with the center of the X as the first vert. But then you have to use degenerate triangles between each square as you move across the rows.

Possibly more wasteful but much easier to manage, do it all as individual GL\_TRIANGLES, and use your index array to manually build the fans. Indices are cheap compared to verts, and you can get a lot of reuse out of each point.

---
Tags: rendering, vertex-buffer
---


title: Read part of texture using SharpDX

text:
# Question
Title: Read part of texture using SharpDX
I have a `Texture3D`. I want to read a part of it from CPU side. (I'm using the SharpDX toolkit (v2.5.1).)

My data is always 0, but the output shows no errors.

This is the source texture:

```
testTex = Texture3D.New<float>(GraphicsDevice, wx, wy, wz, PixelFormat.R32.Float, texDat, TextureFlags.ShaderResource, sdx11.ResourceUsage.Default);

```

I'm trying to read part of it here:

```
tempFloat = new float[1];
TextureDescription stagedTexDesc = new TextureDescription()
{
    Height = 1,
    Width = 1,
    Depth = 1,
    MipLevels = 1,
    ArraySize = 1,
    Format = testTex.Format,
    Usage = sdx11.ResourceUsage.Staging,
    CpuAccessFlags = sdx11.CpuAccessFlags.Read | sdx11.CpuAccessFlags.Write,
};
texNew = Texture3D.New(GraphicsDevice, stagedTexDesc);

deviceContext.CopySubresourceRegion(testTex, 0, new sdx11.ResourceRegion(iHPos.X, iHPos.Y, iHPos.Z, iHPos.X + 1, iHPos.Y + 1, iHPos.Z + 1), texNew, 0);
texNew.GetData(tempFloat);

```

`tempFloat[0]` value is always 0.0. The `GetData` method performs `Map` and `Unmap` of the resource automatically

If I try to call `GetData` on the original texture, it seems to get the data correctly.

Also, is there a better way to read the data?

# Answer
It seems I used deviceContext in wrong way. It should have been either initialized like this:

```
var deviceContext = (SharpDX.Direct3D11.DeviceContext)GraphicsDevice;

```

Here is the explanation what I did wrong here:

```
var deviceContext = new SharpDX.Direct3D11.DeviceContext(GraphicsDevice);

```

When creating a new DeviceContext, it is actually creating a deferred context, more relevant in multithreaded scenarios. In your case, all commands issued on this newly created deferred context were in fact no-op (because a deferred context needs a special pattern to replay it on the immediate context).

Another solution would be to use directly:

```
GraphicsDevice.Copy(testTex, 0, new sdx11.ResourceRegion(iHPos.X, iHPos.Y, iHPos.Z, iHPos.X + 1, iHPos.Y + 1, iHPos.Z + 1), texNew, 0);

```
> 1 votes

---
Tags: textures, directx11, sharpdx
---


# Question
Title: How can I create an array of GameObjects?
I need to add one assest multiple times in my scene similar to the blender array tool and I was wondering what is the best way to do this because adding each asset individually and setting there locations doesn't seem like the best way to do it. I need to:

* Create multiple sprites quickly
* Be able to set the distance between the sprites
* Set the number of sprites

How can I do this in the editor preferably without any plugins?

# Answer
If you want to create an array of this gameobject, you can do this as follows:

```
int Size = 10;     //Number of objects
GameObject[] Tiles = new GameObject[Size];

```

Let's assume you have created a prefab, called "Tile". If we want to initialize the array's gameobjects, we could do it like this:

```
//Loop for the entire size of the array, 10 in this case
for (int i = 0; i < Size; i++)
{
    //Create the game object
    Tiles[i] = GameObject.Instantiate (Resources.Load ("Tile")) as GameObject;

    //Position it in the scene
    Tiles[i].transform.position = new Vector3(i * 0.32f, 0, 0);
}

```

If you assign the following script to the Start() function of a gameobject in your scene, you will see 10 Tile prefab objects appear when you Run your game.
> 2 votes

# Answer
Have a look into the Builder Pattern. It wraps up all that complex construction for you.

Builders are best driven by some kind of external textual or binary map data file, from which are read in various shorthand specs for each entity.

So in other words with this...

```
class SoldierBuilder //singleton
{
     function build()
     {
       //encapsulates a bunch of object creations, some of which create their own subobjects, etc. in order to build this whole soldier
     }
}

```

you would do something like

```
for each (record in soldierToBeBuiltRecords) //comes from a data file
   builder.build(record)

```

Bear in mind that for instance you might have two different builders, a `SoldierBuilder` and a `WeaponBuilder`. Then the `SoldierBuilder` might utilise the `WeaponBuilder` within it's own construction code, in order to build weapons for the soldiers as spec'ed in the soldier data, *aside* from using other parameters therein to construct the soldier itself.

You can use the same builder both at level setup and during runtime. And you can use it for predefined (data-specified) entities, or dynamic entities whose specs your game logic may decide at runtime.

As for setting the distance between sprites, I guess that should be a distinct bit of logic coded in the way you want it. It doesn't really have anything to do with construction, but rather positioning in relation to existing entities. Your builder's focus should only be within the context of the entity itself.
> 1 votes

---
Tags: 2d, unity, gameobject
---


title: MMO: In-App vs. Website Purchase

text:
# Question
Title: MMO: In-App vs. Website Purchase
Im currently writing a turn based start game, which will be played in an MMO style (players download clients, central server handling the game logic etc.) and now I need to decide how I charge my players for playing my game, since this will have some implications on how player account handling is going to work.

After looking a bit around, I found two alternative ways of doing this

a) Classical in-app purchase, for which my clients need to be able to take the payment info, send them to my server which then charges the selected amount (using some API like stripe.com) and provides the selected services

b) Account administration and payment via website, and then synchronization between website and game server over some database

Most MMO games I know use the website approach (b) although I assume that in-app purchase (a) is faster and easier for my players and will therefore yield higher conversion rates.

So, my question is: Are there some major problems (security, paperwork) or drawbacks (complicated to implement) with in-app purchase I overlooked?

Im not doing a mobile game (full desktop) and Im from europe, just in case this information might be needed.

# Answer
The important thing to remember, is to keep your in-app purchased local to the server only. If a customer purchases something, whether through your website or through your game, it should get processed server-side.

Look at Guild Wars 2, SWTOR, or Hearthstone for examples of game that do this. Their in-game purchase screen is no more than a fancy website that happens to match the style of the game itself, Guild Wars 2 literally uses an in-game browser to achieve this.

Of course, you still want to take account security in mind. Just because someone's logged in game doesn't mean you can trust them with 1-click purchases.
> 1 votes

---
Tags: mmo, monetization, payment
---


# Question
Title: How can I avoid a busy-wait in this game loop implementation?
I've been developing a small framework for OpenGL and WinApi for some research purposes. My biggest problem right now is the game loop. Simplified I did something like this: Main thread:

```
HANDLE hUpdate = (HANDLE)_beginthreadex(0, 0, updateThread, 0, 0, 0);
while (!done)
{
    if (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE))
    {
        if (msg.message == WM_QUIT)
        {
            done = TRUE;
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
    else
    {
        Draw();
    }
}

```

Update thread:

```
unsigned int __stdcall updateThread(void *params)
{
    QueryPerformanceCounter(&nextTick);
    QueryPerformanceCounter(&lastUpdate);
    while (!done)
    {
        LARGE_INTEGER currentTick;
        QueryPerformanceCounter(&currentTick);

        while (currentTick.QuadPart > nextTick.QuadPart)
        {
            double frameTime = ((currentTick.QuadPart - lastUpdate.QuadPart) * 1.0) / clock.QuadPart;

            QueryPerformanceCounter(&lastUpdate);
            Update(frameTime);

            nextTick.QuadPart += TIME_STEP * clock.QuadPart;
            QueryPerformanceCounter(&currentTick);
        }
    }
    return 0;
}

```

This way i got fixed time step while draw will be called as much as it can (kinda what I was looking for). The BIG problem is that everything is operating using busy wait, and it just swallows CPU and still no real game logic has been written. Can anyone tell me, or redirect me to some good, efficient implementation of game loop? While I was researching I came across information that Sleep() is bad for game loop.

# Answer
> 2 votes
I'd move your game logic code to the same thread as your message processing/drawing code (i.e. the main thread).

This not only saves you from properly locking ressources to one thread at a time, it also allows you to use vertical synchronisation (VSync) as an alternative to waiting in a busy loop or using your own calls to `sleep()`. In addition to that, you can introduce a minimum frame time (which would essentially be something like sleeping for 10 ms), which would essentially limit you to 100 frames per second.

Also I see one tiny problem with your logic update: If your processing isn't fast enough to catch up with the time that passed (e.g. one iteration takes 10 ms, while there is supposed to be one update every 5 ms), you'll end up in an infinite loop of updates, that's getting a backlog that's only increasing in size. That's not necessarily a problem in the multithreaded approach, but if you consider merging everything, you've got a problem. In either way, you'd have to check for `done` in your inner update loop, though.

# Answer
> 1 votes
I'd suggest that worrying about CPU usage due to busy-waiting at this stage in your development is a form of pre-emptive optimization. In other words: you haven't written all of your code yet, you don't yet know what your final CPU budget is going to be, so in the absence of that knowledge you shouldn't really be making decisions relating to that budget just yet.

When you do have your game logic written you're likely going to find that you're still hitting 60fps just fine, and you'll be able to profile your full game and get a view on where your CPU usage is going. Armed with that knowledge, you can then start making some more meaningful decisions.

For example, you may find that your game actually does need 100% CPU at all times in order to maintain 60fps, perhaps owing to a heavy or complex physics simulation. Or you may only be able to hit 10fps, in which case you need to optimize. Or the opposite: you may easily hit 200fps in which case you can decide to offer some higher quality simulation, or give some of that CPU time back instead.

Once you've done this a few times you'll be able to make more accurate (and informed) advance judgements, but right now you really can't.

Sleep, by the way, can be perfectly fine for reducing CPU usage, so long as you're aware of the problems with it and take the appropriate steps to work around them. What it's **not** fine for is controlling framerate. That's not a problem for you as you're already using a proper timer.

# Answer
> -1 votes
I think your problem here is simply that your making it run as much as possible, but expecting the CPU usage to be something other than maxed out. If you simply do "while (true) ;" you should expect to see the same thing as your asking the computer to test if "true == true" constantly.

In your loop you doing essentially nothing but constantly querying the time. Sleeping while waiting until the next frame is going to drop your CPU usage, but as you implement your game logic it may be unnecessary (Here is a related topic on sleep).

Try seeing how many times it goes through that loop before (currentTick.QuadPart \> nextTick.QuadPart) == true. As you implement logic this number will fall.

To put it another way, your loop won't be consuming all that much CPU time when you actually have your game logic inside the loop. So this is a case of premature optimization. To quote from Gnome;

> Traps for the Unwary
>
> It is very easy to be misled by the profiler. There are stories of people optimizing the operating system idle-loop because that is where it spent all its time! Don't optimize code that does nothing the user cares about.

---
Tags: game-loop
---


title: Voxel Lighting in Unity3D

text:
# Question
Title: Voxel Lighting in Unity3D
I'm working on a Voxel project in Unity3D for fun and learning. I've been reading up on how this is done and have implemented a simple Voxel map in my project. My question is about the lighting. I've read several articles on how Minecraft implemented lighting. It doesn't seem too complicated but I'm wondering if it's necessary in Unity (and also I'm unsure how I would actually implement that in Unity)

So far I'm just using Point Lights on blocks that should emit light. Is Unity's Point Light efficient enough on a Voxel map if there are many light sources? So far on my scene it works OK with several lights on it. Adding many lights slows down the game as expected but since my computer is not a gaming beast I don't know if it's because Unity's Point Light is not optimized for this type of map or if it's just due to my low end computer. (To give you a point of comparison, I run Minecraft with a lot of lag but Eldritch with absolutely no lag, if you're familiar with both those games)

I would like some thoughts from more experienced users on this subject. If you had to develop a Voxel game in Unity, that may include 100 torches and 100 cubes of glowing lava, would you just use the Point Lights?

If the answer is no, is playing with the RGB values of the block textures the way to go?

# Answer
I'm not such an experienced (esp. with unity) but if the scene is static, I would not render the block using white squares (faces) with a texture, but using some pre-computed colored square with the same texture. With a shader, this would imply multiplying color of the texture by the precomputed color of the square.

Thus no real-time light computation would be done for the lighting block's square faces. I believe minecraft does not use true light objects either, seeing how mobs blinks from and to a lit/unlit state and how it's impossible to have half-lit mobs.

If you want smooth lighting, you should store a color component per visible face and per vertex.
> 2 votes

# Answer
No. Using point lights, especially in Unity Free, is far more expensive than using voxel-based lighting.

Lighting is the least expensive part of generating a Voxel world in my experience. Not only that, but by using voxel-based lighting instead of constructs such as point lights, you can achieve a pseudo-radiosity. Essentially, the light will "wrap around" corners and other obstructions much as it would appear to in many real-life situations.

Here's a THREE.js implementation of a voxel generator. While it's not Unity, the voxel calculations are the same, and the overall threading setup is very similar to what you'd have to deal with in Unity. On my machine, it takes 200ms to do the lighting, compared to ~6s to generate the terrain itself.

Voxel based lighting is generally performed using a flood-fill algorithm. Many implementations are recursive, but you can get an increase in execution speed by using a queue or stack to process the flood-fill in one method call instead.

Also of note: you may encounter rendering artifacts with point lights with the light "leaking" between the quads used to render the voxel faces if you use traditional point lights.

Additionally, by using voxel-based lighting, you now have a nice, voxelized representation of your lighting information for your scene. In theory, this could be used on the GPU to calculate per-vertex lighting for characters and moving objects.
> 2 votes

---
Tags: unity, lighting, voxels
---


title: How can I develop a game for iOS?

text:
# Question
Title: How can I develop a game for iOS?
I have a Mac arriving in the next few weeks, and plan to program a 2d game. I know a little bit of Java but nothing about Objective C. I've heard about cocos2d -- it seems good but I don't know where to start. Should I learn Objective C first and use XCode, and postpone learning how to program games?

# Answer
> -2 votes
If your goal is to make the best use of your time, I would do this:

1. Come up with an idea now. You can spend all the time in the world programming, but if you don't have a direction, it's all for naught.
2. Start learning Objective C when the computer arrives.
3. Program the game (in Objective C) once you think you can.

---
Tags: ios, cocos2d, objective-c
---