title: SFML networking rts

text:
# Question
Title: SFML networking rts
You will be controlling only one person directly in the game. But, you can issue vague command like to build something here or attack at this square.

So I'm trying to make a multi-player roguelike game. However, I have a bit of a problem understanding how to do sending and receiving data to the server.

Was wondering how would I use threads to do this?

I have two c++ project. One is for the server and one is for the client. I can create multiple client and connect it to server.

So do I just create threads on the server for each player to listen for client input. So I would wait for say 100ms for the input and then send it to update game, then repeat again?

I just want to know how to design it. I could probably work out how to do the detail myself. Just need the big picture.

So I was thinking that if I have say two threads for networking. One for listening to client input, one for sending updated stuff to the client. Although, maybe you need to do networking on one thread and you can't separate them like you can't have openGL on two threads.

# Answer
You mentioned it's a roguelike, will it be turn-based or real time ? Generally if you are going for a real-time game with timing critical elements, you should be placing the commands player make slightly to the future to compensate for the latency. This can be few hundred milliseconds at most.

Typically each client on the server has a thread. This thread handles reading the data and sending the response to the particular client. If you're planning on storing game logic on the server, then you'll need a common data storage with concurrency handling. Look into mutex/semaphore for more information on how to do this.

Another option is to have the server merely as a message conveying service. This means that you should encode your player movements into actions that will be sent, through the server, to the other players in the game. The games themselves are then responsible for maintaining a synced state.

Both of these approaches are valid and it really depends on how you want to do it. If you want to have a master process besides the server but on the clientside, you could set it so that the creator of the game has "additional privileges" such as spawning the monsters to a dungeon. Something a server would randomly do, but assuming you want to have a generic message delivery server and include all the game specific stuff on the side of the game.

As for receiving the data on the server side, depending on whether you're using UDP or TCP, you could simply have the thread listen to the socket all the time and attempt to read a packet (Åin the format you define) and react to it when it arrives.

A good thing to realize is that you generally don't have to sync up all the data, but only the stuff that has changed. If timing is not critical, you could simply be transmitting deltas (i.e. what has changed) all the time.

One thing to consider in a design like this is that sometimes someone is late due to network lag or something. If a command is missed, how will this be fixed. You should design your game so that a) the actions can be calculated from the past or b) implement a resync (i.e. send all objects across to all players; pause the game for a short while meanwhile).

And then there's the approach I first encountered in Unity was to divide the communication into delta updates and RPC calls. Big stuff like killing a monster, picking up an item, etc. will go through RPCs. However, stuff like exact player movement uses delta updates and movement prediction (the latter one means that the drawing thread can use the previous movement to interpolate to the direction it assumes the entity is moving to).

As for the communication itself, you could either use polling or simply listen to the server socket all the time for updates. In this case, you might want to utilize non-blocking IO in C++ (full duplex). Here's a thread from StackOverflow: https://stackoverflow.com/questions/4675824/how-to-implement-a-full-duplex-channel-over-tcp-with-a-single-thread)

I know a lot of this is vague but your question is a bit broad as well. I recommend you try to narrow your question down a bit by providing more detail in the future.
> 1 votes

# Answer
For the love of all that is right in the world, do not create one thread per client. Java perpetrated that disaster of a design by not giving you much of a choice in earlier versions but there's no reason to bring it into modern C++ code.

You want a form of *multiplexing*. You can listen to a collection of sockets and react when data is available in any of them. All on a single thread. You can send data on those sockets without needing another thread. Most AAA games put this into a *single* dedicated networking thread for latency reasons, but it works just as well on the main thread for most games.

The hard part you need to deal with is how you're actually going to architect the game. Note that many (most?) RTS games use a *lock step* form of networking, meaning the server sends out the next "frame" state to each client and waits for some kind of synchronization event before doing the next. This does mean that if a client starts to lag, all the clients will experience equivalent lag. Put a cap on how much lag you'll tolerate before considering a client de-synchronized (and either needing to resync the whole state or just disconnecting the client). There are of course many other ways of networking a game, though most the articles I can think of tend to be focused more on latency-sensitive shooters or large-scaled MMOs and may not necessarily be good advice for your project.

Note also that many articles are just really out of date. TCP for instance is a *perfectly* good choice for networking in a game like an RTS, especially with lock-step networking, and is even the protocol of choice for many smaller MMOs. Despite this, almost every article around on networking is about building a custom UDP protocol.

In short, do the absolute simplest thing possible until you have hard evidence that you need something more complicated.
> 4 votes

---
Tags: c++, networking, sfml
---


# Question
Title: how to make cross platform 3d games using modern opengl?
How to create games that run on windows, Linux, mac os x, android, ios, wp8 etc.... using c/c++, opengl 3 or 4 and opengl es 2.0. any tutorials or videos on how to create cross-platform 3d games.

# Answer
> 2 votes
There is plenty of good OpenGL tutorials, but unfortunately it is not that easy to find a good tutorial resource for OpenGL that is not outdated...

However, I recently found a pretty good website that offer 17+ tutorials about OpenGL 3.3+. You can find it at the following address: http://www.opengl-tutorial.org

As explained in the first lesson, all tutorials can be built on Windows, Linux and Mac.

So, even if it doesn't covers all your requests, I guess it's a rather good start.

---
Tags: c++, opengl, 3d, opengl-es, cross-platform
---


title: Plot 3D function with OpenGL

text:
# Question
Title: Plot 3D function with OpenGL
I need to build some sort of engine that can take a multivariable function such as

```
f(x,y) = cos(x) + y

```

and produce it's graph in 3D space.

Is there a recommended method of doing that?

# Answer
The basic idea is rather trivial. First you should start drawing a grid. Simplified, I'd just define a quad using four vertices. `x` would be `x`, `y` would be `y`:

```
(0, 0, 0)
(0, 1, 0)
(1, 1, 0)
(1, 0, 0)

```

But how to get `z`? You simply assume `z = f(x, y)`, so you'd get something like this:

```
(0, 0, f(0, 0))
(0, 1, f(0, 1))
(1, 1, f(1, 1))
(1, 0, f(1, 0))

```

Then just use these vertices to actually draw something in your 3D space.
> 1 votes

---
Tags: opengl
---


title: Developing GLSL Shaders?

text:
# Question
Title: Developing GLSL Shaders?
I want to create shaders but I need a tool to create and see the visual result before I put them into my game. As to determine if there is something wrong with my game or if it's something with the shader I created. I've looked at some like Render Monkey and OpenGL Shader Designer from what I recall of Render Monkey it had a way to define your own attributes (now as "in" for vertex shaders \>= 330) easily though I can't remember to what extent. Shader Designer requires a plugin that I didn't even bother to look at creating cause it's an external process and plugin. Are there any tools out there that support a scripting language and I could easily provide specific input such as `float movement = sin(elapsedTime());` and then define `in float movement;` in the vertex shader ?

It'd be cool if anyone could share how they develop shaders, if they just code away and then plug it into their game hoping to get the result they wanted.

# Answer
Since I get the idea that you have rolled your own custom game software, you might as well roll your own shader tool. If you show the GLSL compile errors you are halfway there.

To bring the experience up to something realistically usable, integrate inotify into your shader loader, and trigger your engine to re-compile shaders when a change happens on disk.

This will give you a truly What-You-See-Is-What-You-Get interface for developing GLSL code without wasting massive effort. You can then use any code editor and your own engine will provide live preview. (Works great with always-on-top or multi-monitor)

EDIT: For windows you can use FindFirstChangeNotification
> 5 votes

# Answer
I think it depends a little of what you are trying to achieve with your shader. But there are some online tools that can do the trick for simple shaders:

https://www.shadertoy.com

http://glsl.heroku.com (Click create new effect on the top-left corner)

http://codedstructure.net/projects/webgl\_shader\_lab/

Also, the galeries in these pages have a lot of shaders where you can read code and get inspired!
> 2 votes

---
Tags: opengl, glsl, tools
---


# Question
Title: How to avoid circular dependencies between Player and World?
I'm working on a 2D game where you can move up, down, left and right. I have essentially two game logic objects:

* **Player:** Has a position relative to the world
* **World:** Draws the map and the player

So far, *World* depends on *Player* (i.e. has a reference to it), needing its position to figure out where to draw the player character, and which portion of the map to draw.

Now I want to add collision detection to make it impossible for the player to move through walls.

The simplest way I can think of is to have the *Player* ask the *World* if the intended movement is possible. But that would introduce a circular dependency between *Player* and *World* (i.e. each holds a reference to the other), which seems worth avoiding. The only way I came up with is to have the *World* move the *Player*, but I find that somewhat unintuitive.

What is my best option? Or is avoiding a circular dependency not worth it?

# Answer
> 62 votes
The World should not draw itself; the Renderer should draw the World. The Player should not draw itself; the Renderer should draw the Player relative to the World.

The Player should ask the World about collision detection; or perhaps collisions should be handled by a separate class which would check collision detection not only against the static world but also against other actors.

I think the World should probably not be aware of the Player at all; it should be a low-level primitive not a god-object. The Player will probably need to invoke some World methods, perhaps indirectly (collision detection, or checking for interactive objects, etc).

# Answer
> 37 votes
Here is how a typical rendering engine handles these things:

There's a fundamental distinction between where an object is in space and how the object is drawn.

1. Drawing an object

You typically have a **Renderer** class that does this. It simply takes an object ( Model ) and draws in on the screen. It can have methods like drawSprite( Sprite ), drawLine(..), drawModel( Model ), whatever you feel like needing. It's a Renderer so it's supposed to do all these things. It also uses any API you have underneath so you can have for instance a renderer that uses OpenGL and one that uses DirectX. If you want to port your game to another platform, you simply write a new renderer and use that one. It's "that" easy.
2. Moving an object

Each object is attached to something we like to refer to as a **SceneNode**. You achieve this through composition. A SceneNode contains an object. That's it. What's a SceneNode? It's a simple class containg all the transformations ( position, rotation, scale ) of an object ( usually relative to another SceneNode ) together with the actual object.
3. Managing the objects

How are SceneNodes managed? Through a **SceneManager**. This class creates and keeps track of every SceneNode in your scene. You can ask it for a specific SceneNode ( usually identified by a string name like "Player" or "Table" ) or a list of all the nodes.
4. Drawing the world

This should be pretty obvious by now. Simply walk through every SceneNode in the scene and have the Renderer draw it in the right place. You can draw it in the right place by having the renderer store the transformations of an object before rendering it.
5. Collision Detection

This isn't always trivial. Usually you can query the scene about what object is at a certain point in space, or what objects will a ray intersect. This way you can create a ray from your player in the direction of the movement and ask the scene manager what's the first object that ray intersects. You can then choose to move the player to the new position, move him by a smaller amount ( to get him next to the colliding object ) or not move him at all. Make sure to have these queries handled by separate classes. They should ask the SceneManager for a list of SceneNodes, but it's another task to determine whether that SceneNode covers a point in space or intersects with a ray. Remember that the SceneManager only creates and stores nodes.

So, what is the player, and what is the world?

The Player could be a class containing a SceneNode, which in turn contains the model to be rendered. You move the player by changing the position of the scene node. The world is simply an instance of the SceneManager. It contains all the objects ( through SceneNodes ). You handle collision detection by making queries on the current state of the scene.

This is far from being a complete or accurate description of what happens inside most engines, but it should help you understand the fundamentals and why it's important to respect the OOP principles underlined by SOLID. Don't resign yourself to the idea that it's too hard to restructure your code or that it won't really help you. You will win a lot more in the future by carefully designing your code.

# Answer
> 16 votes
Why would you want to avoid that? Circular dependencies should be avoided if you want to make a reusable class. But the Player is no class that needs to be reusable at all. Would you ever want to use the Player without a world? Probably not.

Remember that classes are nothing more than collections of functionality. The question is just how one does divide the functionality. Do whatever you need to do. If you need a circular decadency, then so be it. (Same goes for any OOP features by the way. Code things in a way that it serves a purpose, don't just follow paradigms blindly.)

**Edit**
Okay, to answer the question: you can avoid that the Player needs to know the World for collision checks by using callbacks:

```
World::checkForCollisions()
{
  [...]
  foreach(entityA in entityList)
    foreach(entityB in entityList)
      if([... entityA and entityB have collided ...])
         entityA.onCollision(entityB);
}

Player::onCollision(other)
{
  [... react on the collision ...]
}

```

The kind of physics you have described in the question can be handled by the world if you expose the velocity of the entities:

```
World::calculatePhysics()
{
  foreach(entityA in entityList)
    foreach(entityB in entityList)
    {
      [... move entityA according to its velocity as far as possible ...]
      if([... entityA has collided with the world ...])
         entityA.onWorldCollision();
      [... calculate the movement of entityB in order to know if A has collided with B ...]
      if([... entityA and entityB have collided ...])
         entityA.onCollision(entityB);
    }
}

```

However note that you probably will need a dependency on the world sooner or later, that is whenever you need functionality of the World: you want to know where the nearest enemy is? You want to know how far the next ledge is away? Dependency it is.

# Answer
> 13 votes
Your current design seems to go against the first principle of SOLID design.

This first principle, called the "single responsibility principle", is generally a nice guideline to follow in order not to create monolithic, do-everything objects that will always hurt your design.

To concretize, your `World` object is responsible both for updating and holding the game state, and for drawing everything.

What if your rendering code changes / has to change? Why should you have to update both of classes that actually don't have anything to do with rendering? As Liosan has already said, you should have a `Renderer`.

---

Now, to answer your actual question...

There are many ways of doing this, and this is only one way of decoupling:

1. The world doesn't know what a player is.
    * It does have a list of `Object`s in which the player is located, however, but it does not depend on the player class (use inheritance to achieve this).
2. The player is updated by some `InputManager`.
3. The world handles movement and collision detection, applying proper physical changes and sending updates to objects.
    * For example, if object A and object B collide, the world will inform them and then they could handle it by themselves.
    * The world would still handle physics (if your design is like that).
    * Then, both objects could see whether the collision interests them or not. E.g., if object A was the player, and object B was a spike, then the player could apply damage to itself.
    * This can be solved in other ways, though.
4. The `Renderer` draws all the objects.

# Answer
> 1 votes
The Player should ask the World about stuff like collision detection. The way to avoid the circular dependency is not to have the World have a dependency on Player. The World needs to know where it's drawing itself: you probably want that abstracted further away, perhaps with a reference to a Camera object which can in turn hold a reference to some Entity to track.

What you want to avoid in terms of circular references is not so much holding references to each other, but rather referring to each other explicitly in code.

# Answer
> 1 votes
Whenever two different types of objects can ask each other. They will depend on each other as they need to hold a reference to the other one to call its methods.

You can avoid circular dependency by having the World ask the Player, but Player cannot ask the World, or vice versa. In this way the World has references to the Players but players don't need reference to World. Or vice versa. But this won't solve the problem, because the World would need to ask the players whether they have something to ask, and tell them in the next call...

So you cannot really work around this "problem" and I think there is no need to worry about that. Keep the design stupid simple as long as you can.

# Answer
> 0 votes
Stripping out the details about player and world, you have a simple case of not wanting to introduce a circular dependency between two objects (which depending on your language may not even matter, see the link in Fuhrmanator's comment ). There are at least two very simple structural solutions that would apply to this and similar problems:

1) **Introduce the singleton pattern into your world class**. This will allow the player (and every other object) to easily find the world object without expensive searches or permanently held links. The gist of this pattern is just that the class has a static reference to the only instance of that class, which is set upon the object's instantiation and cleared upon it's deletion.

Depending on your development language and the complexity you want you could easily implement this as a superclass or interface and reuse it for many major classes you don't expect to have more than one of in your project.

2) **If the language you're developing in supports it (many do), use a Weak Reference.** This is a reference that does not affect things like garbage collection. It is usefull in exactly these cases, just be sure to not make any assumptions about whether the object you're weak referencing still exists.

In your particular case, your Player(s) could hold a weak reference to the world. The benefit of this (as with the singleton) is that you don't need to go searching for the world object somehow each frame, or have a permanent reference that will hamper processes affected by circular references such as garbage collection.

# Answer
> 0 votes
As the others have said, I think your `World` is doing one thing too many: it is trying to *both* contain the game `Map` (which should be a distinct entity) *and* be a `Renderer` at the same time.

So create a *new* object (called `GameMap`, possibly), and store the map level data in it. Write functions in it that interact with the current map.

Then you *also* need a `Renderer` object. You *could* make this `Renderer` object the thing that both *contains* `GameMap` and `Player` (as well as `Enemies`), and also draws them.

# Answer
> -6 votes
You can avoid circular dependencies by not adding the variables as members. Use a static CurrentWorld() function for the player or something like that. Do not invent an interface different from the one implemented in World already though, this is completely unnecessary.

It is also possible to destroy the reference before/while destroying the player object to effectively stop the problems caused by circular references.

---
Tags: collision-detection, architecture, objects
---


# Question
Title: How do you manage your game resources in XNA?
In the past I have used `Content.Load<type>("filename");` all over the place. This quickly becomes a nightmare to manage and worse you start having multiple copies of the same asset loaded in several different places.

Then I moved on to using a Resources class which basically looked like the following:

```
public class Resources
{
    public static Texture2D particle01;
    ...
    public static Texture2D particle93;

    public static Effect shader01;
    ...
    public static Effect shader32;

    public static Load(ContentManager content, GraphicsDevice device)
    { //load all the resources }

    public static Unload()
    { //unload all the resources }
}

```

Then I could simply use `Resources.particle01` to get a reference to the resource from anywhere within the same namespace.

This was a nice approach because it eliminated the duplicates that I had in the past. Also all loading was done in a single class, so it was easy to keep track of the resources. And finally, I could simply right click, for example, `particle93` and click find all references to find all the places that used that texture.

However, there are issues with this approach and I would like to know if there is a better solution out there.

# Answer
> 8 votes
Well for starters XNA's content manager doesn't load the same asset twice, it will just return a reference if something was already loaded.

As for your resource approach, I don't know if it's really the way to go since you basically hard code your content assets into your game.

A possible solution to your problem would be the factory pattern. Say you would like to load a level, stored as XML. You load the XML file and load the level by doing LevelFactory.Construct(xml); This factory inspects the XML file and loads all the assets associated with that level and puts them into the world. Sub-parts of the world like NPCs could be constructed by the level factory by calling the NPC factory and passing part of the XML file so that the NPC factory knows to load what textures and models.

Using this approach you get a 'cascading series' of factories that are all data driven so you can have a clear separation between content (the XML file and the files referenced by the XML file) and code (the factories). While still keeping the content loading code away from the other code. You now don't have todo Player = new Player(textureA, textureB, textureC); anymore, you can just ask the factory for a new player and it will figure out the rest.

Tip: you can always have a few methods for default objects or have a fallback when nothing is specified in the XML.

Hope this helps!

# Answer
> 3 votes
I used FlatRedBall, which has an amazing concept of Screens. Instead of worrying about loading/unloading textures, you instead write code like:

```
Sprite s = this.addSprite("spaceship");

```

And it will handle the content life-cycle for you. I also use this approach in my own framework, Radiant Wrench. I find that it keeps management to a minimal and just gets out of your way.

The code for managing sprites is not that trivial (you need a sprite class and screen class, for starters), so I would suggest give FRB or RW a try. You will always benefit from learning new ways to do things (sometimes better ways).

# Answer
> 2 votes
This might seem unfavorable to some but I tend to keep my resources local to the GameState that needs them, and each GameState has a ResourcePool of sorts. This is a nice way to keep level assets separate since I don't really need menu backgrounds Your Resources class would be better served as a structure, and the GameState will be responsible for Load and Unload.

Some of resource management in XNA is partly determined by how you import your content in the first place. Many people bind textures and effects to their models in the content processing phase of the build- leaving them to only manage meshes and the rest is already referenced within.

You seem to take the more classic "mix and combine" approach for more flexibility, so you need an approach that black-boxes the underlying work and cut the code you have to write in the long run. I haven't used FlatRedBall, but from what I can tell from the short description written here, it sounds like the Lazy Loading pattern. This is a concept worth looking into if you want to make your life easier with managing many resources.

# Answer
> 1 votes
I use a public static class called Assets. It contains dictionaries of each kind of asset, model, effect, spritefonts,etc, it has a load function where it looks in the content folder for folders such as "Textures", "Models", etc, and loads all the assets. Then when I want to call an Asset I just use something like Assets.Textures\["SpriteSheetX"\];

I don't know if this is bad practice but it's very easy. I mostly just pass around strings of the file name and deep down in the core it will load the asset from Assets.

---
Tags: xna, xna-4.0, assets, resource-management
---


title: Word Search Game Issue

text:
# Question
Title: Word Search Game Issue
I am developing a game like word search. I have used AndEngine for this and for displayig grid of words I have used TiledMap. In this game, we need to join letters to make a word as we drag our fingure it will draw line on tiles and make connection between letters. I am able to draw lines vertically and horizontally accurately but as I try to draw line diagonally it goes to the nearby tile and draw line from last touched tile to nearby tile. But as I carefully move to the diagonal tiles it draws line accurately.

Can any one help me to solve this issue?

```
e.g.
----------------
|1   2   3   4 |
|5   6   7   8 |
|9  10  11  12 |
----------------

```

as shown in above e.g.

I am able to draw line for `"1234" & "159"`, It means all horizontal and vertical positions works accurately. But for `"963"` its not as accurate as i draw for horizontal and vertical.

I want to draw line on one board as shown above. There will be letters below lines and need to connect correct words.

# Answer
Rather than detecting each tile as the touch position passes over it, you could contiually detect the direction a touch has moved from its own starting point, and lock that direction to the 8 horizontal/vertical/diagonal directions (like this question's topic).

I'll reference your artwork :)

```
----------------
|1   2   3   4 |
|5   6   7   8 |
|9  10  11  12 |
----------------

```

For example, the first touch is at the center of `10`. Assuming an origin at the top-left, that position is `(1.50, 2.50)`. Now that touch moves toward tile `7`, and it gets a vector position of `(2.01, 2.01)`. Purely from the current touch location, that is within tile `11`. However, the difference of these two vector positions is

```
 (2.01,  2.01)
-(1.50,  2.50)
-------------
 (0.51, -0.49)

```

Clearly, this is a diagonal vector that is closest to the direction `(1, -1)`. Knowing that and the drag distance, your logic can behave as if the touch was firmly within tile `7`.

This method will allow you to build a finite state machine for the drag direction. You will also be able to correct for fat-fingers being unable to drag a straight line, with accuracy improving as the drag moves farther from the origin.
> 1 votes

# Answer
Try drawing your diagonal lines using a Paint object that has ANTI\_ALIAS\_FLAG set to true.
You can do this when calling the constructor or by calling the "setAntiAlias" method of an existing Paint object.
> -1 votes

---
Tags: android, andengine, tilemap
---


# Question
Title: SDL gray scale image from a a color image?
I am new to sdl. I have basically have the following codes which can load the images. I know how to access the pixel as below. What I need it to convert the image to 8 bit grey level and 1 bit monochrome separately. I know it got to do with pixel manipulation. Any hint or idea how to to this? I am not too sure what to set for SDL\_CreateRGBSurface and also once I get the pixel what manipulation to be done?

# Answer
> 1 votes
Essentially you're just looking for a conversion function, i.e. breaking down a three component color into a one component color. This can be done different ways, probably easiest one being a simple average function:

```
gray(r, g, b) = (r + g + b) / 3

```

In C/C++ this could be done the following way (assuming you've got 24/32 bit colors with alpha being unused/occupying the most significant byte; one byte per color; i.e. RGB888 or RGBA8888):

```
int source_color = SDL_GetPixel(...); // some color

const unsigned int component1 = source_color & 0xff; // red or blue
const unsigned int component2 = (source_color >> 8) & 0xff; // green
const unsigned int component3 = (source_color >> 16) & 0xff; // blue or red

// calculating the average component/color (i.e. grayscale)
const unsigned int gray = (component1 + component2 + component3) / 3;

// back to SDL's RGB color (optional)
const int gray_rgb = 0xff000000 | (gray << 16) | (gray << 8) | gray;

// There are multiple ways to get the monochrom image, based on the format you'd like (e.g. just a boolean value or just a RGB value).

// First version (actually not recommended, but might save you code e.g. having one fixed conversion function):

    // calculating the monochromatic color with a given threshold (127)
    const unsigned int mono = gray > 127 ? 255 : 0;

    // once again back to SDL's RGB model (optional)
    const int mono_rgb = 0xff000000 | (mono << 16) | (mono << 8) | mono;

// Second version:

    // just return the final color in one step
    // this returns pure white or pure black
    const int mono_rgb = gray > 127 ? 0xffffffff : 0xff000000;

```

Note that there are similar approaches using different weightings applied to the color components. Also you can try different thresholds for the monochrome conversion to lighten/darken the image.

As for the actual SDL Surface, that's up to you. I'd just stick with `SDL_PIXELFORMAT_RGB888` or `SDL_PIXELFORMAT_RGBA8888` to avoid further conversions, unless it understands grayscale images now (which I don't think?).

---

Further explanation on the conversions:

If you're storing a color in an integer value, you'll usually use one byte per color. In hex notation this will mean that you've got two digits per color, essentially translating to something like `AABBGGRR`, where `AA` are the byte for alpha, `BB` the byte for blue, etc. If you're familiar with the hexadecimal notation of colors in HTML/CSS (like `#ff0000` for red), then this should sound familiar to you.

If you'd like to store a grayscale value `x` in (A)RGB notation, you'd end up setting all three color components (red, green, and blue) to the same value (of `x`). This happens in this line:

```
const int gray_rgb = 0xff000000 | (gray << 16) | (gray << 8) | gray;

```
* The logical or (`|`) essentially adds the various components.
* `0xff000000` represents full opacity (alpha = 255).
* `gray << 16` moves the value of `gray` to the correct position for red or blue (depends on pixel format). This is known as a left shift, e.g. `0x00000012 << 8` will result in `0x00001200` (values moved to the left by 8 bits).
* `gray << 8` moves the value of `gray` to the correct position for green.
* `gray` finally stays as is, which will be the value for blue or red (again depending on the pixel format).

Finally, `const unsigned int mono = gray > 127 ? 255 : 0;` will set the monochrome color (which is actually grayscale again, 256 different values!) based on the grayscale value. `255` represents white, `0` represents black.

---
Tags: sdl, c
---


# Question
Title: After a succesful glLinkProgram, should I delete / detach my shaders?
After I have a linked program, and thinking about defensive programming, should I delete and detach the shaders used to link this program?

If yes, is that going to free any resources? Or do these shader objects only going to be freed after a glDeleteProgram call?

edit: Just for clarification what I am doing is (which is consistent with the answer):

> glCreateShader -\> glShaderSource -\> glCompileShader -\> glCreateProgram -\> glAttachShader -\> glLinkProgram -\> glDetachShader -\> glDeleteShader -\> draw using this shader program -\> and when I don't need this shader anymore glDeleteProgram

# Answer
Yes, you should always do this. I didn't find out about this until just recently, but a shader won't actually be deleted by `glDeleteShader` until it's been detached. It's mentioned on the man page for `glDetachShader`

**EDIT**: Almost missed the bit about deleting the shaders too. Yes, you should do this as it frees up the memory used to store the shader source and unlinked object code. This is explained in more detail in this StackOverflow question.
> 52 votes

# Answer
The order is right, but you do not really need to deattach the shaders, because calling glDeleteProgram does that for you with all attached shaders and then they are automaticaly deleted (if they were flagged for deletion with glDeleteShader func) .

Reference: http://www.opengl.org/sdk/docs/man/xhtml/glDeleteProgram.xml .
> 2 votes

---
Tags: opengl, shaders
---


title: Spritesheet vs single tiles

text:
# Question
Title: Spritesheet vs single tiles
I am currently programming a 2d platformer and this is the first time I am coding a video game. Now I've downloaded the 'platformer art deluxe' package. In the tiles folder there are single tiles and a spritesheet with every tile on it.
Should I use the spritesheet or the single tile sprites?

# Answer
If you should use them or not is up to you. You can learn more about why people use sprite sheets, and decide if it's worth implementing for your game. The logic is not too difficult too difficult for fixed grid sprite sheets. It's just a matter of calculating the offsets and sizes for each texture and converting those into UV coordinates:

```
//create UV arrays for each texture in the sheet, store look up by index
public TextureSheet(int width, int height) {
    for(int i = 0; i < width * height; i++) {
        textureMap.put(i, calculateUVMapping(i, width, height));
    }
}

private Vector2f[] calculateUVMapping(int texture, int sheetWidth, int sheetHeight) {
    int textureIndex = texture;
    int u = textureIndex % sheetWidth;
    int v = textureIndex / sheetHeight;

    float xOffset = 1f / sheetWidth;
    float yOffset = 1f / sheetHeight;
    float uOffset = (u * xOffset);
    float vOffset = (v * yOffset);

    Vector2f[] UVList = new Vector2f[6];

            //create the coordinates required for making a quad with the texture
    UVList[0] = new Vector2f(uOffset, vOffset); // 0,0
    UVList[1] = new Vector2f(uOffset, vOffset + yOffset); // 0,1
    UVList[2] = new Vector2f(uOffset + xOffset, vOffset); // 1,0
    UVList[3] = new Vector2f(uOffset + xOffset, vOffset + yOffset); // 1,1
    UVList[4] = new Vector2f(uOffset, vOffset + yOffset); // 0,1
    UVList[5] = new Vector2f(uOffset + xOffset, vOffset); // 1,0

    return UVList;
}

public Vector2f[] getTextureMap(int textureIndex) {
    return textureMap.get(textureIndex);
}

```
> 1 votes

# Answer
If its a small project then it shouldn't matter.

Binding a texture is expensive. So spritesheets can be bound once, and then instead of drawing the entire sprite, you draw just a section of the sheet. This is can be an performance increase, but really not the big of a deal on smaller projects. Also sprite sheets have a certain amount of optimization that can be placed into them (such as dithering, colors, compression, etc).

This tutorial is about spritesheets in CC2D, but has some good points about using spritesheets in general:

http://www.raywenderlich.com/32049/texture-packer-tutorial-how-to-create-and-optimize-sprite-sheets-in-cocos2d

But unless you are using a library or this is a serious game, writing your own spritesheet functionality is going to be a pain.
> 0 votes

---
Tags: 2d, sprites, tiles, platformer, spritesheet
---


# Question
Title: How to secure Pacman game for making it fool-proof enough to keep hackers away?
We have made an online game very similar to Pacman. The idea is to award top scorers with various incentives and prizes. But at the end of the day, we need to keep hackers at bay so that our game app is secured and let the genuine top scorers to enjoy playing it for prizes and incentives.

What we want to prevent from happening is not to allow hackers to find out or detect how to win this maze-based game (similar to Pacman) for incentives and prizes. By securing I meant is to secure the Algorithm of the game, making it tougher enough for the hacker to prevent from finding out ways to win it every time.

So how can we keep the malicious hackers away?

Looking for credible, tried and tested information. Thanks

# Answer
As a first step to securing the game you can't allow any user to run the actual game logic on their computer. If they can do that then they can also reverse engineer it and hack it easily.

What you need to do is have a secure server under your control which runs all the game logic. The client program on the users computer simply sends moves to the server and retrieves results. Note that the server needs to verify that any command from the client is a valid command, and reject it if it's not.

That still leaves some possibilities for cheating, but without that it definitely won't be secure.

Unless you have experience in writing online games which give out prizes, you might want to get someone who is to do it for you. For example online casinos require the same kinds of security to prevent people cheating.
> 3 votes

---
Tags: security, hacks
---


# Question
Title: Multiple render targets and gamma correctness in Direct3D9
Let's say in a deferred renderer when building your G-Buffer you're going to render texture color, normals, depth and whatever else to your multiple render targets at once.

Now if you want to have a gamma-correct rendering pipeline and you use regular sRGB textures as well as rendertargets, you'll need to apply some conversions along the way, because your filtering, sampling and calculations should happen in linear space, not sRGB space. Of course, you could store linear color in your textures and rendertargets, but this might very well introduce bad precision and banding issues.

**Reading** from sRGB textures is easy: just set *SRGBTexture = true;* in your texture sampler in your HLSL effect code and the hardware does the conversion sRGB-\>linear for you.

**Writing** to an sRGB rendertarget is theoretically easy, too: just set *SRGBWriteEnable = true;* in your effect pass in HLSL and your linear colors will be converted to sRGB space automatically.

**But how does this work with multiple rendertargets?** I only want to do these corrections to the color textures and rendertarget, not to the normals, depth, specularity or whatever else I'll be rendering to my G-Buffer. Ok, so I just don't apply *SRGBTexture = true;* to my non-color textures, but when using *SRGBWriteEnable = true;* I'll do a gamma correction to all the values I write out to my rendertargets, no matter what I actually store there.

I found some info on gamma over at Microsoft: http://msdn.microsoft.com/en-us/library/windows/desktop/bb173460%28v=vs.85%29.aspx

> For hardware that supports Multiple Render Targets (Direct3D 9) or Multiple-element Textures (Direct3D 9), only the first render target or element is written.

If I understand correctly, *SRGBWriteEnable* should only be applied to the first rendertarget, but according to my tests it doesn't and is used for all rendertargets instead.

Now the only alternative seems to be to handle these corrections manually in my shader and only correct the actual color output, but I'm not totally sure, that this'll not have any negative impact on color correctness. E.g. if the GPU does any blending or filtering or multisampling after the *Linear-\>sRGB* conversion...

**Do I even need gamma correction in this case, if I'm just writing texture color without lighting to my rendertarget?** As far as I know, I DO need it because of the texture filtering and mip sampling happening in sRGB space instead, if I don't correct for it.

Anyway, it'd be interesting to hear other people's solutions or thoughts about this.

# Answer
> 1 votes
Sounds like a driver bug. A simple way around this is to write your diffuse and/or specular colors out in linear values. To maintain proper color resolution (the sRGB-to-linear conversion happens in floats, but storing linear values in 8-bit ints loses some precision), you should use 10-bit RGB images. Obviously this will not work if you need a real alpha component, but maybe you can hide that within your normal or something.

# Answer
> 0 votes
Can we see your tests? This is really aesthetic anyway - if you find you need to brighten/gamma correct the texture color, then do it, this is only an issue if your texture is stored in sRGB format,

Code for converting from sRGB is in GPU Gems 3

```
float3 diffuseCol = pow( f3tex2D( diffTex, texCoord ), 2.2 );
//Or (cheaper, but assuming gamma of 2.0 rather than 2.2)
float3 diffuseCol = f3tex2D( diffTex, texCoord );
fuseCol = diffuseCol * diffuseCol;

```

# Answer
> 0 votes
I can see a few possible solutions to this problem:

1. Leave the MRTs linear, and do the conversion later on in the rendering pipeline. The lights and alpha blended objects probably want blending in linear space anyway.
2. Turn off the render state, and do the conversion in the shader with `result = pow(result, 1.0/2.2);` (or more cheaply with sqrt() which is 2.0 and not 2.2).
3. Switch to D3D11. That lets you specify in the texture format if you want SRGB conversion to happen or not. For example there's DXGI\_FORMAT\_R8G8B8A8\_UNORM\_SRGB.
4. See if there's up to date drivers that do the right thing. However you're not the only one that's had trouble with that render state.

---
Tags: directx, shaders, rendering, deferred-rendering
---


# Question
Title: Does opengl performs Visibilty algorithms based on z-index?
Does OpenGL performs Visibilty algorithms based on z-index? Or we have to write our own algorithms. Mainly I'm referring to z-buffer algorithm. Is it in-built?

# Answer
Yes, OpenGL (or really, the GPU hardware that OpenGL is used to access) has built-in support for depth testing via z-buffers. To enable it, you just have to ensure your OpenGL context includes a depth buffer when it's created (the details of this depend on what OS or toolkit you're using). Then, insert these calls in your render function prior to drawing any geometry:

```
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearDepth(1.0f);

```

and add `GL_DEPTH_BUFFER_BIT` to your `glClear` call. That should be all you need to do to enable z-buffering. For more information, see this tutorial.
> 6 votes

---
Tags: opengl
---


# Question
Title: Programmatically set brightness of a PointLight
I'm a beginner, so there is definitely something I'm missing here. I'm trying to set brightness of my PointLight object from the in-game command line.

Here is what I tried, but it doesn't work:

```
class MyCustomGameInfo extends GameInfo;

exec function myTest(float brightness)
{
    local PointLight pointLightOut;
    local PointLight pointLight;

    foreach AllActors( class 'PointLight', pointLightOut )
    {
        pointLight = pointLightOut;
    }

    pointLight.LightComponent.SetLightProperties(brightness);
    pointLight.LightComponent.UpdateColorAndBrightness();
}

defaultproperties
{
}

```

So when I compile it, go to my UDK project, run it, press tab and start typing myTest, the command line autocomlpete works perfectly, and even shows the float parameter. However, it doesn't work. I have a feeling that the way I'm retrieving the object is wrong.

# Answer
> 2 votes
Are you using a dynamic light? If the light is completely static, I *think* all of the lighting information is going to be baked into the map, so it won't be modifiable at runtime.

Also, you can try logging out the value of `pointLight` to make sure it's both valid, and the correct light actor.

---
Tags: lighting, udk
---


# Question
Title: How can I refactor "attack cooldown" into "attack speed"?
I'm building a game where the player's character can attack bad guys and vice versa. I built this with the concept of an "attack cooldown" because I don't want units to be able to attack each other every single frame. I want there to be some delay between attacks. Here's roughly how it works:

```
if unit.ticksUntilAttack <= 0
  unit.attack(target)
  unit.ticksUntilAttack = unit.attackCooldown
unit.ticksUntilAttack = unit.ticksUntilAttack - 1

```

I also have a page where I show the character's stats and list this as "Attack Cooldown". I was showing my friend and he said, "Why don't you rename that to 'Attack Speed'"? I explained that it's not really the speed at which you attack because "smaller is better". We both agreed that "attack speed" is a more standard way to show this concept and that I should change things the way he suggests.

The problem for me is that "attack cooldown" is a much more intuitive way for me to program the solution. I'm wondering if there's some "trick" to refactoring the current code I've got. I'm thinking something like this:

```
if unit.attackSpeedAccumulator >= SUM_NEEDED_TO_ATTACK //a constant that's the same for every unit
  unit.attack(target)
  unit.attackSpeedAccumulator = 0
unit.attackSpeedAccumulator = unit.attackSpeedAccumulator + unit.attackSpeed

```

Is there a smarter way to do this?

# Answer
You could express it in terms of "attacks per second" or "attack rate". If the per-second numbers are too small to be convenient for the player to compare, you could just scale them by an arbitrary constant - e.g. 0.5 attacks per second (1 attack per 2 seconds) could be multiplied by 10 or 100 and displayed as "5" or "50". The way you'd code it would be something like

```
attackAccumulator += attackRate * frameTime;
if (attackAccumulator >= 1.0)
    // allow attack

```

Or you could keep your current code, and just calculate attacks-per-second as 1 / the cooldown time in seconds.

On the other hand, I think the concept of a cooldown time or charge-up time is pretty common and players will understand it. Many games have that type of mechanic. As long as you display the number as a time value (e.g. "5 seconds" instead of just "5"), I think it would be fine.
> 13 votes

---
Tags: game-design, ui-design, refactoring
---


# Question
Title: how to set up a contract between a Client and Server in C#
I am trying to make a turn based game, so first should I use UDP or TCP for the client server set up and why?

Second how do I implement it? I have seen a lot of code that just sends byte strings to each other but that is not sufficient enough to make a game... I have heard of Remote Method Invocation, and I haven't found a good explanation of it or a good implementation of it, so if you could show some of that as well.

Lastly, on MSDN there was the WCF (the tutorial on MSDN does not work on my computer at least) so it does not help me understand what it does

So how should I try and set up my server? and how to I call methods from the Client, and from the server? and how to I make the client or server respond to each other?

Thanks for any response that may help!

# Answer
> 4 votes
**A turn-based game should use TCP.**

TCP guarantees that you receive all packets in the order they were sent. You can basically treat it like a file stream.

UDP gives no such guarantees - you could receive a packet out-of-order, duplicated, or not at all. A UDP connection will give you lower latency (it doesn't have to wait for late packets or re-sends), but you don't need that in a turn-based game, and the logic to handle those scenarios is non-trivial (not worth the effort).

---

Personally I would probably implement this using `TcpListener` and `TcpClient`. I'd use `BinaryReader` and `BinaryWriter` to send and receive data on the resulting `NetworkStream`.

I'd implement "Remote Procedure Call" (or RPC, a more general term for "Remote Method Invocation") with something extremely simple, like this:

```
if(reader.ReadInt32() == NetworkMessage.PlayEffect)
{
    PlayEffect(reader.ReadString(), reader.ReadInt32(), reader.ReadInt32());
}

```

---

Using WCF is an option. But before you do, consider if you actually need any of the features it provides. It is basically a framework for writing "services" that produce and consume messages, usually over a network.

One of the key features of WCF is that it allows for very loose coupling between client and server - allowing many different clients and servers to interoperate. You generally don't need this for a game, which generally just has one client application and one server.

When in doubt, do the simplest thing that could possibly work - you can always switch to something else later - and that is made much easier if you haven't attached yourself to a bulky framework.

---
Tags: c#, client-server
---


# Question
Title: Should I code game logic separately from game engine scripts
I'm developing a game in Unity3d, economic strategy. I wonder if I should code logic inside unity scripts, or write it as an external module/library?

By game logic I mean game model, which describe game entities, they relation with each other, their methods. And this logic has nothing to do with and doesn't need to know anything about networking, rendering, representation etc.

If I do it inside unity scripts, then logic is tied to unity engine and I don't see a way to implement multiplayer(client-server) without rewriting whole logic for server-side, where unity cannot be used.

I would like to define logic outside of scripts, and later, reference it inside some "main" unity script. This way I could implement multiplayer easily.

Is this a common practice, or should I avoid it, or maybe there is some alternative patterns?

# Answer
> 7 votes
There are definitely some advantages in developing your game logic in an agnostic (non-Unity) environment.

Pros

* It forces you to think about game design more purely. I find it is much easier to think about game design, whether on a board or on a computer screen, if I don't also have to think about writing or using an engine.
* It is easier to write and run tests, though I hear there are testing frameworks for Unity.
* It is easier to simulate your game at faster than real-time. Balance and mechanics in "economic strategy" games are comparatively more chaotic than in other games: the effects of adjusting Ability X are often less localizable and less generalizable than in first-person shooters for instance. Therefore balancing this type of game is a much more time-consuming process. When writing AI or tuning numbers, being able to simulate many games (outcomes) generatively, automatically, at faster-than-real-time, and to finally output statistics, can be incredible useful.
* MonoDevelop for Unity is only *ok*. If you write your game logic in a pure .NET library, you can use Visual Studio which has a more mature debugging environment.
* And as you alluded to, to validate game moves on a server you probably want all or some of your game logic to be running in an environment not dependent on Unity.

Cons

* If your game model depends on physics, or any other capability already offered by Unity, you must recreate it or use some other library that you can link against or build.
* In general you might find yourself rewriting certain basic constructs in your own library, and writing wrappers or converters to go to-and-from yours and Unity's.

# Answer
> 0 votes
You can define your game logic in C#. There are a number of ways of moving C# to server side.

Alternatively, if you wish to use a different cross-platform scripting language for game logic, there's always LUA (and again, because you're using C#, a brief google search will yield a number of ways you can integrate LUA with Unity).

As previous answers have noted, it depends on the complexity of your game. In my view, C# is (these days) sufficiently cross-platform as long as you avoid the Unity API.

---
Tags: unity, game-mechanics, logic
---


# Question
Title: Get polygons points from an array of 0 and 1
I have an 2D array containing `1` for walls or `0` for empty cells.

I can draw my maze by iterating through the map, placing a wall when `map[x][y]` is equal to `1` but I want to get the points of the different polygon formed by the `1` in order to have minimum draw call.

But I'm not sure about the Maths and I don't know how to proceed.

Would you please give me some hint ?

# Answer
A simple to understand, but probably not optimal method is the following:

* Step through all elements of the array, starting at the top left.
* At each step, examine the current element and 3 of its neighbors: the one to its right, the one to its bottom, and the on to its bottom right.
* Check how many of the 4 elements have the value 1. If exactly 4 or 0, you don't have a point there. If 1 or 3, you have a point. If 2, and these two are in the same row OR in the same column, you don't have a point.

Some illustration:

Black means a wall, white means empty space. A,B,C and D are the elements of your array, e.g. \[i,j\], \[i+1,j\], \[i,j+1\] and \[i+1,j+1\]. The red dot shows where a polygon point must be created.

So go through the whole array, collect the points in a list (there will be many duplicate points, just don't add them or remove them later). Pay extra attention to the area near the boundaries of the array!
> 1 votes

---
Tags: maze
---


# Question
Title: How to define axis of Sprites in a CCAnimation?
I'm struggling to find how to define a kind of axis in my frames, when my sprite punches it moves back. I want to define the head as a pivot for the other sprites with different sizes.

How can I accomplish that?

# Answer
> 1 votes
I have not come across a way to define the type of axis that you're talking about, however I can offer a method that I've used to overcome this issue.

The best method, and most easily explained to the artists on the project, is to make all the sprite frames for all animations for a particular character the exact same sizes.

For example, if your character walks and punches, of course the walking sprites will usually be narrower than your punching animation. If you crop your sprites without leaving any empty spaces, your character will appear to pop around since the anchor point for a sprite is usually it's center, and the center of a walking animation and a punching animation are different.

If you keep the sprite frames of all animations for the same character the same sizes and position the head in the same spot within the sprite frame each time (don't worry about the empty spaces within the PNG, since TexturePacker will strip those out for you) when the sprite is animated, the sprite will not shake around, of course, the bounding box for the character will be affected since your sprite's size will always be as large as your largest animation frame. This may or may not impact your collision detection code, so adjust accordingly.

# Answer
> 0 votes
What Jamornh suggests is a good solution, but might be problematic if you already have most of the content finished. What I do in my game engine, is that I have a property `Vector2 Sprite.CenterPoint` in my `Sprite` class. This stores the location of the sprites rotation center, relative to the upper left corner of the sprite. A similar property could store the coordinates of the center of your character's head, or center-of-gravity. When switching between the character's sprites (during an animation, for example), you can translate the sprite by taking this point into consideration.

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


# Question
Title: How do other 2d tile-based web games record their overworld data?
I'm developing a 2d (top down) tile-based strategy game that is web based. It uses PHP and a MYSQL database along with jquery. It was originally a mostly text-based game. I have since developed what I consider to be a primitive engine which handles multi-player turn processing and things like player movement are now automated.

I'm wondering how other 2d tile-based, turn-based games that are web-based, and even non-web-based, handle their game world data (terrain details, who is standing where, etc.). By "handle" i mean store and use -- not just one or the other.

My game world is essentially a sector grid of about 250,000 maptiles in total! This is simply a large database of sector information which represents several continents. Because it is turn-based I have not seen any problem with the large amount of sector information (no lag yet) but I am concerned I may be going about it the wrong way. Not all of those tiles are visible at a given time, only a small area. However, I'm aware of size limitations to database tables and already have a database that is 4gigs. How do other 2d tile-based games with large worlds record their sector information, terrain details, and how do they keep track of who is standing in a sector? My game world consists of several large continents. Is there a better, or more efficient way to record this information?

What if i decided to increase the scale of my game world and effectively increase the number of sectors in my world? 250,000 sectors sounds like a lot but it really isn't. With my current model my world is roughly 1/4th the size of our Earth. My goal is to have an Earth sized world.

Do other continent-based overworlds do this same thing? I realize a small game world would be fine with something like this but I'd like to increase the detail in my world but doing so would mean increasing (multiplying) the number of sectors and having an even larger database to contend with.

# Answer
> 1 votes
I've made a game similar to Pardus as part of my diploma project. It has a tile-based world just like you described: hundreds of sectors (=continents), each sector is a 2D map with ~1000 tiles. There are different tile types (empty space, nebula, energy fields, asteroids etc.), there can be buildings, resources, players or monsters on each tile.

Here's the schema of my *'tile'* table and all the tables that are linked to a *tile* in some way:

The most important thing to notice here, is that each *tile* has an ID. The basic info (coordinates, sector ID etc.) are stored in the *'tile'* table. A *'player'* will just reference a *tile* by its ID. This way, I don't have to store duplicates of coordinates, tile type etc. When I want to know where a certain *player* is, I do a query like this:

```
SELECT tile.coord_x, tile.coord_y, tile.sector
FROM tile, player
WHERE tile.id = player.tile

```

You should google for the keywords **'database normalization'**. A good practice is to **normalize to 3NF (third normal form)**.

---
Tags: 2d, turn-based, data
---


# Question
Title: Producing a smooth mesh from density cloud and marching cubes
Based on my results from this question I decided to build myself a 3D noise map containing float values in place of my existing boolean point values. The effect I'm trying to produce is something like this, rather than typical rolling hills; which should explain the "missing cubes" in the image below.

If I render my density map in normal "minecraft mode" (1 block per point in the density map) varying the size of the cube based on the value in my density map (floats in the range 0 to 1) I get something like this:

I'm now happy that I can produce a density map for the marching cubes algorithm (which will need a little tweaking) but for some reason when I run it through my implementation it's not producing what I expect.

My problem is that I'm getting something like the first image in this answer to my previous question, when I want to achieve the effect in the second image.

Upon further investigation I can't see how marching cubes does the "move vertex along the edge" type logic (i.e. the difference between the two images on my previous link). I see that it does do some interpolation, but I'm not convinced I have the correct understanding of what I think it should do, because the code in question appears to give the same result regardless of whether I use boolean or float values.

I took the code from here which is a C# implementation of marching cubes, but instead of using the `MarchingCubesPrimitive` I modified it to accept an object of type IDrawable, containing lists for the various collections (vertices, normals, UVs, indices), the logic was otherwise untouched.

My understanding is that given a very low `isovalue` the accuracy level of the surface being rendered should increase, so in short "less 45 degree slows more rolling hills" type mesh output. However this isn't what I'm seeing.

Have I missed something or is the implementation flawed and need to be fixed?

EDIT:

A little more detail on what I am seeing when I "marching cube" the data.

Ok so firstly, ignore the fact that the meshes created by the chunks don't "connect" (i'll probably raise another question about this later).

Then look at the shaping of the island, it's too ... square, from the voxels rendered as boxes you get the impression there's a clean soft gradual hill and yet from the image there are sharp falling edges even in the most central areas where the gradient in the first image looks the most smooth.

The data is "regenerated" each time I run this so no 2 islands come out the same, and it's purely random so not based on noise, but still, how can it look so smooth in 1 image and so not smooth in the other?

# Answer
You're not interpolating the vertices correctly, depending on the density value of two points that should have a vertex placed between them, you should have the vertex placed in such a way that the density value for that point is 0.

I'm doing a piss-poor job of explaining, but here is an really good article:

Nvidia GPU Gems 3 - Chapter 1
> 0 votes

---
Tags: c#, unity, voxels, marching-cubes
---


title: Sidescrolling terrain 1D perlin noise

text:
# Question
Title: Sidescrolling terrain 1D perlin noise
I'm working on a tile based game and already got a generator working. But it doesn't seem to be smooth enough to look realistic.

Here's the code I'm using:

```
for (int i = 0; i < width; i++)
        {
            float y = ClassNoise.PerlinNoise1D(i, 2f, 4);
for(int j = 2048+y;j<height;j++)
{
  tiles[i][j] = new Tile(i,j);
}
}

public class ClassNoise
{
    public static float Noise(int x)
    {
        x = (x<<13) ^ x;
        return (float) ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
    }
    public static float PerlinNoise1D(float x, float persistence, int octaves)
    {
        float total = 0;
        float p = persistence;
        int n = octaves - 1;

        for (int i = 0; i <= n; i++)
        {

            float frequency = (float) Math.pow(2, i);
            double amplitude = Math.pow(p, i);
            total += InterpolatedNoise(x * frequency) * amplitude;
        }

        return (int) total;

    }

    private static float InterpolatedNoise(float x)
    {
        int integer_X = (int) x;
        float fractional_X = x - integer_X;

        float v1 = SmoothNoise1D(integer_X);
        float v2 = SmoothNoise1D(integer_X + 1);

        return CosineInterpolate(v1, v2, fractional_X);

    }

    public static float CosineInterpolate(float a, float b, float x)
    {
        float ft = (float) (x * Math.PI);
        float f = (float) ((1 - Math.cos(ft)) * 0.5);

        return a * (1 - f) + b * f;
    }
    public static float SmoothNoise1D(int x)
    {
        return Noise(x)/2  +  Noise(x-1)/4  +  Noise(x+1)/4;
    }

}

```

How can I make this terrain generator smoother?

EDIT:

It currently looks like this (The terrain on the screenshot isn't the full terrain it's just the terrain on the screen):

# Answer
Primarily the issue is that you are using a non realistic persistence of 2. Persistence should be between 0 and 1, where closer to 1 is more rough and closer to 0 is more smooth, see here for more details. 2 is simply a meaningless number that more or less says make the finest octave unreasonably large. Larger than the maximum output is supposed to be.

Correcting this will cause you to have a continuos 0 output, this is because you have cast your output to (int), stop doing this and you will start getting an output between -1 and 1 that is smooth. The following graph is for values between 0 and 20 with persistance of 0.5.

### Multiple octaves

You are also effectively using the same seed for all your octaves, each octave uses the same 3 prime numbers in the Noise function so actually your octaves are the same noise at different scales. This can cause difficulties. Each octave should have its own primes.

Replace your Noise function with something like:

```
    public float getBasicNoise(int x) {
        x=(x<<13)^x; // bitwise shift to the left by 13 places then rased to n

        //& performs a bitwise multiplication (i.e. 0*0=0, 1*0=0, 1*1=1
        //it makes this multiplication with the largest possible int
        //i.e. +111111.....1111
        return (float)( 1.0 - ( (x * (x * x * primes[2] + primes[0]) + primes[1]) & Integer.MAX_VALUE) / 1073741824f);

    }

```

Then each octave is initialised with its own primes, avoiding these problems.
> 5 votes

# Answer
You might consider using the midpoint displacement algorithm vice perlin noise depending on the terrain you'd like to have

Why would someone chose midpoint displacement over perlin noise for 3D terrain generation?

Here is a great example of "hills" generated using midpoint displacement algorithm: https://gamedev.stackexchange.com/a/9386/20399

What is the simplest method to generate smooth terrain for a 2d game?
> 0 votes

---
Tags: java, perlin-noise
---


title: "retro"-look in 3d-XNA-game

text:
# Question
Title: "retro"-look in 3d-XNA-game
In my XNA-4.0-game (which somehow is a bit like MineCraft), I have got some big cubes with small textures (16x16px) on it. By default, XNA just scales them up smooth so there aren't any hard borders. But as the game is a retro game, I want these big pixels. So how do I turn of that interpolation?

# Answer
> 2 votes
Change the sampler state to Point clamp or wrap before drawing.

```
  GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

```

---
Tags: xna, 3d, interpolation
---


# Question
Title: Box2d contant speed before and after collision
I want to make my body fly at constant speed, how to make it fly at constant speed before and after collision? I set restitution of my body to 1.0 but after some direct and powerful collisions my objects begins to slow, I want it to fly same speed as before. I heard this can be done by setting liner damping of the object, I think it can prevent only from fast flying objects not slow. Thanks in advance.

Edit\* I can simply modify velocity of the object every frame, is it a solution?

```
var velocity:b2Vec2=b.GetLinearVelocity();
var speed:Number=velocity.Length();
var ratio:Number=circleSpeed/speed;
velocity.Multiply(ratio);
b.SetLinearVelocity(velocity);

```

# Answer
> 5 votes
Ok here's the dealio.

Forget box2d for the next little while. Just think about physics.

# Head-On Collisions

First of all, recall the definition for the coefficient of restitution:

> The coefficient of restitution (COR) of two colliding objects is a fractional value representing the ratio of speeds after and before an impact, taken along the line of the impact.

Also, lets keep things simple and restrict ourselves to thinking about head-on collisions between two circles. This means that the line of impact will be coincident with the axis along which the circle(s) are moving (one may be at rest), as shown below:

Image Courtesy of ecourses.ou.edu

Consider the set-up in the figure above, where ball `A` is moving towards ball `B` and their masses are significant relative to each other. When the collision occurs, `B` will gain some momentum in the direction `A` was initially travelling, but `A` can do one of three things depending on the initial velocity of `A` and the masses of the two balls:

1. `A` will bounce off `B`, reversing its direction and travelling with a smaller speed than it entered the collision with
2. `A` will completely transfer its momentum to `B`, and will stop as a result.
3. `A` will continue along its initial direction, but with a smaller speed.

Any high-school or 1st year university physics text will walk you through this, and show the equations that can be used to solve for any parameter you desire.

Ok now this is important: in cases 1-3 the kinetic energies (speeds) for each of the balls change before and after the collision, **even though the COR = 1**. Why is that? The Wikipedia definition sacrifices a little clarity for the sake of compactness, but it is still correct. Take a look at the equation below from the wiki article:

This is just the conservation of momentum equation and the COR equation, written from their definitions.

It is quite clear that, even with COR = 1, the speeds of the colliding objects before and after the collision need not be maintained. All that's required is that the *difference in their speeds* before and after the collision remain the same.

# Main Answer

Given this brief explanation I can point out some problems with your question. You are asking that the speed of an object be maintained before and after a collision, when this is non-physical behaviour. box2d is built to simulate physically realistic behaviours (within computational limits), and you are not letting it do that. So my advice is to think carefully about what you want to achieve in your game, and make your next move based on that. There are a few options:

1. **Don't use box2d** \- if you just want simple axis-aligned bounding boxes bouncing around, always maintaining the same speed, then you should be able to write that yourself without too much trouble
2. **Make everything travel at a constant speed** \- Do the following:

* set gravity to zero
    * set the mass of all the bodies to the same value (or adjust each fixture's density so the final mass of all the bodies is the same)
    * set the initial velocity of all bodies to the same value
    * turn off rotation for all bodies
    * set friction to zero for all fixtures
    * don't use any joints
    * don't apply any forces or impulses
    * don't create bodies on top of other bodies (this is not an error, but it will solve the collision and give both bodies new velocities)

This should give the effect you are looking for, but it severely restricts what you can do. After listing all these restrictions this really looks like a poor choice, but it's here nonetheless.
3. **Store the desired speed somewhere else and set the body velocity as necessary** \- you could implement a Collision Callback and have it set the bodies' speed's based on a speed stored elsewhere (e.g. on the entity that owns the body). That way it would reset the speed of a body after every collision. **Warning:** this will produce the non-physical behaviour I was talking about, and many things will end up looking funky as a result

* e.g. Ball `A` hits a slower moving ball `B` as in the figure (where both are travelling in the same direction). Also, the masses and initial velocities work out so that case 3. from above applies. This means that `A` and `B` will both have the same final direction. This is all fine and dandy in a normal collision because at most `A` will be moving with the same velocity as `B` an they will remain in contact. However, if you try to enforce that the speeds before and after are the same, then after the collision `A` will be overlapping B! Now what? Maybe you can find an answer to this but it's not going to be pretty.

Also, your are going to have oblique collisions that will exchange some linear kinetic energy for rotational kinetic energy (reducing the linear velocity of the center of mass, while causing it to spin). Setting fixed rotation will solve this problem, at the cost of your objects not being able to rotate.
4. **Change your game** \- figure out a different design solution that's based around physically correct collisions, then use box2d normally. This is my preferred solution. I don't know your game design at all, so this may not be an option, but I encourage you to think creatively.

# Notes

Please do not change the velocities after every step, that would be a huge waste of cpu time, not to mention you will still have to figure out ways to get around the problems arising in solution 3.

linearDamping in box2d works like Aerodynamic Drag. In layman's terms this means that fast moving objects will be slowed much quickly than slower moving objects. Increasing the linearDamping exaggerates this effect. angularDamping works exactly the same, except it applies to rotation instead of linear motion. Neither linearDamping nor angularDamping affect collisions.

I hope this helps!

---
Tags: box2d, physics
---


# Question
Title: Collision resolution in case of collision with multiple objects
I have static objects and movable objects. The collisions are detected using the separating-axis-theorem.

For example, in this situation I have two static objects (in red):

and a movable object between the two:

My algorithm is able to compute the collision between two of these objects, and it also spits out a perfect resolution vector (meaning a minimum-displacement-vector) to the collision.

So for example, when I check the collision between the green rectangle and the right red rectangle, the algorithm spits out a vector that tells me how I need to move the green rectangle in order to resolve the collision:

Notice that I just quickly drew this in MSPaint, so in that picture it could actually be that the minimum-translation-vector pushes the green rectangle out on the top, but I'm going to assume here that pushing it out to the left/right is actually shorter.

The general way of approaching this would be to only resolve the collision of one collision per frame, instead of all at once. But in my case, this would result in flip-flopping:

First, the solver detects two collisions but only resolves the collision between the right rectangle and the green rectangle:

Then, in the next frame, it detects only one collision which is between the left red rectangle and the green rectangle, and resolves it:

As you can see, this doesn't actually resolve the collision (for example by pushing the green rectangle out to the top), and instead just flip flops between the two states infinitely.

How can I solve this?

# Answer
> 7 votes
Depending on exactly what you are trying to achieve (high physical accuracy or just a close-enough real-time simulation), you could try using speculative contacts.

Here are the details: http://www.wildbunny.co.uk/blog/2011/03/25/speculative-contacts-an-continuous-collision-engine-approach-part-1/

He describes in that article what you need to know to implement it, and it's very simple compared to other approaches (such as sphere casting and then sorting collision resolutions by time of impact).

If you need/want more, you can purchase his source code for (IIRC) $7.

Here is a video of my implementation in 3D: http://www.youtube.com/watch?v=JvT2H1RmOas

Notice how stable the simulation is with just a single iteration. You could easily use multiple iterations per frame to resolve multiple collisions to a stable state, which would be more accurate.

# Answer
> 2 votes
You can first compute all vectors needed to solve each collision then compute a resultant from them.

The only case when this can byte you is if these vectors nullify each other, just like in your example. In that case the collision cannot be solved.

# Answer
> 0 votes
If you closely look at it, that state of objects is (or should be) unachievable..

Let the leftmost red shape be shape R1, and the rightmost red shape be shape R2. Let the green shape be G.

i.e. Given the size and geometry of all three objects, and given that all objects are not penetrable:

```
 (1) G could not have been just directly to the left of R2, since R1 has been there
     already. Consequently, the translation of G from left to right, penetrating R2
     could not have occurred.
 (2) G could not have been just directly to the right of R1 since R2 has been there
     already. Consquence of which is the same as that from (1).
 (3) Had G come from the top, the movement will be blocked by both R1 and R2, given
     that their geometry and Y coordinate is the same.

```

Now, boils down to it, if your algorithm queries your objects one by one, it then is a matter of concurrency, i.e. in a sense, the algorithm is supposed to check ALL objects at the same time, but the algorithm limits you to do objects and process them one at a time...

If G is checked against R1 after it is checked against R2, then G would appear to legally be to the right of R1 (if G say approaches R1 with the direction of vector \<-1,-1\> with arbitrary magnitude (or distance)), because the checking between R1 and G permits it, and forgets about the checking between R2 and G which was done before.

A solution you may do is to collect all minimum displacement vectors into an array or whatever data structure you want, and choose one that would prove legal to ALL Objects.

Note that at a given frame, the object (G for instance) can only have ONE direction. (oh man, sounds like the boyband...)

---
Tags: 2d, collision-detection, collision-resolution, separating-axis-theorem
---


# Question
Title: Cocos2d how to correctly preload a spritesheet before the scene start?
I'm working on a game with Objective-C and Cocos2d, the game has a huge number of images, and obviously as I add images on the spritesheet (well yes I'm using spritesheets) the loading time get longer, I've seen a huge increasing in loading time since the last update (I had to add a lot of stuff) and that's why I truly need to preload the entire spritesheet before the game start. So here is what I don't know exactly how to do, I'm using this method in the appDelegate in the applicationDidFinishLaunchingWithOptions method:

```
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"spriteSheetFile.plist"];

```

but seems to do nothing. There is surely something I'm missing...

I've also tried:

```
[[CCTextureCache sharedTextureCache] addImageAsync:image_png target:self selector:@selector(loadImage:)];

```

but to be honest I'm not sure on how to use this with a spritesheet...

so my question is: what here is wrong and how can I preload a spritesheet full of sprites before the game start? and also what I'm not totally sure about is, if I preload a spritesheet, this means that when the game start the sprite needs to be draw the first time, there is where the loading comes from? how can I make this scene loading as fastest as It can?

any help would be great, thanks

# Answer
> 2 votes
This question is several weeks old, but I thought I would answer in the event you were still looking for assistance, or too perhaps help someone else down the line.

Please note that the way you are loading the spritesheet using CCSpriteFrameCache is correct, but it does nothing more than add the contents of the spritesheet to memory. You then need to create sprites from that loaded content using CCSprite * mySprite = \[CCSprite spriteWithSpriteFrameName:@"spritename.png"\], for example. I assume you know how to add sprites as children of a layer or how to use CCSpriteBatchNode. The latter is where you get the performance boost.

Once a spritesheet has been loaded into memory you can access its contents from virtually anywhere within your application. As such you could, if you wanted to, load all spritesheets at the time your application launches or at any point a pregame launch screen is displayed; thus this resource load would occur prior to the actual game start. Then you would only need to create your needed sprites for actual game play.

A potential problem with this approach, however, would be if you had many spritesheets and not all of them would be needed for each game "level" for lack of a better term. The more spritesheets you load, the more memory they take. So you have to balance this preload approach with any performance issues that may arise.

Let me know if this helps.

---
Tags: cocos2d-iphone, cocos2d, objective-c, spritesheet, preload
---


# Question
Title: Why doesn't the Source engine clear the back buffer?
In the Source engine, when the map does not have a sky box, I see that typical artifact from the back buffer not being cleared. Why does the Source engine do that? Is it a performance reason, or something like that?

# Answer
> 4 votes
The source engine doesn't clear the back buffer simply due to the way levels are setup (i.e. it's not needed).

Source engine levels are built from brushes (i.e. volumes are either added as solid/liquid or subtracted from other brushes) and the player (or more specific, the camera) is always in an enclosed space, even if the level is supposed to be outdoors. Areas where you see the skybox are actually the surfaces of brushes marked as "sky". I've had a random look at YouTube and the first hit I've found explains level building pretty well. Watch it from about 1:45 to 2:15 to see the "sky" being set, then at the end of the video you'll see it in action.

So why not clear the back buffer? Performance. Clearing the backbuffer would solve glitches you can see when the camera gets "outside" due to a bug, but in standard gameplay you wouldn't notice this anyway. So if it doesn't make any difference, you can just skip it alltogether. Clearing the back buffer has a complexity of O(n) depending on the number of pixels on screen, doing nothing at all would simply be O(0) (well, that isn't defined, but I think it pretty much shows the idea).

---
Tags: rendering, source-engine
---


# Question
Title: XNA Arcball and moving model - the model is altered instead of the camera
I'm trying to implement an arcball type camera, I've got all controls working very nicely. I can rotate the X/Y axis with my mouse and zoom in and out with the Z/X keys.

The problem is, that the camera doesn't rotate around the model, but instead, the model rotates around its axis and the camera remains on the same position. When I zoom in or out, the model scales bigger or smaller.

In summary I want to achieve: rotate camera and zoom in/out on my model and still keep control of my model. How should I go about this?

This the code I'm using. Help or advice is much appreciated

**Draw character**

```
void DrawCharacter(Matrix view, Matrix projection)
{
    // Render the skinned mesh.
    Matrix[] bones = animationPlayer.GetSkinTransforms();

    foreach (ModelMesh mesh in currentModel.Meshes)
    {
        foreach (SkinnedEffect effect in mesh.Effects)
        {
            effect.SetBoneTransforms(bones);
            effect.View = view;
            effect.Projection = projection;
            effect.EnableDefaultLighting();
            effect.SpecularColor = new Vector3(0.25f);
            effect.SpecularPower = 16;
        }
        mesh.Draw();
    }
}

```

**Update camera**

```
    private void UpdateCamera(GameTime gameTime)
{

    // start arcball
    float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

    // mouse movement
    MouseState currentMouseState = Mouse.GetState();
    if (currentMouseState != originalMouseState)
    {

        float xDifference = (currentMouseState.X - originalMouseState.X);
        float yDifference = currentMouseState.Y - originalMouseState.Y;

        Mouse.SetPosition(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);
        if (Mouse.GetState().RightButton == ButtonState.Pressed)
        {
            cameraRotation -= xDifference * 1.05f;
            cameraArc += yDifference * 1.025f;

            // Limit the arc movement.
            if (cameraArc > 90.0f)
                cameraArc = 90.0f;
            else if (cameraArc < -90.0f)
                cameraArc = -90.0f;
        }
    }

    // Check for input to zoom camera in and out.
    if (currentKeyboardState.IsKeyDown(Keys.Z))
        cameraDistance += time * 0.25f;

    if (currentKeyboardState.IsKeyDown(Keys.X))
        cameraDistance -= time * 0.25f;

    // Limit the camera distance.
    if (cameraDistance > 500)
        cameraDistance = 500;
    else if (cameraDistance < 0.001f)
        cameraDistance = 0.001f;

    // reset camera
    if (currentKeyboardState.IsKeyDown(Keys.R))
    {
        cameraArc = -5;
        cameraRotation = 180;
        cameraDistance = 100;
    }
    /// end of arcball

    Matrix cameraFacingMatrix = Matrix.CreateRotationY(sphereFacingDirection);
    Vector3 positionOffset = Vector3.Transform(CameraPositionOffset,
        cameraFacingMatrix);
    Vector3 targetOffset = Vector3.Transform(CameraTargetOffset,
        cameraFacingMatrix);

    Vector3 cameraPosition = spherePosition + positionOffset;

    if (heightMapInfo.IsOnHeightmap(cameraPosition))
    {

        float minimumHeight = heightMapInfo.GetHeight(cameraPosition) + CameraPositionOffset.Y;

        if (cameraPosition.Y < minimumHeight)
        {
            cameraPosition.Y = minimumHeight;
        }
    }

    Vector3 cameraTarget = spherePosition + targetOffset;

    // with those values, we'll calculate the viewMatrix.
    viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up);
}

```

**Draw**

```
    protected override void Draw(GameTime gameTime)
{
    GraphicsDevice device = graphics.GraphicsDevice;

    device.Clear(Color.Gray);

    GraphicsDevice.BlendState = BlendState.Opaque;
    GraphicsDevice.DepthStencilState = DepthStencilState.Default;
    GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

    // draw models
    DrawModel(terrain, Matrix.Identity);

    // Compute camera matrices.
    float aspectRatio = (float)device.Viewport.Width / (float)device.Viewport.Height;

    Matrix view = Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) *
                  Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
                  Matrix.CreateTranslation(0, -45, 0) *
                  Matrix.CreateLookAt(new Vector3(0, forwardRotation, -cameraDistance),
                                      new Vector3(0, 0, 0), Vector3.Up);

    Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                            aspectRatio,
                                                            1, 10000);

    DrawCharacter(view, projection);

    DrawAxe(view, projection);

    base.Draw(gameTime);
}

```

# Answer
> 1 votes
This assumes the camera (`posCam`) is supposed to rotate around a specific point (`posTarget`).

To rotate the camera around a specific point (simplified):

* Translate the camera's position: `posCam -= posTarget;`
* Rotate the camera (`posCam`) the way you'd like to.
* Translate the camera back to where it should be: `posCam += posTarget;`
* Rotate the camera's facing the same way.

---

Update:

Not 100% sure since I can't try this right now, but I'd say something like this in your `Draw()` function might be enough:

```
Matrix cameraTrans = Matrix.CreateTranslation(0, -45, 0) * // This includes the camera's distance
              // The following lines apply the rotation
              Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) *
              Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
              // Then move the camera to the actual position relative to the object
              Matrix.CreateTranslation(objectPosition.x, objectPosition.y, objectPosition.z);

// Get the real position of the camera
Vector3 cameraPosition = Vector3.Transform(Vector3.Zero, cameraTrans);

// Get the actual view matrix
Matrix view = Matrix.CreateLookAt(cameraPosition, objectPosition, Vector3.Up);

```

(You might have to play around with the order of transformations, but I think they should be fine.)

Outside that code you shouldn't have to touch anything except the rotations/angles.

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


# Question
Title: What is the camera direction vector for an isometric view?
What values correspond to a 3D vector for screen-normal from within an isometric game?

It needs to be in game coordinates. It is a standard isometric where tiles are rotated 45 degrees and half height (in 2D projection).

For example \[+x,0\] in game corresponds to north-east on screen. But what is the vector leading out of the screen. This vector is always the same (a fixed orthographic projection).

# Answer
> I need vector in iso coordinates that leads outside the monitor (is normal to a monitor screen).

It's two rotations. Your tiles are half as high as they are wide. Projection/dot product is proportional to cosine, and `arccosine(1/2) == 60 degrees`, which means that's your first rotation. It is followed by a 45-degree rotation.

You start with unit-z, `0, 0, 1`
The first 60 degree rotation (about the x-axis) yields `(0, -ROOT(3)/2, 0.5)`
The next 45 degree rotation (about the z-axis) yields `-ROOT(2)*ROOT(3)/4, -ROOT(2)*ROOT(3)/4, 0.5)`

Invert it, and it's your camera's direction.

```
Vector3 camera_forward = (0.612375, 0.612375, -0.50000);

```

(I assumed that up-left was position Y, and up-right was positive X)
> 7 votes

# Answer
Maybe I'm missing something right now (bare with me; it's late in the night).

Essentially you'll just need two tiny steps here to get from world space to screen space (i.e. from world coordinates to screen coordinates):

* Rotate your coordinates by 45° (rotation axis pointing out of the screen).
* Divide the new y coordinate by 2.

For the other way (from screen coordinates to world coordinates) you just reverse this:

* Multiply the y coordinate by 2.
* Rotate your coordinates by -45°.

Remember that you're doing isometric projection, not perspective projection (so you don't have to fiddle with real rotation along the x axis).
> 0 votes

---
Tags: 3d, vector, isometric, projection, screen
---


# Question
Title: How to check if user has integrated graphics card?
I'm almost done with my Direct3D game. When user starts game first time it will adjust settings (and maximum settings) based on DirectX feature level starting from 9\_1 up to 11\_1. I have different shaders/multisampling/anisotropy/LOD/shadows. I used my personal PC for development and I had so much backup power I thought performance wont be a problem. Then I bought laptop with integrated graphic card which supports 11\_1 but is extremly slow (AMD A6-4400M, Radeon 7520G). First I thought it's my game but after few days of intense testing in other games it feels like integrated card has not enough power. In my game on full settings game drops to 30fps. When I disable few settings I can easly get up to 60 (which is required by Windows store apps).

I don't want to ruin user experience first time he runs app so I would prefer to adjust his settings to 60 fps and here is my question. Is there any way to check if it's integrated card and does it make any sense? I don't want to force user to run some simulator. I could also check ram but I won't solve my problem since game is not using much ram.

Thanks in advance.

Edit: Fixed hardware description.

# Answer
My laptop has an "integrated" Nvidia 5400M. It plays most games with ease. Make sure your laptop is not using the Intel 4400 graphics GPU and is actually using the AMD 7520G. (Many newer laptops have two graphics options these days).

To answer your question, it doesn't make much sense to test for integrated or not, you need to know the capabilities of the GPU, not if it's user replaceable. You can do that by compiling a list of the most common graphics cards and creating pre-configured settings for them based on how powerful they are.

Or you can a very short simulation and ask the user to check their settings if you find the simulation isn't running well, or continue with the standard settings if no problems are detected.
> 6 votes

# Answer
Along the lines of other answers here, figuring out what card the user is using may not be the most effective course of action. DirectX9 has a built in method to query the current video hardware by capability. Interestingly enough, DirectX 10+ does not follow this idea, where instead running DirectX 10+ is a sign in of itself that the hardware is compatible with everything DirectX 10+ does. Dropping down versions is a sign of missing power.

Running dxdiag would tell you what version you are personally running, and you can draw conclusions from there.

Source for capability query for DX9: How can I check for Shader Model 3 support?
> 1 votes

# Answer
Specifically, you will need a list of hardware PCI IDs you explicitly you want to specially handle. Typically, modern games do this with a large bevy of settings and simply have a "detect best settings" option that allows the user to tweak further as desired.

You can use feature detection, but this doesn't particularly indicate speed or efficiency. Sometimes a driver version is just busted or lying, too.

You can use `DXGI_ADAPTER_DESC` used from IDXGIAdaptor::GetDesc to read the PCI ID of the device for DX10+ cards. Use IDXGIFactory::EnumAdaptors to get the interfaces. There are similar methods to use for DX9 cards (if you support them), but I don't know them off the top of my head. You can also, with some manual string parsing (at least the only way I recall) get the driver version number.

Given that info, you can consult your own database of known hardware and driver versions you've tested to select decent defaults, with a "low quality" setting being a good guess for unknown cards. Just be sure to let the user tweak the setting values. Even if, e.g., you detect an Intel GPU, those GPUs have improved a lot in recent iterations and for all you know might even be NVIDIA/AMD contenders a few years down the line; don't presume to know the future or know the user's hardware better than he does.
> 1 votes

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