# Question
Title: Where do I begin if I want to write a C++ 2d game?
I am a C# web developer and I want to expand my skillset and have some fun while doing it. I know some of the basics of C++ and I would love to write a simple 2d game/game engine for myself using C++. What other libraries or SDKs do I need and where would I find some tutorials and informational resources to move forward?

I've already looked into XNA with C#. There are a lot of resources for that but I would rather use non Microsoft products. The point of this is to have a little fun while becoming a better rounded programmer.

Please note that I'm not asking for the *best* place to start. I'm just asking for *a* place to start.

Thanks for any help!

# Answer
> 27 votes
The standard starting place (in my experience) for C++ game dev is SDL. You've got to get your hands a little dirtier with this than you do XNA.

If you want to try something a little higher level then I would suggest SFML. It handles some of the more menial tasks for you but you've still got to keep your eye on your memory usage, etc.

# Answer
> 10 votes
Personally, I would pick Allegro 5, for the following reasons:

1. It has a CMake-based build system. This makes it much easier than most build systems for working on multiple platforms. This seems like a minor thing, but it's pretty important overall. It makes building the library much simpler.
2. SFML is still in significant flux. 2.0 is a pretty substantial change. Whereas Allegro has already been through a significant change with version 5, and it's now all about stability.
3. It covers modularity in a different way from SFML. With SFML, you ask for specific components, but you get all of them. If you ask for the graphics component, you get all of the graphics component. With Allegro 5, you always get the graphics component. But if you don't want to use Allegro's bitmap loaders, you don't have to; you can use your own.
4. It has very good documentation. SFML uses Doxygen-style documentation, but even that is pretty Spartan. Whereas Allegro 5 is more comprehensive, with functions grouped together based on specific systems that they cover. It's not perfect, but it is better overall.
5. They're smart enough to *not* try to do threading. With C++11/Boost.Threads either widely available or just around the corner, using another thread wrapper can be more than just problematic: it can be dangerous to getting your code working properly.

# Answer
> 9 votes
I would suggest using SDL. It's been around a long time so the documentation and support are pretty good, and it's one of the easiest ways I know of to get a drawing surface on the screen. It will give you practice writing classes in C++ (since you'll probably want to wrap a lot the the SDL C function calls) and also give you some experience using pointers and references and doing some basic memory management. Managing your own memory is one of the major differences between C++ and C#.

# Answer
> 4 votes
I think a **fantastic** place to start is LazyFoo. This will get you up and running with SDL faster than any other place I've seen. I'd recommend quickly getting into OpenGL (as soon as you can stomach it) because you'll get a lot more bang for your programming dollar- with hardware acceleration. If you do go that route, I recommend This Guide.

# Answer
> 3 votes
* SFML -- the baby in the group, but potentially easiest to use from what I've read.
* SDL -- the middle road. Very mature library, sensible, generally concise if a little arcane from time to time, and a very common choice. Setting up display formats can be a bit of a bastard, I've used lazyfoo's tutorials to help on that front.
* Allegro -- Geriatric, it's been around since Atari ST days. For that reason, a lot of the 2D rendering code (which I think is only in Allegro 4) is pretty darn quick since the logic was built for much lower spec systems. I personally don't find it very intuitive, even considering the documentation.

Considering OpenGL accelerates the 2D side of things these days, it's not that important to have access to the fast software renderers that Allegro and SDL have (or had in earlier versions). However when I pick a library I focus on project maturity, user base and docs more than speed (so long as speed is reasonable), and I would say SDL and Allegro win on those fronts. SDL has also been to release triple AAA titles like Civ: Call to Power.

# Answer
> 2 votes
I would recommend SFML if you are using c++. It will get you something on the screen quickly and using it with your c++ game code is straight forward.

---
Tags: c++
---


# Question
Title: How do I create a CPU read/write buffer in SlimDX (what are the legal combinations of Usage and CPUAccess flags)?
Currently, I create a vertex buffer in SlimDX like so:

```
SlimDX.Direct3D11.BufferDescription Description = new SlimDX.Direct3D11.BufferDescription();

Description.BindFlags = SlimDX.Direct3D11.BindFlags.VertexBuffer;
Description.CpuAccessFlags = SlimDX.Direct3D11.CpuAccessFlags.Write;
Description.OptionFlags = SlimDX.Direct3D11.ResourceOptionFlags.None;
Description.SizeInBytes = _BufferSize;
Description.StructureByteStride = 0;
Description.Usage = SlimDX.Direct3D11.ResourceUsage.Dynamic;

_Buffer = new SlimDX.Direct3D11.Buffer(Parent.Device, Description);

```

Which I can update:

```
DataBox box = _Parent.Context.MapSubresource(_Buffer, 0, _BufferSize, SlimDX.Direct3D11.MapMode.WriteDiscard, SlimDX.Direct3D11.MapFlags.None);
box.Data.Position = destStartPosition * _VertexStride;
/* Where T is my vertex structure type */
box.Data.WriteRange<T>(data);
_Parent.Context.UnmapSubresource(_Buffer, 0);

```

My first question is about the MapSubresource parameter **MapMode.WriteDiscard**: when the documentation says

> "the previous contents of the resource will be undefined"

, **does that mean that if I only update part of the buffer, when it is unmapped the remainder could become anything? Or simply that if I read from the DataStream there is no guarantee what I am reading will be valid?**

Second, if I specify **MapMode.Write, SlimDX will throw an exception** (`E_INVALIDARG: An invalid parameter was passed to the returning function (-2147024809)`). **Why is this?** The documentation says that I only need to have a writeable buffer for this to be valid, which I do, because that is the same requirement for WriteDiscard which I can pass successfully.

One last question, if I specify:

```
Description.CpuAccessFlags = (SlimDX.Direct3D11.CpuAccessFlags.Write | SlimDX.Direct3D11.CpuAccessFlags.Read);
Description.Usage = (SlimDX.Direct3D11.ResourceUsage.Dynamic | SlimDX.Direct3D11.ResourceUsage.Staging);

```

**The same exception is thrown, but this is the only combination of flags I can see that would give me a ReadWrite buffer, how can I create one?**

# Answer
> 4 votes
I'm not sure it's actually possible to do this, and even if it's possible I doubt it's a good idea. When you run a graphics application, the CPU and GPU are both running at the same time - the GPU is rendering frame n while the CPU is setting up frame n+1. This means any resources, like buffers, that are generated on the CPU and consumed on the GPU need to be double-buffered. There are two (sometimes more) copies of the buffer, one for the CPU to write the next frame's data, and one for the GPU to read the last frame's data. The two get swapped when the CPU hands off a new frame to the GPU (that is, when you call Present).

The Direct3D API hides all the details of this and makes it look like you just have just one buffer. When you map the buffer using WriteDiscard, you're getting the "next frame" copy of the buffer - it does NOT have last frame's data in it (it may have the data from two frames ago, but there are no guarantees). However, if you try to map the buffer in regular read/write mode, you're asking for the "last frame" copy of it - the one currently being consumed by the GPU! The API has to either stall until the GPU finishes rendering, or internally make a copy of the buffer, both of which are expensive operations.

Now, I'm not sure why you're getting an error, as my understanding of the API is that this is legal, even if it's a bad idea. However, this seems like a case where you should think about what you're doing at a higher level and see if there's a way to accomplish that without needing to map a resource that the GPU is currently consuming.

As for your question about combinations of Usage and CPUAccess - when having problems with a wrapper like SlimDX it's often a good idea to go to the source: the real D3D11 docs. :)

Finally, note that the usage is an enum, not flags, so you can't OR multiple usages together like you tried to do in that last code fragment. You only get to pick one usage.

---
Tags: c#, graphics, directx, directx11, slimdx
---


title: Interfaces 101: Making it Pretty

text:
# Question
Title: Interfaces 101: Making it Pretty
I've made a few games which I've actually released into the wild. There's one particular issue I run into over and over, and that's the issue of the interface/theme of the game.

**How can you make non-arbitrary, consistent decisions about the look-and-feel and interface of your game?**

For example, in version one of my Silverlight chemistry-based game, I made a (bad?) decision to go witha natural, landscape-style look-and-feel, which resulted in this UI:

Then in a later iteration, I got smarter and went with a more "machiney," grungy look-and-feel, which resulted in this (final UI):

I will definitely say that my taste in UI improved through iteration. But it was a result of a lot of initially arbitrary decisions followed by a lot of tweaking.

Is there a better way to figure out how to theme your game?

---

To give a parallel in writing, when you're writing a fantasy/sci-fi novel, there are a lot of elements you need to describe. While you can arbitrarily invent objects/creatures/places/etc., you get a *much more consistent world* when you sit down for a few minutes and design the area, region, planet, or universe. Everything then fits together nicely, and you can ask yourself "how would *this* work in this universe?

**Edit:** It seems like I didn't explain this well. Let me simplify the question in the extreme: when I need to lay out a title screen (with background, fonts, skinned buttons) **how do I decide how they should look?** Green or blue? Grunge or not? Rounded or flat? Serif or sans-serif?

Take that question and explode it into your game as a whole. How do you figure out how things should look? What process do you use to make them consistent and non-arbitrary?

Look at the screenshots again. I could have stuck to grass/sky/rocks, but metal seemed more fitting to the idea of chemical reactions and atoms.

# Answer
You seem to have conflicting styles.

Have a look at these UI's from Peggle, Ultima Underworld, Diablo 3, Starcraft 2, and Gran Turismo 5.

Notice how each UI is **consistent within its theme**.

**Peggle is pin-ball like in all its UI elements. Everything's a meter, a lever, a nozzle, a springboard.**

**Ultima Underworld has UI elements are iron/steel, potions, backpacks, maps. Adventure Time.**

**Similar to Ultima underworld (in fact appears to be based on UW)**

**Futuristic, sleek, simple, minimal (protoss)**

**Car interior**

So you see, your first design is completely inconsistent and unthemed. What an open field have to do with your game? Same goes for the metal background. Try a lab bench for the game board, and a chem lab background, with flasks and vials and rubber gloves and petri dishes.

**Dr. Mario is very basically medical, bacteria, virus, medicine themed**

Further **the UI should have similarly-styled graphics to the game play elements**. The chemical symbol balls are round and gently graded solid colors. The backgrounds/game board you chose have *art styles* that are completely dissimilar to the gameplay elements. The field is a vivid photograph. The metal is very detailed, while the chemical balls are smooth and relatively undetailed.
> 15 votes

# Answer
One thing I'm starting to realize is *very* important: proper use of contrast.

Look at that first picture. It's contrasty all over the place! The sky is bright, the horizon is dark, then the far grass is bright, then the bottom is dark. The tiled background wildly varies between extremely bright and extremely dark. All of this is non-information. Visual clutter. The actual important parts - the circles - are drowned out by all the contrast changes.

Now look at the second picture. The background is dark and relatively monotone. There's a bright border around the entire playing field. The tiled background is mostly dark, with thin white lines in important locations. Suddenly you can actually see the puzzle, because it's one of the most contrasty things around.

Personally, I would still tweak it a bit - I'd make the playing field look grungier as well. Those white lines to show grid divisions are important, but the human brain is really good at extrapolating straight features, and those could be a lot darker and even broken up a bit.

The big thing that jars me out of that UI is the bottom bar. It's bright, it's in your face, and it's hard to read the text. That last bit is important - the reason it's hard to read the text is, again, because of contrast. We read text partially by looking for the edge of letters, but the letters blend in unfortunately well with parts of the bottom bar.

What I would do: Rejigger the bottom bar to fit well with the main background, in terms of contrast. Make a lighter border between it and the main background to get across the fact that it's separate. Then get rid of most of the text. "Diamond" can become an actual diamond. "Atoms left" can become a pictorial view of a few atoms. "Time left" can become an hourglass or a wristwatch or a pocketwatch. "Next" can go away entirely - you say "you have to play through to see which atoms you get", but that's an annoying game mechanic. Turn it into a stack of atoms on the right, sitting on a beat-up conveyor belt, with a little visual machinery clue for which the next one in the line is. Tada! Puzzle improved, interface improved, everything looks less cluttered.

If you *do* need to use text, there's two ways to guarantee contrast. First, put your text on something which is, itself, low-contrast. If it's got a dark background, use light text. If it's got a light background, use dark text. If you can't do that (and sometimes you just can't), don't hesitate to use the outer glow effect. It's a great way to provide the right border contrast no matter what your text is on.

When you're playing with interfaces, open up an image editor, swap it to monochrome, and try two things: blur, and edge detect. When your UI is monchrome blurred, your vision should automatically gravitate to the important areas. When it's on edge-detect, the important areas should be highlighted. Examples:

Compare these two. The first one is nearly unreadable - sure, some of the gems are visible, but many of them aren't. On the second one, the grid stands out instantly, as does the dialog box. While there's only one gem on the board, you can instantly see where it is.

The first one massively emphasizes the grid edges. Some of the gems are nearly invisible. The second emphasizes those still (and more than I personally would), but it also emphasizes the border of the puzzle very strongly, and the gem is significantly more (though still not perfectly) visible.

This method isn't a panacea by any means, but it can help you track down things that should be fixed. Just keep in mind that human vision is based around edges and contrast, and design your UI to be readable by humans.
> 8 votes

# Answer
(I'm gonna come at this from a color theory perspective)

I think that your question isn't about how to make an attractive GUI, I think you're really pointing at is "How do I choose the experience I want to give my players?"

And this is mostly a psychological answer. You mention choosing blue or green or red, and it's not really about the colors, it's about the emotions the colors make you feel when you see them.

If you have a game that is red(the background is a chade of red, the player is wearing red or uses a red game piece, the fonts all are a readable shade of red) how do you think you would feel if you played this game? And it doesn't even matter what the game is.

You'd *feel* like the game was either very angry or some sort of Valentines Day game.

This is where the decision making process comes in. If you want your player to feel like they are conducting a science experiment in your chemisty game, perhaps making everything clean and simple. Maybe something that emphasises the color white.

If you want your player to feel like they are doing some sort of manufacturing job, where they feel like they are getting down and dirty with the science, then maybe your second picture, or emphasizing the colors yellow and black together.

If you want your player to feel as tho they are at one with the chemistry, like it's an extension of themselves and all living things, then your first picture could be a good start. An emphasis on light blues and light greens and natural tones like brown.

It really does come down to the raw emotion that you expect your player to feel.
> 7 votes

# Answer
Short answer: There is *no* short answer.

Design is a huge field, with tons of books, articles, and as mentioned, *libraries* that cover this question. Colour-scheme, fonts, styles, layout, use of whitespace, negative spaces, textures, colours and their meanings in different cultures, why comic sans is evil and should never be used. There's courses, books, blogs, research papers, and websites dedicate to these sort of things. There's not going to be a simple answer to this, since the question is asking a lot.

That said: Frankly, your best option is to hire a designer to help you out. If that is out of your budget, make friends with a designer to help. If that's not possible, you might have to go it alone for a while.

So a few tips. For colour schemes, use something like a Colour Scheme Designer. Spend some time learning about how colours work together, and generally, try to only pick a *few* colours, don't go overboard. The limit should be about 3 colours.

For fonts, well, there's whole articles and papers of research (here's one about serif vs sans serif). Again, the general rule is to pick, at most, two fonts. A good choice is to pick a font that is not the default, but still looks nice. If it's an option, Helvetica is a pretty nice, but there's plenty of other good ones out there.

For style and/or theme, this one is even harder to answer. I think the biggest tip here is to ***be consistent with your style***. Don't try to blend nature with scifi, or sketchy line art with his res 3d poly models. This mostly means finding one artist to do ALL the art, or doing it yourself (in the case of large companies, this is why there's an art lead). Theme is something you'll have to play with, unless you have a set theme in mind before you begin. Honestly, it might change as time goes on and you have more of the game done. Chances are pretty good that theme will change over the course of development, in fact.

Overall, while design can be taught, some people just... aren't that good at it (much like programming). This is where having a design friend to help comes in handy.
> 5 votes

# Answer
**EDITED:**

Ok, I've rewritten this, now that I understand the question better.

The reason I got confused is because you tried to give a parallel in writing, but the example you have is not parrallel at all. The design of a UI is a question of presentation. The content of a book is about the actual substance.

So, looking at UI design as a question of presentation, you have to think about what you want to present. I mean, of course you are trying to present your game, but what else? Do you want it to appear professional? Fun? Dark? Light?

As an example, I will look at the two images you posted, and tell you the impressions I get from them.

The first one, there are some obvious aspects of it we can look at. It is lighter than the second image, of course. Add that to the fact that you chose an image of a field with depth (as the field tilts away from the viewer) and the feeling is one that is much more expansive. It feels more free, it feels more light-hearted.

When you look at the second image it is, of course, much darker. It also has a background that is a flat image perpindicular to the line of sight of the viewer, taking away that sense of continuing depth the first image had. Add that the only real depth cues come from the shading on the diamond plating, and it brings that background image up very close to the camera. All these add together to give it a much darker, more claustrophobic feel to it.

So now, what can you do with the two themes? Well, the first theme is something that could be good if what you want to do is make it feel more casual. It gives a sort of sense like what the player is doing right now with the game pieces is not all that is going on in the world. The second image gives it more of a sense of urgency. The "known world" of the game is much smaller, and it puts more emphasis on what the player is doing.
> 2 votes

# Answer
Is this really about 'making it pretty'? That's a subjective thing, and I happen to think the first screenshot looks better than the second.

Picking a theme is not rocket science really - you know the key content or purpose of your game, and can keep that in the front of your mind when choosing every other aspect to go with it.
> 1 votes

# Answer
One thing nobody else seems to have mentioned so far: ask some of the people who are going to play the game for their feedback. UI designers spend a great deal of time showing designs to users and finding out what's right or wrong with them, whether they're designing a game, a word processor or a flight deck.
> 1 votes

---
Tags: gui, ui-design
---


# Question
Title: tiled map - changing textures? (XNA HLSL)
I have successfully created a tiled map of various textures. Right now, i had a Vector4 in my own custom Vertex declaration deciding what texture each of the tiles should be. This is working perfectly. I can have any of my four tiles on the map, and any combination of them.

However, i would like to start having the tiles change, yet i do not know how to change this Vector4 of the vertices. They have been added to a vertex buffer if that helps you answer the questions.

# Answer
You have to use SetData again to send the modified vertices to the gpu.
> 2 votes

---
Tags: xna, c#, textures, tiles, hlsl
---


# Question
Title: 2D circle / rectangle collision detection issue - brief overlap
I'm currently trying to build a Breakout clone as a first step into game development. I'm using the following collision detection code (adapted from https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection). I have a rectangle and a circle, and the following C# code:

```
       Point circleDistance = new Point(Math.Abs(ball.collisionRect.Center.X - block.collisionRect.Center.X), Math.Abs(ball.collisionRect.Center.Y - block.collisionRect.Center.Y));

        if (circleDistance.X > (block.collisionRect.Width / 2 + ball.collisionRect.Width / 2)) { return false; }
        if (circleDistance.Y > (block.collisionRect.Height / 2 + ball.collisionRect.Height / 2)) { return false; }

        if (circleDistance.X <= (block.collisionRect.Width / 2)) { return true; }
        if (circleDistance.Y <= (block.collisionRect.Height / 2)) { return true; }

        float cornerDistance_sq = (circleDistance.X - block.collisionRect.Width / 2) ^ 2 + (circleDistance.Y - block.collisionRect.Height / 2) ^ 2;
        Console.WriteLine("Corner dist = " + cornerDistance_sq);
        return (cornerDistance_sq <= ((ball.collisionRect.Height / 2) ^ 2));

```

The ball moves automatically, and the rectangle is controlled using the keyboard.

When a collision occurs, I'm simply inverting the X and Y components of the ball's speed vector.

Occasionally, however, when the rectangle is moving and collides with the ball on its left or right edge, it gets 'caught', and overlaps by more than a few pixels. This results in several collisions in quick succession, and the ball 'jitters' until the rectangle is moved out of the way.

You can see the overlap at https://i.stack.imgur.com/DBgVR.jpg

I'm not sure why this occurs - if I add a boolean variable 'previousCollide' that is set on collide, then stop inverting the vector if this is set, then unset it once collisions have stopped occurring, then whilst there is still visible overlap the 'jitters' go away.

How can I prevent this?

# Answer
> 2 votes
The usual way to prevent this (as far as I understand) is to have a concept of "collide and move." This means that if two objects collide, "backtrack" them until they're just touching at the moment of collision.

In your case, you may need to redo your algorithm to calculate when two objects will collide (instead of waiting for it to happen after the fact). Or, if they do collide, reverse the position of the ball according to the opposite direction of its velocity until it's on top of the paddle, and then bounce it.

I don't know if that makes sense, but basically, you want to tell when they just start to collide and THEN bounce.

---
Tags: xna, c#, collision-detection
---


# Question
Title: Question About Scrolling A Tilemap In C++/SDL/OpenGL
I been working with scrolling this week but I recently encounter a problem that I don't understand why it's happening.

In a 2D scroller I want to scroll a tilemap pixel per pixel which gives a smooth scrolling in the game, but I encounter a weird problem, when the movement of the map corresponds with the exact size of the tile, for example, the map it's scrolling 32 pixels to the right, the map seems to jump to the next tile and not the one that corresponds correctly with the screen.

This is the code for drawing the map:

```
bool Tilemap::drawTilemap(GLfloat sizeTile, int indexTileset)
{
    offsetX++;
    if (offsetX >= 320.f) offsetX = 320.f;

    GLfloat widthTilesetImage = tilesetList.at(indexTileset).getWidthImage();
    GLfloat heightTilesetImage = tilesetList.at(indexTileset).getHeightImage();

    int widthMap = 40 + offsetX/32;
    int heigthMap = 23;

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_TEXTURE_COORD_ARRAY );

    glBindTexture( GL_TEXTURE_2D, tilesetList.at(indexTileset).getTexture() );

    for (int i = 0; i < heigthMap; i++)
    {
        int startX = offsetX/32;

        for (int j = 0; j < 40; j++)
        {
            int frameIndex = layerMap[i][startX];

            if (frameIndex == 0)
            {
                continue;
            }

            frameIndex -= 1;

            const GLfloat tileX = 0.0f + ( (sizeTile)*j);
            const GLfloat tileY = 0.0f + (sizeTile*i);

            const GLfloat verts[] = {
                    tileX, tileY,
                    tileX + sizeTile, tileY,
                    tileX + sizeTile, tileY + sizeTile,
                    tileX, tileY + sizeTile
            };

            const GLfloat textureWidth = (sizeTile - offsetX/widthTilesetImage) / (GLfloat)widthTilesetImage;
            const GLfloat textureHeight = sizeTile / (GLfloat)heightTilesetImage;
            const int numFramePerRow = (GLfloat)widthTilesetImage / sizeTile;
            const GLfloat textureX = ((frameIndex % numFramePerRow) * textureWidth)+offsetX/widthTilesetImage;
            const GLfloat textureY = (frameIndex / numFramePerRow ) * textureHeight;

            const GLfloat texVerts[] = {
                    textureX, textureY,
                    textureX + textureWidth, textureY,
                    textureX + textureWidth, textureY + textureHeight,
                    textureX, textureY + textureHeight
            };

            glVertexPointer(2, GL_FLOAT, 0, verts);
            glTexCoordPointer(2, GL_FLOAT, 0, texVerts);
            glDrawArrays(GL_QUADS, 0, 4);

            startX++;

        }
    }

    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_TEXTURE_COORD_ARRAY );

    return true;
}

```

The variable offsetX it's the one that helps me move one tile at a time the map. The variable startX indicates when it's no longer drawing one tile, so in this one start in the next column of the matrix of tiles.

So, what could be wrong in my code?

Thanks for the help.

# Answer
> 1 votes
Sorry for the late answer. I already find out the problem, I leave the new code so maybe someone will find this useful. The problem was handling the different offset in each row of the tilemap, but now it's solved.

```
void Tilemap::drawTilemap(int indexTileset)
{
    GLfloat offsetXTemp = offset.x;

    offsetXTemp = transformOffsetXToIntervalValues(offset.x);

    GLfloat variableSizeTile = 32.f;

    GLfloat widthTilesetImage = tilesetList.at(indexTileset).getWidthImage();
    GLfloat heightTilesetImage = tilesetList.at(indexTileset).getHeightImage();

    int widthMap = (1280 / (int)sizeTiles) + 1;
    int heigthMap = (int) ceil( 720.0f / sizeTiles );

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_TEXTURE_COORD_ARRAY );

    glBindTexture( GL_TEXTURE_2D, tilesetList.at(indexTileset).getTexture() );

    GLfloat posXPrevious = 0.0f, posXPreviousOnTexture = 0.0f;

    for (int i = 0; i < heigthMap; i++)
    {
        int startX = (int)floor(offset.x/sizeTiles);
        posXPrevious = 0.0f;

        posXPrevious -= offsetXTemp;
        variableSizeTile = 32.f;

        for (int j = 0; j < widthMap; j++)
        {
            if ( startX == widthLevelInTiles )
            {
                break;
            }

            int frameIndex = layerMap[i][startX].getID();

            if ( frameIndex == 0 )
            {
                startX++;
                variableSizeTile = 32.f;
                posXPrevious = posXPrevious + variableSizeTile;

                continue;
            }

            if ( j == 0 && offsetXTemp != sizeTiles)
            {
                posXPreviousOnTexture = offsetXTemp/widthTilesetImage;
                variableSizeTile -= offsetXTemp;
                posXPrevious = 0.0f;
            }

            else
            {
                variableSizeTile = 32.f;
                posXPreviousOnTexture = 0.0f;
            }

            if ( j == 40 )
            {
                variableSizeTile = offsetXTemp;
            }

            frameIndex -= 1;

            const GLfloat tileX = posXPrevious;
            const GLfloat tileY = sizeTiles * i;
            posXPrevious = tileX + variableSizeTile;

            const GLfloat verts[] = {
                    tileX, tileY,
                    tileX + variableSizeTile, tileY,
                    tileX + variableSizeTile, tileY + sizeTiles,
                    tileX, tileY + sizeTiles
            };

            const GLfloat textureWidth = variableSizeTile / (GLfloat)widthTilesetImage;
            const GLfloat textureHeight = sizeTiles / (GLfloat)heightTilesetImage;
            const int numFramePerRow = (int)widthTilesetImage / (int)sizeTiles;
            const GLfloat textureX = ( (frameIndex % numFramePerRow) * sizeTiles/(GLfloat)widthTilesetImage )
                                    + posXPreviousOnTexture;
            const GLfloat textureY = ( frameIndex / numFramePerRow ) * textureHeight;

            const GLfloat texVerts[] = {
                    textureX, textureY,
                    textureX + textureWidth, textureY,
                    textureX + textureWidth, textureY + textureHeight,
                    textureX, textureY + textureHeight
            };

            glVertexPointer(2, GL_FLOAT, 0, verts);
            glTexCoordPointer(2, GL_FLOAT, 0, texVerts);
            glDrawArrays(GL_QUADS, 0, 4);

            startX++;
        }
    }

    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_TEXTURE_COORD_ARRAY );
}

```

---
Tags: c++, opengl, sdl, side-scroller, tilemap
---


title: How can I program on the GPU in Unity?

text:
# Question
Title: How can I program on the GPU in Unity?
In my previous question, I asked about why people don't program on the GPU. Now I am learning about fluid dynamics with this article. They say that it should all be done on the GPU. The game engine that I use is Unity, and I know that shaders are run on the GPU. But is there any way to program (other than shaders) on the GPU?

# Answer
> 2 votes
Vertex and pixel shaders are the primary way that graphics programming on the GPU is done. However, more recent GPUs also support some technologies for more general-purpose parallel programming, such as CUDA (NVIDIA only), OpenCL, and most recently compute shaders (on DirectX 11 GPUs; google for more info about them). I don't think CUDA or OpenCL can effectively interchange data with the graphics pipeline, but compute shaders can.

# Answer
> 2 votes
Use Compute shaders (DirectX 11) or OpenCL on desktop systems.

---
Tags: unity, gpu, gpgpu
---


# Question
Title: How can I see the height of an object within Blender?
I'm fairly new to Blender. I know there is the "Transform" section in the Object menu of the Properties tab, which contains Location/Rotation/Scale of a selected object. What I'd like to know is if there is way to tell the height (Z) of an object, or just the selected face?

# Answer
> 9 votes
In Blender 2.5 and later, select the face or edge you want to measure in Edit Mode, and turn on the Properties shelf by pressing 'N'. In here, scroll to Mesh Display \> Numerics. You can select to display the edge length and the face area of the faces.

To get the size of an entire object, the Properties shelf in Object Mode will list the X, Y and Z dimensions. It's right in the Transform section.

---
Tags: models, 3d-meshes, blender
---


title: Integrate LibRocket With SDL And OpenGL

text:
# Question
Title: Integrate LibRocket With SDL And OpenGL
I been currently involved in a game project and we reach the point we're want to added the GUI for menus and other stuff but the time that we maybe spent developing our own system could cost us a bit of time, and this is a part of the system that we don't want to lose too much time.

So, we're reading about some UI Libraries like GUIchan, CEGUI and recently LibRocket which apparently is very flexible and useful, so my question is if Librocket could be integrate with a project develop in SDL/OpenGL in C++? and if you know where to find information about that, because we're unable to find something like that.

# Answer
Yes, you absolutely can use libRocket with nearly any rendering system (There is libRocket apps in most Desktop systems, iOS and Android. )

libRocket uses an abstract render interface internally. libRocket is a library that is ready to parse text into internal structures, and then push its geometry into that abstract renderer.

So, nothing is rendered at all if you don't implement the renderer yourself. You simply inherit Rocket::Core::RenderInterface if im not mistaken, and implement a few functions yourself.

Documentation on how to do this can be found here: http://librocket.com/wiki/documentation/C%2B%2BManual/Interfaces

Then, when you assign your custom renderer, it will be used for pushing the geometry. At this point, you have full control of what to do with it.

There are samples around for OpenGL renderers, but you can adapt one to SDL, if you see that suits you !

Hope it helps.
> 7 votes

# Answer
I guess you have to make some changes in libRocket code to make it pass Window creation. I'm not sure if there is another way but I'm sure this piece of code will work! and I assume you are developing for a windows system, if you are targeting another platform there is a similar steps but with different variables and function changes!

first of all you need to get a handler to the window SDL creates. this piece of code extracts required HWND value (according to here:

```
#include <SDL_syswm.h>

struct SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);

if(-1 == SDL_GetWMInfo(&wmInfo))
    throw AVException(SDL_GetError());

HWND hwndSDL = wmInfo.window;

```

now we need to make sure libRocket uses same window for it's rendering, after a little search in it's files I've found a file `hg/shell/src/win32/ShellWin32.cpp` (address is based on googlecode) which contains window creation functions. there you'll see a function named `bool Shell::OpenWindow(const char* name, bool attach_opengl)`. that is the main function responsible for creating a window. to make libRocket reuse our `hwndSDL` variable you have to remove/comment all the lines in that function except these :

```
if (attach_opengl)
{
    opengl_attached = AttachOpenGL();
    if (!opengl_attached)
        return false;
}

```

and just before these lines add this piece of code:

```
window_handle = hwndSDL;

```

I know it's probably not the best way to do job but I'm sure it'll work. and if you are targeting anything other than windows you just have to find equivalents for HWND value and createwindow function. they sure are somewhere in codes since almost all window systems either windows or non-windows share same logic.
> 1 votes

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


# Question
Title: Updating XNA BoundingSphere - sphere moves in opposite Y direction?
In my players update method I calc the new world matrix then I update a boudingsphere by:

```
MyBoundingSphere = MyBoundingSphere.Transform(World);

```

However when the the model's World has moved vertically down MyBoundingSphere moves vertically up?! (i.e. MyBoundingSphere.Center.Y increases instead of decreases);

# Answer
During a BoundingSphere.Transform(Matrix m) operation, the bounding sphere moves in the same direction as m's Translation vector tells it to. Your problem must be elsewhere.

Have you checked that the sphere starts out in the right place? (before the downward movement of the model).
> 1 votes

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


# Question
Title: Is it sound to use javascript for cross platform game scripting instead of lua? I might need web clients for my game
I have been looking around for clues on the subject but I'm not convinced to commit to javascript as my primary scripting language.

Currently I have started with lua. But I fear it will be a limiting choice for my future projects which include web clients for my games.

So basically I would like to know if you think it would be a viable solution for handheld devices and consoles.

---

Also, I would be glad to hear about:

* anyone who had much success with javascript in cross platform games
* failures with javascript scripting engines
* restrictions within console SDKs that would prevent this type of solution
* successes using lua in web games

# Answer
> 2 votes
Javascript is absolutely getting more popular for the task and there are already games in apple's AppStore and the others that prove this. Besided the game libraries like `crafty` or `impact`, a lot of new technology around javascript has emerged over the last months and you might want to look at

* CoffeeScript to write Javascript much quicker
* Backbone.js to structure your game a lot more (I seriously use this in a game)
* Jasmine (in case you are paranoid enough to write tests for you game)
* localStorage in newer browsers to save the players data.

In can you create a server-client game then node.js is also something to look into.

When you start your game please be aware that there's not only canvas or webgl but for some games svg or even plain html with some awesome css transformations might be useful as well.

# Answer
> 2 votes
The JavaScript you would write for your desktop game's scripting would likely not be the same as what would be used as a web client (Assuming by this you mean running in the web browser). An exception would be if you are talking about using an existing engine that uses JavaScript, like Unity3D, which is already cross platform and can be run in a web browser.

The issue is that if you embed JavaScript in your engine so that you can script your game in JavaScript, that doesn't all of a sudden mean your engine can be run from the browser.

---
Tags: javascript, web, mobile, console
---


title: Understanding Perlin Noise

text:
# Question
Title: Understanding Perlin Noise
I'm toying with Perlin Noise after some work with Diamond Square. I followed the implementation by Hugo Elias that basically, makes a series of functions with x,y as input to throw each coordinate value.

My PHP code is here:

I have two questions:

How do I use the algorithm to generate a height map in an array? I did not fully understand it and just ported to PHP the pseudocode, but doing the last function (map\_perlined) after reading somewhere that the algorithm "magically" gives you transitioned values for each x,y point given (apparently, without having to read its adjacent values), I just get this when using as random function `mt_rand(-100,100)/100;`

And this when using the cryptographic: `1.0-(($n*($n*$n*15731+789221)+1376312589)&0x7fffffff)/1073741824.0;` (which, BTW, can be implemented "as-is" in PHP?):

So, summing up, three questions:

1. Is my code correct?
2. The random function can be ported to PHP as described in the code? It throws no errors, but the results are not there.
3. How do I actually use the algorithm?

**UPDATE**

Ok, made a PHP port of the code shown in Gustavson paper, and as other coder said, it just generate one octave. Have any other useful site/paper/guide about how to use this with the concepts of multiple octaves, amplitude, frequency, etc. to control the noise function? On Gustavson's paper just shows the results, not the actual implementation of the algorithm, perhaps i'm missing something?

**UPDATE 2**
@NATHAN

I made something like:

```
$persistence = 0.5;

for ($j = 0; $j < $size; $j++) {
    for ($i = 0; $i < $size; $i++) {

        for ($o = 0; $o < 8; $o++) {
            $frequency = pow(2,$o);
            $amplitude = pow($persistence, $o);
            $value += SimplexNoise($i*$frequency, $j * $frequency) * $amplitude;
            }

            //$value = SimplexNoise($i, $j) + 0.5 * SimplexNoise($i, $j) + 0.25 * SimplexNoise($i, $j);
            $this->mapArray[$i][$j] = new Cell($value);

```

And after normalizing the values to 0..1, I get a rather dull height map such as:

How do I seed the map? Perhaps what I need to implement is the 3d version with the third value a random height? But if so, I'd have to find out to take in consideration neighbour values, which I'd be ending with something like a diamond square algorithm, exactly what I do not want to do.

**UPDATE 3**

More Perlin work. I have yet to find a way to guide the noise to my results. Check these octaves and the final result:

Octave I to IV

Summed up

Each octave is pretty much the same. Check the code:

```
$persistence = 0.5;

    for ($j = 0; $j < $size; $j++) {
      for ($i = 0; $i < $size; $i++) {
        $value = 0;

        for ($o = 0; $o < 4; $o++) {
          $frequency = pow(2,$o);
          $amplitude = pow($persistence, $o);
          $value += improved_noise($i*$frequency, $j*$frequency, 0.5)*$amplitude;

        }
        $this->map[$i][$j] = new Cell($value);

```

The results are normalized. What would you use have a strong influence in the development of the noise? I see examples where changing the amplitude gives soft or rough surfaces, but even if I give a huge amplitude, I see little difference.

# Answer
What you implemented isn't Perlin noise. I'm not sure why Hugo Elias says it is, but he's confused. Here is Ken Perlin's reference implementation. It doesn't actually call any external random number generator, but uses a built-in hash function to produce the pseudorandom gradient vectors.

Note also that Perlin noise consists of just one octave. Summing up multiple octaves (scaled instances of the noise function), as Hugo Elias suggests, is a useful technique, but not part of Perlin noise. What you get by doing that is called fractal noise, sometimes "fractal Brownian noise" (because of the supposed similiarity to Brownian motion).

If you want to understand geometrically what the algorithm is doing, try this paper. It's about a different kind of noise called "simplex noise", but also includes an explanation of classic Perlin noise. Incidentally, simplex noise was also invented by Perlin and is supposed to be an improvement over his classic noise, so you might try implementing it too if you're interested in playing with noise functions.
> 29 votes

# Answer
That's a common misconception. What Hugo Elias calls "Perlin" noise is in fact fractal, or pink, noise. To better understand what Perlin noise is, you can read Perlin's article linked in Nathan Reed's answer, or libnoise docs (there's the same error there: Perlin noise is what they call Gradient noise), or CoherentNoise docs.

Now, to actually answer your question: you didn't get the expected result because noise frequency is too high. Your frequencies start with 1 and increase, meaning that every pixel in the resulting map has a random value. To see finer structure of the map, you need to "zoom in" on the noise. I don't really speak PHP, but I suppose the code should look like this:

```
$arrayMap[$i][$j] = PerlinNoise_2D($i/$width, $j/$height, $p, $octaves);

```

That is, you "stretch" one period of noise over your entire map. Of course, you can use other coefficients - just try different ones, see what happens.
> 11 votes

---
Tags: algorithm, php
---


title: Circle-Line Collision Detection Problem

text:
# Question
Title: Circle-Line Collision Detection Problem
I am currently developing a breakout clone and I have hit a roadblock in getting collision detection between a ball (circle) and a brick (convex polygon) working correctly. I am using a Circle-Line collision detection test where each line represents and edge on the convex polygon brick.

For the majority of the time the Circle-Line test works properly and the points of collision are resolved correctly.

Collision detection working correctly.

However, occasionally my collision detection code returns false due to a negative discriminant when the ball is actually intersecting the brick.

Collision detection failing.

I am aware of the inefficiency with this method and I am using axis aligned bounding boxes to cut down on the number of bricks tested. My main concern is if there are any mathematical bugs in my code below.

```
/*
 * from and to are points at the start and end of the convex polygons edge.
 * This function is called for every edge in the convex polygon until a
 * collision is detected.
 */

bool circleLineCollision(Vec2f from, Vec2f to)
{
    Vec2f lFrom, lTo, lLine;
    Vec2f line, normal;
    Vec2f intersectPt1, intersectPt2;
    float a, b, c, disc, sqrt_disc, u, v, nn, vn;
    bool one = false, two = false;

    // set line vectors
    lFrom = from - ball.circle.centre;      // localised
    lTo = to - ball.circle.centre;          // localised
    lLine = lFrom - lTo;                    // localised
    line = from - to;

    // calculate a, b & c values
    a = lLine.dot(lLine);
    b = 2 * (lLine.dot(lFrom));
    c = (lFrom.dot(lFrom)) - (ball.circle.radius * ball.circle.radius);

    // discriminant
    disc = (b * b) - (4 * a * c);

    if (disc < 0.0f)
    {
        // no intersections
        return false;
    }
    else if (disc == 0.0f)
    {
        // one intersection
        u = -b / (2 * a);

        intersectPt1 = from + (lLine.scale(u));
        one = pointOnLine(intersectPt1, from, to);

        if (!one)
            return false;
        return true;
    }
    else
    {
        // two intersections
        sqrt_disc = sqrt(disc);
        u = (-b + sqrt_disc) / (2 * a);
        v = (-b - sqrt_disc) / (2 * a);
        intersectPt1 = from + (lLine.scale(u));
        intersectPt2 = from + (lLine.scale(v));

        one = pointOnLine(intersectPt1, from, to);
        two = pointOnLine(intersectPt2, from, to);

        if (!one && !two)
            return false;
        return true;
    }
}

bool pointOnLine(Vec2f p, Vec2f from, Vec2f to)
{
    if (p.x >= min(from.x, to.x) && p.x <= max(from.x, to.x) &&
        p.y >= min(from.y, to.y) && p.y <= max(from.y, to.y))
        return true;
    return false;
}

```

# Answer
> 20 votes
The segment running from **A** to **B** can be computed as

**P**(t) = **A** \+ **D** · t where **D** is **B** \- **A** and **t runs from 0 to 1**

Now the circle is centered on the origin (move **A** and **B** if necessary to put the center in the origin) and has radius *r*.

You have an intersection if for some t you get that the **P** has the same length of *r* or, equivalently, that the length of **P** squared is equivalent to

The length squared of a vector is obtained doing the dot product of a vector by himself (this is so true that if one finds a suitable operation for the dot product he can define a new and consistent concept of length)

**P** · **P** = (**A** \+ **D** · t) · (**A** \+ **D** · t) =

**A**·**A** \+ 2 **A** · **D** t + **D** · **D**

We want to find for which t we get **P** · **P** = r² so we end up to ask ourself when

**A**·**A** \+ 2 **A** · **D** t + **D** · **D** t² = r²

or when

**D** · **D** t² + 2 **A** · **D** t + **A**·**A**-r² = 0

this is the very famous Quadratic equation

at² +bt +c = 0

with

a = **D**·**D**; b = 2 **A** · **D** and c = **A**·**A**-r²

We have to check if the determinant **b² - 4ac** is positive and so we find 2 values of t that give us the intersections points **P**(t).

**t must be between 0 and 1** otherwise we found solutions that lie on the line passing through **A** and **B** but that are before **A** or after **B**

**\[EDIT\]**

Since other questions may find some help to this answer, I decided to try to simplify the the reasoning in this edit using some images. This is the starting condition. Now focus on the segment **A\_B**

**D** is the vector that moves A into B so if t is between 0 and 1, **D**·t is a "proper fraction" of D so the point **A** \+ **D**·t lies in the **A\_B** segment: the brown points comes when t is between 0 and 1 and the dark green one is when t \> 1.

Now we can simplify things if we move the circle's center into the Origin. This can be always done because is a simply change of coordinate system that preserve geometry, angles, intersection, measures etc.

Now we have a simply way to compute the lenght of **P** when t varies and say for which t **P** crosses the circle's boundaries.

As you see **P'** is in length greater than r while **P"** is less than r. Since both the vector lenght and r are positive numbers, the relation of order of being greater or less than are preserved is we compute the relation between the lenghts squared and the radius squared. **P\*1** and **P\*2** are the point that makes the **|P|²** equal to r²

As mentioned in the pre-edit section, we arrive to get a quadratic equation where t is our variable. As is known solution values of t range from the case when t is a couple of complex numbers - that means no intersection; the case when t are two equal solution - that means that there is one intersection; the case when there are two distinct solutions- that means that there are two intersections.

The *Discriminant* is used to discriminate the previous condition and a validity test is done on t to see if it a valid intersection but outside our segment - i.e. the solution t has to be real and between 0 and 1 to be considered a proper intersection that fall in the segment **A\_B**

---
Tags: c++, collision-detection, mathematics, geometry
---


# Question
Title: Get position of point on circumference of circle, given an angle?
I would like to know how to get a specific point on the circumference of a circle, given an angle. The diameter of the circle is 1, and the center point of the circle is `{ X: 0.5, Y: 0.5 }`.

# Answer
You can work this out using basic trigonometry. http://www.freehomeworkmathhelp.com/Trigonometry/Trigonometry\_Introduction/trigonometry.html

```
Tan(angle) = Opposite / Adjacent
Sin(angle) = Opposite / Hypotenuse
Cos(angle) = Adjacent / Hypotenuse

```

I always remember the above as

```
The Old Arab
Sat On His
Camel And Howled

```

The above means if we have the angle and one length of a right-angled triangle we can work out the lengths of the other sides. Luckly your problem can be thought of as calculating the length of triangle sides:

Above, r is the hypotenuse, x is the adjacent and y is the opposite.

So for x:

```
Cos(a) = x / r
Cos(a) * r = x
x = Cos(a) * r

```

And for y:

```
Sin(a) = y / r
Sin(a) * r = y
y = Sin(a) * r

```

This is assuming a circle at (0, 0), so we just add on the circle's center.

```
radius = 1;
CenterX = 0.5;
CenterY = 0.5;

x = Cos(angle) * radius + CenterX;
Y = Sin(angle) * radius + CenterY;

```

**Note:** The C# Math functions use angles in radians, so if you have degrees convert them first:

```
radians = degrees * Math.PI / 180

```
> 24 votes

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


# Question
Title: How does one multiply by a constant in a VS1.1 assembly vertex shader?
I'd like to multiply a vector by -1

e.g.

```
mul    r0,    r0,    -1

```

When I try this, I get this error message:

```
SimpleShaderA.vsh(20,17): error X2000: syntax error : unexpected integer '1l'

```

How can I specify -1 in my (first) shader program?

# Answer
> 2 votes
The `mul` assembly instruction takes registers as inputs, not constants. You can do this instead

```
def c0, -1, -1, -1, -1
mul r0, r0, c0

```

which uses the def instruction to define a constant vector in register `c0` and uses that as the second multiplicand to `mul`.

You could also use swizzling on the `c0` register, so you could put different constants you may need to multiply by in `c0`'s components. You can also just write the multiplication in terms of `c0` and assign it values via the `Set***ShaderConstant*` APIs.

---
Tags: shaders
---


# Question
Title: Does the ClientSizeChanged event disable exceptions?
If I illegally index into a list in the subscribed ClientSizeChanged() method, no ArgumentOutOfRangeException is thrown. Is this normal behavior ? And if so, when should I expect this behaviour ?

---

@ Roy T. : You're right in that it is an event which I'm subscribing to as follows :

```
game.Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);

```

and here's my event handler addendum (sorry, I don't know how to properly talk about these things) :

```
    // Event manager that responds to the window size being changed
    private static void Window_ClientSizeChanged(object sender, EventArgs e)
    {
        presentationRegion = GDM.GraphicsDevice.PresentationParameters.Bounds;
        if (currentScreen <= 0 || currentScreen > screens.Count)
            throw new Exception("currentScreen index is out of bounds of the screen list");

        List<int> myIntList = new List<int>();
        myIntList[-2] = 7; // Exception is not thrown here

        screens[currentScreen - 1].UpdateLayout();
        //Game.Window.Title += " WinCSC | ";
    }

```

I've put in the integer List just to demonstrate the effect. Although I originally noticed it with the screens\[currentScreen-1\].UpdateLayout() call.

@ Blecki : You are onto it I think. So when I trace the execution, as soon as i index into myIntList with an index of -2 execution breaks out of Window\_ClientSizeChanged() and the exception is not caught. And even if I throw my own exception inside Window\_ClientSizeChanged() the application continues without the debugger catching it.

# Answer
> 1 votes
You should check out this question and my answer to it. I think you may be getting bit by the same issue, specifically the fact that in 64-bit Windows, exceptions that reach the managed/native transition boundary are quietly swept under the rug, never to be seen again.

This occurs most often in event callbacks for Windows Forms and other wrapper APIs that occur in response to Win32 messages, such as HWNDs being constructed (the Windows Forms `Load` event) or resized (possibly the client-size-changed event you are trying to hook now).

As I noted in my other answer, there's a detailed explanation of this behavior here.

---
Tags: xna
---


# Question
Title: How to get the maximum installed version of DirectX?
Okay, So I would like my engine to detect weather or not it can use DirectX 10, if it can't it defaults to DirectX 9.0c but, the function DirectXSetupGetVersion() will only return Versions 5 through 9. Could someone point me to what could tell me the device capabilities? Thank you for your time.

# Answer
Detect the OS version. If you are on XP or below, you are limited to 9. Using the DirectXSetup API isn't terribly useful, instead you should look at device capability bits to determine what features are supported (and to what extent) and tailor your code based on that.

If you are on Vista or above, you can use the D3D11 API. When you initialize D3D11, you can specify and/or query for the feature levels supported. You could also just attempt to initialize D3D10 and see if it fails.

In all cases, you should package the appropriate runtime redistributable(s) with your application installer to ensure the DLLs are available at runtime.
> 6 votes

# Answer
Try a LoadLibrary on d3d10.dll - that'll tell you quickly enough if Direct3D 10 is available.

Caveats:

The user could quite easily pop a DLL called "d3d10.dll" in their program folder which would break this.

If you statically link to the Direct3D 10 libs then trying to run the program on XP or below just won't work anyway; Direct3D 10 or above is just not available for these Windows versions.

Direct3D 10 is always gonna be installed anyway on Windows Vista or higher (whether or not it can actually run a Direct3D 10 program is another matter).

I think we need more info, such as what versions of Windows you're targetting, before we can definitively answer this one.
> 0 votes

---
Tags: c++, directx, microsoft, compatibility
---


# Question
Title: How can I move an object around the screen in cocos2d?
I am trying to move the object around the screen using cocos2d. I have this code:

```
-(void) move
{
  CGFloat upperLimit = mWinSize.height - (mGunda.contentSize.height / 2.0);
  CGFloat upperLimit1 = mWinSize.height;
  CGFloat lowerLimit = (mGunda.contentSize.height / 2.0);
  CGFloat RightLimit = mWinSize.width - (mGunda.contentSize.width/2.0);
  CGFloat Right = (mGunda.contentSize.width/2.0);

  if(mImageGoingUpward ) {
    mGunda.position = ccp( mGunda.position.x, mGunda.position.y + 5);

    if(mGunda.position.y >= upperLimit) {
      mImageGoingUpward = NO;
      mHori = NO;
    }
  } else {
    mGunda.position = ccp( mGunda.position.x, mGunda.position.y - 5);
    if(mGunda.position.y <= lowerLimit) {
      mGunda.position = ccp(mGunda.position.x +5, lowerLimit);
    }

    if(mGunda.position.x >= RightLimit) {
      mGunda.position = ccp(mGunda.position.x, mGunda.position.y+10);
      mHori = YES;
    }

    if(mHori) {
      if(mGunda.position.y >= upperLimit) {
        mGunda.position = ccp(mGunda.position.x - 5,mGunda.position.y);
      }
    }
  }
}

```

It is supposed to move the object around the screen. The code mostly works, but it doesn't move the object from the top-right of the screen to the left of the screen.

# Answer
> 1 votes
it's basically because when you mark `mHury` as true, this statement `if(mGunda.position.y >= upperLimit)` is still not true.

# Answer
> -2 votes
Check through your logic - it is broken. To sum it up in English, assuming I got it right (your code is horribly indented and not C++ :P)

if going upwards then adjust position upwards and if we exceed some limit in y stop further upwards movement. else: lower the image (wtf???) if y is below some lower limit move it to the right (wtf???) if x is above some upper limit then move it upwards at double speed (again, wtf???) and set a flag to say we are moving horizontally if the horizontal flag is set and we have y exceeding some upper limit then move it to the left. (again, wtf???)

Maybe I am missing something, but this makes no sense to me. What are you actually trying to achieve and how is the requirement to move input to this code (e.g. who sets mImageGoingUpward - can mHori be set from outside, etc.)? It is not very obvious, which precludes a detailed and complete answer to the question.

---
Tags: iphone, cocos2d-iphone, ios
---


title: Is there a proxy for the Steam Web API?

text:
# Question
Title: Is there a proxy for the Steam Web API?
I'm making a small spreadsheet that tracks the amount of kills my wrench's eaten over time in TF2. So far I've been manually copy pasting fields from the TF2 window, but hey, Steam does have some API I could consume, and Google Spreadsheets can consume XML too. This number I'm tracking should also be exposed by the `GetPlayerItems` route, so I should be golden!

Except the Steam Web API *requires* a domain-bound authorization key (!). I don't own docs.google.com, so I can't get one. Thus, I cannot make the API call.

Is there some kind of API proxy service for the Steam Web API so that I can query the API without having to buy a whole damn domain for such a simple use case? ...or do I have to resort to scraping middle men such as tf2b.com?

# Answer
As Thomas McDonald noted, while your (one) API key is bound to a domain, **your requests do actually not need to be made from there.** So, *no proxy service is necessary.*

Since I already do have a blog, I registered an API with that site, and now I can happily consume the API without resorting to scraping.
> 5 votes

# Answer
You can request a key for a No-IP subdomain and do your petitions from your own computer.
> -1 votes

---
Tags: steam
---


# Question
Title: Trouble rigging rotating head to pivoting arm
I've got a 3ds max model and I'm trying to rig it. I followed some tutorials, but I got stuck. I've got my rotating head, and the arm that holds it and pivots up and down, but the two don't "connect" well.

Here's my rigging set up:

The leftmost dummy should move up and down and control the height of the miner head (the jagged-edge wheel) and the arm that holds it.

But, when I move my dummy up vertically to test, the arm works perfectly, but the miner head ... uh, doesn't. This is from the same angle as the first shot and you can see that the miner head tilts, instead of moving straight up and down.

I tried playing with the miner head's pivot points, but they seemed perfectly centered. Is there a way to make my miner head only go straight up and down (that will still work with my rotation constraint? ) instead of doing this strange sideways tilting motion? Maybe that's not the right thing to do, I could really use some hints in where to go from here to fix this strange tilting motion..

# Answer
> 0 votes
So, the solution involved going back a few steps, before any constraints were added.

First, the miner head wasn't rotating correctly, but fixing the pivot point before doing anything else - especially constraints, helped a lot.

Next, we want a look at constraint from the arm to the up-down-dummy, just as it was before. We also want the same constraint on the head, only, with much less influence, so when it moves up and down, it appears to stay on it's arm.

Finally, the rotation constraint on the head, as it was before.

So, the problem was : 1- pivot point wrong, 2- used the wrong constraints

---
Tags: 3dsmax, rigging
---


title: Ideas for 2D Water Simulation

text:
# Question
Title: Ideas for 2D Water Simulation
I am looking for any input on simulating water in 2D, against a rather large (call it) blocked/not blocked array (viewed from the side). I have come up with the following ideas:

## Cell Automata

Do a massively parralel simulation on the CPU, using cell automata. With rules as simple as:

* If there is a cell open to the bottom move to it.
* Check the left and right cells, choose a random one out of the two and move to it.

**Pros**

* Simple to implement.
* Meaningful/deterministic in a multiplayer system.

**Cons**

* Probably really slow.
* Not convincing.

## Fluid Dynamics on the GPU

Perform a rough approximation of fluid dynamics on the GPU against a texture like the following:

```
+------+-----+-----+-------+
|R     |G    |B    |A      |
+------+-----+-----+-------+
|vX    |vY   |NULL |Density|
+------+-----+-----+-------+

```

**Pros**

* Probably really fast.
* Could be quite convincing.
* A further pixel shader could render it directly.

**Cons**

* Difficult to implement.
* Difficult to tweak.
* I can't allocate a single texture the size of my level.
    + I could overlap the grid areas, but this would add further complexity.

## Particles

Use particles to simulate the water. During rendering using additive blending and then apply a multiplication function to the alpha channel to give the water crisp edges.

**Pros**

* Will probably look nice.
* Easy to implement.
* Easy to render.
* Meaningful in a multiplayer system, although would require quite a bit of bandwidth to transfer.

**Cons**

* Inter-particle effects will probably be slow (neighborhood lookup).
* Could lead to water 'leaking' through solid spaces (because the solid space is small, e.g. 1px).
* Could lead to strange holes in the water depending on the particle size.
* Both of the above could be mitigated by allowing particles to drift closer together than their real size, however would cause problems with the inter-particle and particle/landscape performance.

Any further ideas?

*Note:* This is an approximation, I am not looking for physically correct water here - just something that 'is good enough' (bonus points for quick and dirty). The game is multiplayer, so unfortunately the whole level needs to be simulated continuously.

# Answer
> 12 votes
every time I tried to simulate water I just ended up applying a lowpass filter on a texture representing water level. It's very simple to implement but it fails whenever you get massive changes in water level which may generate large waves. In this method there are some places where water always have some constant level, like river ends. in those cases you just over right color for that specific pixel.

**Pros:**

* easy to implement
* realistic results in case of calm waters
* fast compute using GPU
* easy to define static water levels or water sources

**Cons:**

* unable to simulate waves

for wavy waters I use some way similar to your Cell Automata algorithm but with a small change that will let me use shaders to compute next step from current situation, here is a sudo code, again I've got a texture representing water level in each pixel color:

```
foreach (pixel p) in oldTexture
{
    newtexture.pixels[p.x,p.y]    += p.color / 5;
    newtexture.pixels[p.x+1,p.y]  += p.color / 5;
    newtexture.pixels[p.x-1,p.y]  += p.color / 5;
    newtexture.pixels[p.x,p.y+1]  += p.color / 5;
    newtexture.pixels[p.x,p.y-1]  += p.color / 5;
}

```

this algorithm has features all similar to the previous one but it works better in wavy waters instead of calm ones. it your choice based on the sea you are simulating to use either one of them.

in the end you've got a texture which tells you water level for each position, in the next step you've got to draw results somehow, the easiest way is to generate a mesh based on water level data.

---
Tags: physics, simulations, water
---


# Question
Title: How can I implement fast, accurate 2D collision detection?
I'm well aware of how to detect if two or more 2D objects collide but I'm interested in how to decide whether to check for a collision. In previous projects, I just had every object check against every other object (I know, O(n^2) level of stupidity) and it created a less than fluid gameplay.

Various forums hail the greatness of Quadtrees, B-Trees, and any other kind of tree or structure you can think of.

What is the most efficient structure for determining whether a collision should be checked?

# Answer
> 14 votes
For a 2d game, unless the 2D objects have a very heavy distribution to one side of your map, a uniform grid is almost always the way to go. The memory complexity is straight forward, (proportional to the dimensions of your map), and with a reasonable distribution, has O(1) look-up time and an average of log(numberOfObjects / (rows * columns)) ^ 2 intersection tests done per cell. You might decide to only check cells which have had an object move in them, which makes static geometry much more efficient. It's easy to modify a uniform grid on the fly, (much less of a pain than in tree based solutions), and it is simpler to implement. The only time I would say not to use it in a 2D game is when the memory requirements of a uniform grid become too large, (say a space sim where the levels are sparse but enormous).

# Answer
> 2 votes
2D Physics engines such as Box2D and Chipmunk, make heavy use of a spatial Hash Map

see http://chipmunk-physics.net/release/ChipmunkLatest-Docs/#CollisionDetection for reference. The chipmunk demos include a really good spatial hash visualizer which makes it really clear how they technique works.

# Answer
> 1 votes
If your world has one very "long" dimension (call it X), compared to others, you can keep the objects in an ordered-list which you can re-sort as they move, and then collision detection means only checking for objects which overlap in the X axis.

Another possibilty is to keep active/passive lists of objects, and don't bother with the passive objects (which aren't moving at all).

If they are all medium-sized objects which are visible to the player on the screen, everything vs everything is probably not too bad.

Other than that, I'm with Darcy, a uniform grid is good.

---
Tags: 2d, collision-detection, data-structure
---


# Question
Title: Does Blitz3D use its own 3D engine or does it wrap OpenGL?
How does Blitz3D work? I mean internally, does it use OpenGL with basic wrappers or it using some open source 3D engine that itself wraps OpenGL?

# Answer
> 5 votes
Blitz3D's engine is based on DirectX 7. It does not uses OpenGL at all.

# Answer
> 1 votes
In addition to earok: BlitzMax was first dialect of Blitz that was using OpenGL.

---
Tags: opengl, blitzmax
---


# Question
Title: Restricting Camera Movements with OpenGL
I've been programming a game using the Java library LWJGL. I've got a little problem, though. It is a 2D game, and I'm aiming for a game like the original Civilization (I quick Google of "Civilization 1" will show you what I want). So far I have been able to generate a random 64x64 tile world. Each tile is .5f in size, drawn like this:

```
float size = .5f;

//...

GL11.glTexCoord2f(uvCoords[0][0], uvCoords[0][1]); GL11.glVertex3f(-size, size, 0.0f);
    GL11.glTexCoord2f(uvCoords[1][0], uvCoords[1][1]); GL11.glVertex3f( size, size, 0.0f);
    GL11.glTexCoord2f(uvCoords[2][0], uvCoords[2][1]); GL11.glVertex3f( size,-size, 0.0f);
    GL11.glTexCoord2f(uvCoords[3][0], uvCoords[3][1]); GL11.glVertex3f(-size,-size, 0.0f);

```

Now, I don't want my camera to be able to leave this 64x64 space and see black. My camera works like this:

```
GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(position.x, position.x + Display.getDisplayMode().getWidth()/zoom, position.y + Display.getDisplayMode().getHeight()/zoom, position.y, -1, 1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

```

I am restricting its movements like this:

```
public void moveForward(float distance)
    {
        if(position.y <= 0.5f)
        {
            return;
        }
        position.y -= distance;
    }

    public void moveBackward(float distance)
    {
        if(position.y >= Constants.WORLD_SIZEY - 0.5)
        {
            return;
        }
        position.y += distance;
    }

    public void moveLeft(float distance)
    {
        if(position.x <= 0.5f)
        {
            return;
        }
        position.x -= distance;
    }

    public void moveRight(float distance)
    {
        if(position.x >= Constants.WORLD_SIZEX - 0.5)
        {
            return;
        }
        position.x += distance;
    }

```

Because the camera's location is the top left corner of the display, it works great for moveForward and moveLeft. However, for moveBackward and moveRight, it moves out of the 64x64 box until the top left corner gets to the edge. How do I prevent this, because I don't know how to get the screens length in the units I am making the tile sizes.

Sorry if this is hard to understand, because I don't know how to explain it myself. That's why I've had so much trouble finding an answer.

# Answer
> 1 votes
Seems to me you want the limit for moveRight to be Constants.WORLD\_SIZEX - 0.5 - Display.getDisplayMode().getWidth()/zoom, and similarly for moveBackward.

The coordinates you pass in to glOrtho are the world space locations that will be mapped to the corners of the screen, so you see that when position.x equals the expression I just mentioned, the right edge of the screen will be at Constants.WORLD\_SIZEX - 0.5, which (if I understand correctly) should be the right edge of the rightmost column of tiles.

Incidentally, I'd suggest applying the limits like this:

```
public void moveForward(float distance)
{
    position.y -= distance;
    position.y = max(position.y, 0.5f);
}

```

The way you did it will only work correctly if you only move around in steps of 0.5. Any other step size could lead to the camera going a bit beyond the bounds and seeing some black, although never more than half a tile's worth.

---
Tags: opengl, java, lwjgl
---


# Question
Title: What is a good method to randomly generate edges between graph nodes?
I am doing a random map generator for a 4X space game.

Each node in the game is place at a random (x,y) coordinate on a 2d grid. A node can have one or more bi-directional edges to another node (representing wormholes). All nodes must have at least one wormhole, and all nodes must belong to the same graph.

Ideally, a wormhole should not exceed a maximum length and if possible, wormholes should not cross each other.

My naive implementation is to iterate through all the nodes and have the node link to the closest 3 nodes. However, I end up with numerous sub graphs. What's a good method to generate the edges for the nodes?

# Answer
> 9 votes
Here's a good answer to a similar question.

First make a connected graph, perhaps using a minimum spanning tree as in the link above. He suggests using random edge weights to make the "minimum" tree random. Then you can randomly add more edges so it isn't just the minimum tree. How exactly you add the random edges depends on what sort of graph you want.

---

In fact, if the problem is just in making sure the nodes all belong to the same graph, you could take your current method of random generation (or any other), and apply Prim's algorithm on top of it. If you wanted to make minimal changes to the graph just to be sure the subgraphs are all connected, you could set the edge cost to 0 for edges that are already there.

# Answer
> 7 votes
The major constraints of your problem are twofold: creating a 1-connected graph; and creating it with proximal connections. Philip's answer, while somewhat valuable, does not address all constraints of your problem

> Ideally, a wormhole should not exceed a maximum length and if possible, wormholes should not cross each other.

When you naively connect points in a cloud, you run the risk (and a high one, at that) of these conditions not being fulfilled.

So you see, the problem isn't so much one of connectivity as one of proximity on those connections. It is trivial to connect every node in a graph to every other node, but connecting only to those that are closest while maintaining 1-connectedness of the overall graph is a bit more tricky.

This is what a Delaunay triangulation creates, in *n* dimensions. The first reason to use Delaunay triangulation is that it fulfills both of these implicitly. The second reason is that it is far easier to work backwards from such a graph (subtracting edges and vertices you don't want), than to try to create it in other ways.

1. Randomly create your full point cloud.
2. Delaunay-triangulate it.
3. Construct the graph (connection of points). In this, you can either generate the whole graph (every star) first, and then derive graph as minors representing your wormhole-connected regions, when performing step 4. Alternatively you can work the other way around, generating only the wormhole-connected regions first as supergraph nodes, and then in a second phase, generate individual stars within those regions' bounding volumes (for these I would derive the Delaunay triangulation's graph dual -- the Voronoi diagram in 3 dimensions) as subgraphs. Now you have proximally-connected star clusters, and all clusters are connected by rarer wormholes: your topology and topography make sense to the player.
4. Apply intelligent methods to shape the super- and subgraphs, depending on how you've chosen to treat it in step 3.

It's important to see that this is a hierarchical process. The first level deals with wormhole connectivity; the second deals with distances presumably traversable using a standard ship drive. You can apply Delaunay at one or both levels to satisfy your constraints.

Doing this purely topologically will leave you with wormholes that don't make sense, since they might connect one side of the galaxy to another, in spite of a high density of stars in beween (and perhaps even falling on the wormhole's direct route). Topology is not topography; the latter is a consideration over and above the former. You are concerned with proximity and thus topography.

---
Tags: random, graph-theory
---


# Question
Title: How to create a view looking down the sight of the gun
I am in the midst of creating an FPS game using XNA. I am using the camera class from the First Person camera demo from dhpoware.com, and everything is working great. What I'd like to implement is the ability to press the right mouse click and then the view changes so that you look down the gun, like the following image:

I have searched and searched but haven't found anything that will help me out, or at least point me in the right direction. Can anyone help?

# Answer
Isn't it as simple as rendering your gun geometry (or 2d HUD style gun) near the camera and narrow the field of view.
> 7 votes

---
Tags: xna, xna-4.0, first-person-shooter
---


title: OpenGL datatypes conversion overhead

text:
# Question
Title: OpenGL datatypes conversion overhead
In my project, certain data is stored in floating point datatypes (C's native float, double). Before sending the data in a VBO to OpenGL I have to convert this data to GLfloat with some pretty silly code.

```
float data[DATA_SIZE];
GLfloat *new_data;

new_data = malloc(sizeof(data));
for (i = 0; i < DATA_SIZE; i++)
    new_data[i] = (GLfloat) data[i];

upload_to_gpu(new_data);

free(new_data);

```

Of course, since I know `float` is equal to `GLfloat` on my platform, I can just ignore this but then my code won't be properly platform-independent. I could also store the data in my program in OpenGL native datatypes but this is unacceptable as I don't want to fixate my code only on OpenGL (DirectX or a software renderer are possibilities I don't want to exclude).

How can I solve this? Is the conversion step unavoidable? Or am I obligated to store my geometry in GLfloat's?

# Answer
Don't do this.

On any system supporting OpenGL you will ever use, GLfloat is the same as the C/C++ native float - IEEE 754 single precision storage.

The C standard does not require IEEE 754 be used as the underlying representation, but a vanishingly small percentage of machines do not meet this criterion. C and C++ compilers will complain at compile-time if GLfloat is not equivalent to float, because then a `GLfloat *` is not compatible with a `float *`. So even in the (0%) chance you do end up on one of these systems, you will have plenty of warning.

Other types, such as GLint, are more relevant, because there are a small but significant number of systems where ints are 16 bits and in these cases you will find GLint aliased to a type permitting at least 32 bits of storage. However, in any game programming task, you are very unlikely to use these kind of systems.
> 18 votes

---
Tags: opengl
---


title: Unity on Facebook?

text:
# Question
Title: Unity on Facebook?
Hey, I know Flash works using Facebook, and I think I've seen some Java stuff on there too, but does anyone know if the Unity Player can be used in Facebook?

# Answer
> 14 votes
The Unity Player can be used on facebook.

One relevant thread on integration: http://forum.unity3d.com/threads/7812-Unity3D-meet-Facebook!

And one very popular game: https://www.facebook.com/uberstrike

Here's a thread on Unity Answers that also has some more details: http://answers.unity3d.com/questions/82/how-can-i-make-my-unity-application-work-inside-facebook

# Answer
> 6 votes
This is kind of a nonsensical question based on a poor understanding of how Facebook apps work. Facebook doesn't really have anything to do with what technology exactly you are using; they simply embed your app as an iframe on their site. You build your app using whatever technology you want on your own server, and then simply tell Facebook what URL to point to.

So basically anything that can be done in a web browser can by done as a Facebook app. Now there are certain technologies that get used more often for Facebook apps, but those trends are due to reasons that have little to do with Facebook, like the fact that most browsers have the Flash plugin.

Also, while you can build your app with pretty much any web technology, you will need to work with PHP or JavaScript (does Facebook provide an API for any other languages?) if you need to interface with their API (eg. to retrieve the player's friends list). That doesn't mean you actually have to build the entire app using PHP or JavaScript, but that you need to have at least a small script acting as the middle-man between your app and Facebook's API.

(I'm not criticizing you btw; until recently I didn't understand how Facebook apps work either, and thought they were hosted on Facebook's servers or something.)

---
Tags: unity, facebook
---


title: How do I use render targets in XNA?

text:
# Question
Title: How do I use render targets in XNA?
I'm trying to render text (or whatever) off screen. But I have a strange issue where the render target size matches the window size and not the render targets size. Yes, it is a contradiction! Here's the render target:

And here's the code, chopped up and put together to demonstrate what's happening in one place :

```
UserInterface.SpriteBatch.Begin(SpriteSortMode.Immediate,
                                BlendState.AlphaBlend,
                                SamplerState.PointClamp,
                                DepthStencilState.None,
                                RasterizerState.CullNone);

RenderTarget2D rt = new RenderTarget2D(UserInterface.GraphicsDevice, 200, 200);
UserInterface.GraphicsDevice.SetRenderTarget(rt);

UserInterface.GraphicsDevice.Clear(Color.Blue);

Rectangle rect = new Rectangle(0, 0, 200, 200);
UserInterface.SpriteBatch.Draw(pixel, rect, Color.White);

renderTarget.GraphicsDevice.SetRenderTarget(null);

UserInterface.SpriteBatch.End();

if (frame == 0)
    rt.SaveAsJpeg(File.OpenWrite("renderTarget.jpg"), rt.Width, rt.Height);

```

The render target is created at 200x200, I then set the render target on the graphics device. I clear it to blue and draw a pixel at 200x200 (in white). Lastly, I save off the render target.

But why does the sprite batch render the pixel in proportion to the window (just take my word that it is `rectSize / WindowSize * RTSize`) rather than filling the render target which I believe it should do in this case?

# Answer
When you call `SpriteBatch.Begin()` with `SpriteSortMode.Immediate`, the current device settings will be applied to the effect of the `SpriteBatch`. This also includes the dimension of your current render target (the back buffer, if no specific render target is set). If you then set and draw to your newly generated render target, you will experience the result you described in your question.

To get the result you wish, you just have to set the render target before you call `SpriteBatch.Begin()`. Something like this should do it:

```
RenderTarget2D rt = new RenderTarget2D(UserInterface.GraphicsDevice, 200, 200);
Rectangle rect = new Rectangle(0, 0, 200, 200);
UserInterface.GraphicsDevice.SetRenderTarget(rt);
UserInterface.GraphicsDevice.Clear(Color.Blue);

UserInterface.SpriteBatch.Begin(SpriteSortMode.Immediate,
                                BlendState.AlphaBlend,
                                SamplerState.PointClamp,
                                DepthStencilState.None,
                                RasterizerState.CullNone);
UserInterface.SpriteBatch.Draw(pixel, rect, Color.White);
UserInterface.SpriteBatch.End();

renderTarget.GraphicsDevice.SetRenderTarget(null);

```
> 7 votes

---
Tags: xna
---


# Question
Title: How to calculate vector that is perpendicular to the direction of moving in Flash?
In flash i have a class that extends movieclip and i am moving it forward, up and down, and rotating it. How can i calculate the vector that is perpendicular to this movieclip?

# Answer
> 4 votes
Well as explained here it is pretty easy to get the perpendicular vector from the movement vector:

> Let's say you have a boat that has cannons that fire to the left and right. Given that the boat is facing along the direction vector (2,1), in which directions do the cannons fire? This is easy in 2D: to rotate 90 degrees clockwise, just flip the two vector components, and then switch the sign of the second component. (a,b) becomes (b,-a). So, if the boat is facing along (2,1), the right-facing cannons fire towards (1,-2). The left-facing cannons fire in the opposite direction, so we flip both signs to get: (-1,2).

So you just need to calculate the direction vector and then do what they said. Now how exactly you should calculate the direction vector will depend on your specific implementation; since you haven't provided us any code I'm not sure what you are doing.

However I'll give an explanation based on one common implementation; you simply store the scalar speed of the moving object, and every frame calculate a movement vector based on that speed and the rotation. In that case the movement vector is calculated using simple trigonometry, something like:

```
x = cos(rot) * speed
y = sin(rot) * speed
movement = [x, y]

```

# Answer
> 0 votes
In 3D, I'd just take the cross product of the movement vector and the up vector.

---
Tags: flash, vector
---


# Question
Title: Where have the cross and dot products gone in DirectX10?
In D3D9 there were functions to deal with D3DXVECTOR3's in order to calculate dot and cross products. However these have disappeared from the math library in D3D10.

I assume they must have gone somewhere? My question is where and why?

# Answer
> 4 votes
The `D3DX10math.h` header still contains declarations for the dot and cross product of vectors. I think the documentation of the D3DXMath library on MSDN is incomplete.

The following example worked fine for me (Please excuse the absolute path for including the header):

```
#include "C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include\D3DX10math.h"

int main(int argc, char* argv[])
{
    D3DXVECTOR3 firstVector = D3DXVECTOR3(1.0f, 0.0f, 0.0f);
    D3DXVECTOR3 secondVector = D3DXVECTOR3(2.0f, 1.0f, 0.0f);

    float dot = D3DXVec3Dot(&firstVector, &secondVector);
    D3DXVECTOR3 cross;

    D3DXVec3Cross(&cross, &firstVector, &secondVector);

    return 0;
}

```

Please note that it is probably a good idea to use DirectX Math, because there is no D3DXMath library in DirectX 11 anymore (although you could still use the `D3DX10math.h`)

# Answer
> 1 votes
These are just simple functions that don't depend on a Direct3D device being available, so as long as the classes/structs being used are the same, you could in theory even go back to D3D8 versions of them (you could even use them in an OpenGL program if you were so inclined).

---
Tags: directx, directx10
---


# Question
Title: How can I determine the first visible tile in an isometric perspective?
I am trying to render the visible portion of a diamond-shaped isometric map. The "world" coordinate system is a 2D Cartesian system, with the coordinates increasing diagonally (in terms of the view coordinate system) along the axes. The "view" coordinates are simply mouse offsets relative to the upper left corner of the view.

My rendering algorithm works by drawing diagonal spans, starting from the upper right corner of the view and moving diagonally to the right and down, advancing to the next row when it reaches the right view edge. When the rendering loop reaches the lower left corner, it stops.

There are functions to convert a point from view coordinates to world coordinates and then to map coordinates.

Everything works when rendering from tile 0,0, but as the view scrolls around the rendering needs to start from a different tile. I can't figure out how to determine which tile is closest to the upper right corner.

At the moment I am simply converting the coordinates of the upper right corner to map coordinates. This works as long as the view origin (upper right corner) is inside the world, but when approaching the edges of the map the starting tile coordinate obviously become invalid.

I guess this boils down to asking "how can I find the intersection between the world X axis and the view X axis?"

# Answer
> 1 votes
> but when approaching the edges of the map the starting tile coordinate obviously become invalid.

Not really, you may not have data for the spot, but there should be nothing wrong with using the same formula.

If you want suggestions for how to overcome the potential problems you might want to show us the appropriate piece of code.

**Edit:**
Just to clarify, let's say you have got a 100x100 tiles map, indexed from 0 to 99. For rendering you'd do something like this:

```
//Loop structure that iterate through tiles
    if(tileX<=99 && tileX>=0 && tileY<=99 && tileY>=0){
        //Draw the tile
    }
    else{
        //Do nothing
    }
//End of loop

```

---
Tags: geometry, isometric
---


# Question
Title: Creating 3D Models for Game similar to Tron in Blender
How can I create 3D Model of objects with glowing edges (just like in Tron) using Blender ?

Note : I am a beginner in Blender

# Answer
Here's a video tutorial of someone doing tron-textures in Blender.

http://www.youtube.com/watch?v=ssMQCdjHWNI&feature=relmfu

The first 3 parts of the tutorial are the relevant parts (unwrapping a model and painting a texture on it), Part 4 starts going into Blender's node system, which you won't be using if you're using a different game engine.
> 1 votes

# Answer
Here is a good tutorial by Andrew Price to get you started.
> 1 votes

---
Tags: models, blender
---


# Question
Title: Does Unity for PC use Direct3D or OpenGL?
I am a mac developer using Unity and I hardly use a PC. When you build a Unity game for Windows, does it use Direct3D or OpenGL?

P.S. I'm not sure if it's called Direct3D or DirectX

# Answer
> 10 votes
Unity supports several renderers for its various platforms, Direct3D and OpenGL among them. You can find references to this fact in the release notes, for example, and in this documentation explaining some differences between renderer implementations that users should be aware of.

It appears that by default, Unity will use D3D on Windows. You can force it to use an OpenGL rendering path, apparently, via a command-line argument (although that thread is quite old). Configuring the rendering path in your game settings appears to be more about deferred versus forward renderers, and not the underlying API used.

# Answer
> 1 votes
As Josh said and if you also look under the Major Features in here, you will see that it uses both, I am not positive, but I believe it is so you can build your game in a variety of platforms.

---
Tags: unity
---


title: State of the art in image compression?

text:
# Question
Title: State of the art in image compression?
I'm looking for good algorithms for compressing textures offline (ie decompressing them at install or load time, I know about using DXT/3DC to save runtime video memory, but these create awful visual artifacts while often being larger in disk than a lossless format like JPEG-LS, even after using LZMA or something for entropy). Since the data will only need to be read by my program, I don't need a portable format like JPEG, which means I'm open to more experimental algorithms. To be clear, I'm concerned with reducing the download size of my game; I will be using them uncompressed on the video card.

I'm looking for formats that support different features... For example, 10 bits-per-channel color (HDR) for higher color fidelity under dynamic lighting conditions, normal map formats(16 bits in X and Y), alpha channels, etc, etc...

**NOTE:** My particular use case is for 2.5D backgrounds. In their uncompressed format, they are 10 bytes per pixel stored in 3 textures:

```
4 bytes - color  - D3DFMT_A2R10G10B10
4 bytes - normal - D3DFMT_G16R16F
2 bytes - depth  - D3DFMT_R16F

```

I store these in 1024x1024 tiles, and since every area has a different background, these can get really large really fast. However, I think knowing more about image codecs in general will help with finding an efficient method to compress these.

# Answer
> 6 votes
> I'm looking for good algorithms for compressing textures offline

What is your purpose in compressing these images? There are generally two reasons to compress a texture:

1. You want to make the texture smaller so that it takes up less memory on the GPU.
2. You want to make the texture smaller so that it takes less time to load/requires less harddrive space, resulting in a smaller download.

The most important thing you can understand is this: *you cannot satisfy both of these at once.* You must pick one: smaller GPU memory, or smaller disk space/load time.

So let's look at both cases.

## Case 1

Your possibilities here are the various "Block Compressed" types, using the D3D 10 language for them.

I'll assume you know what BC1-3 are, since they are formerly known as DXT1, DXT3, and DXT5, respectively. BC4 and BC5 are for 1 and 2-channel formats respectively. These two can be either unsigned or signed normalized.

BC5, 2-channel compressed, can be used for storing tangent-space normal maps, with the third coordinate (Z) reconstructed in your shader. It does a reasonably good job.

BC6H and BC7 are quite new. BC6H is a compressed, floating-point format. BC7 is a more accurate way to compressed RGBA color data. You can only get BC6H and BC7 support from DX11-class hardware.

The OpenGL internal formats for these are as follows:

1. BC1: `GL_COMPRESSED_RGB_S3TC_DXT1_EXT` and `GL_COMPRESSED_RGBA_S3TC_DXT1_EXT`
2. BC2: `GL_COMPRESSED_RGBA_S3TC_DXT3_EXT`
3. BC3: `GL_COMPRESSED_RGBA_S3TC_DXT5_EXT`
4. BC4: `GL_COMPRESSED_RED_RGTC1` and `GL_COMPRESSED_SIGNED_RED_RGTC1`
5. BC5: `GL_COMPRESSED_RG_RGTC2` and `GL_COMPRESSED_SIGNED_RG_RGTC2`
6. BC6H: `GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB` and `GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB`
7. BC7: `GL_COMPRESSED_RGBA_BPTC_UNORM_ARB`

The BC1-3 and BC7 formats can also be in the sRGB colorspace. OpenGL provides similar sRGB variants and GL\_COMPRESSED\_SRGB\_ALPHA\_BPTC\_UNORM\_ARB.

Obviously, none of these are lossless.

As I understand it, BC6H and BC7 are not widely supported in tools, though I seem to recall that NVIDIA's texture tools do support them.

## Case 2

If you're talking about normal 8-bit-per-channel images, you already know your options. But for more exotic texture types, like floating-point, 10-bit-per-channel, and normal maps, you're out of luck.

The simple fact is that most general image compression software is intended for regular old images. Most people who deal with floating-point textures don't really care enough about loading speed or disk space to bother with compressing them. They're big, but they've accepted that. And it's really hard to losslessly compress floating-point values.

So really, just stick with known paths for regular images, and use zlib or 7z or some other general compression method for the others. That's generally about the best you can do.

Do note that any lossless image compression technique can be made to work on any pixel data, so long as that data can fit. So you can always put a normal map in a PNG, even if it is a 2-component normal map (the third component is 0). It may not compress well, but it will probably beat out pure-zip.

---

> 4 bytes - color - D3DFMT\_A2R10G10B10

If you're storing a color, a normal, and a depth, then I can only assume that you are doing some form of deferred rendering-type thing here. That is, the color is the diffuse reflectance, not the light radiating from the background.

Given that, 10-bit colors are pretty much overkill. You don't need that level of color accuracy for a diffuse reflectance value; you can get the same level of accuracy from an sRGB color value. HDR is all about the lighting; you can do HDR just fine with lower color-depth.

Once you're dealing with regular sRGB colors, you can start using standard image compression techniques.

> 4 bytes - normal - D3DFMT\_G16R16F

There's no reason you can't take that down to G8B8 using signed-normalised values. Games do this all the time, and normals are not sensitive enough to need 16 bits worth of accuracy. And they're normals, so even using floating-point is way overkill.

Whether you can live with the artifacts produced by feeding it through BC5 compression is up to you. But you can at least go down from 32-bpp to 16-bpp with no detectable loss of fidelity.

Ultimately, everything is a tradeoff. You need to decide how much image quality you are willing to give up to get your game's data size under control. And since it's a tradeoff, you need to run actual tests to see where you are willing to draw that line.

# Answer
> 2 votes
There's WebP which Google have been suggesting as an improvement over JPEG.

For 2D images where compression artefacts are unacceptable, I'd go with some form of lossless compression like PNG.

Also note that DXT compressed images will usually shrink significantly when zlib or other lossless compression is applied to them.

For more exotic formats like HDR and 16-bit normals you could try OpenEXR. I've not used it myself though.

---
Tags: 2d, textures, sprites, image, compression
---