# Question
Title: What techniques could I use to give players the ability to control certain features, e.g. fatness?
I'm working on a tool for character customization (e.g. starting from a base model, a player can control his fatness), so I'm looking for ideas, techniques or other regarding this topic.

After some research I thought to this technique: starting from two models (one standard human and one fat human, both with the same data, like vertices and triangles), then creating a new model by storing data about the two original mesh (e.g. store vertex data of the second mesh as color data), and controlling their interpolation with a shader.

What do you think about this idea? Suggestions?

# Answer
> 9 votes
You might want to have a look at Elder Scrolls: Oblivion, in particular the character creation screen. They do a lot with modifiable anatomies there. Each race has its own anthropometric norms and ranges. Anthropometrics is the study of the particular measurements / proportions of individual physical characteristics (phenotypes) of individual human beings, comparatively speaking. It's a good place to start doing some research into exactly *what* varies between individuals.

Your idea sounds good, although I think simply interpolating between just two meshes may not give you enough variation.

# Answer
> 3 votes
I would create two models for every attribute you want morphed, much like your original idea of having a fat and skinny model.

Using 'nose' as an example, have a 'nose' slider and you interpolate between the two nose meshes for your result. This way you could have many variations of modifiable attributes.

Depending on your language, I would then dynamically create a final model by assembling the interpolated body pieces together. You could then save this model if you want to use it between game plays, or it may be better / simpler to just save the various interpolation values and recreate the final model each time you load the game.

Stitching together the final model may be difficult if the perimeter vertices of the two models aren't the exact same.

\[Edit\] You may have to define reference vertices by name / id to know where to stitch the nose (for example). If you have a head size attribute, the location of the nose will vary. But if you knew nose vertice 'xxx' maps to head vertice 'yyy' you could shape the nose to fit the new head size exactly.

---
Tags: graphics-programming
---


# Question
Title: Multi-platform multi-threading: What are the real challenges?
While a library like SDL provides a cross-platform wrapper API for threading, I think it would be naive to assume that this leads directly to easy development of games across vastly different platforms (desktop / mobile).

What is the best way to tackle developing in this way (given any cross-platform threading API) considering the following:

* different numbers of cores
* vastly different processing capabilities per core
* A generally different systems architecture with eg. different latencies for cache, RAM , and I/O access

I get the feeling that the only way to do this is evaluate how many threads may be run per each device you intend to support, and find out what the lowest common denominator is. However, this still leaves me in the dark as to the total amount of processing throughput available. Am I right in assuming the only way to do this effectively is to actively develop for the lowest spec mobile device I intend to support, throughout development? -- i.e. the lowest common denominator? Should this *roughly* be sufficient? Or is there more to it than this?

EDIT: Please could others offer further experience on this as I don't feel my question has been answered fully yet.

# Answer
You talk about "multithreading difficulties" but what difficulties are you actually talking about? In a way you're citing a phantom problem which may not even exist. The real challenge is one you make for yourself - if you are absolutely determined to get every last drop of power out of a piece of hardware, that does involve using the hardware to best effect, but that also widens the gap between the most powerful machine and the least powerful. The implication of this is that if you have a game that really makes the most of a PS3 (for example), you can't really run it on a cheap cellphone anyway, so your problem is no longer "how can I get 1 program to work across very different hardware" but becomes "how can I implement 1 game idea several different ways so that it works on differently powered hardware". The threading issue becomes less relevant then.

> While a library like SDL provides a cross-platform wrapper API for threading, I think it would be naive to assume that this leads directly to easy development of games across vastly different platforms (desktop / mobile).

Easy development of games - sure. Optimal multithreading, no. But you don't *need* multithreading to make games. To make high performance ones, it certainly helps. But many great games run in a single thread.

> What is the best way to tackle developing in this way (given any cross-platform threading API) considering the following:
>
> * different numbers of cores
> * vastly different processing capabilities per core
> * A generally different systems architecture with eg. different latencies for cache, RAM , and I/O access

Instead of trying to assign systems to threads, assign tasks to threads. Give each task the data it needs to run and farm the tasks off to whichever hardware is available. Usually you'll have some sort of thread pool to abstract away the various cores or processors, and a task manager which has a queue of tasks and yields them up to the various threads when the thread signals that it is finished the previous task and is ready for a new one. Hardware with more cores will obviously complete the tasks more quickly and be able to render more rapidly. Specialising this system to work optimally on systems with different characteristics becomes an advanced optimisation problem, but can be based on certain heuristics (eg. a task which doesn't need to return much data can easily be pushed to a different processor but one with a lot of data to return might need to be kept local).

However, decomposition of game features into discrete tasks is quite a complex matter and often not worth the effort unless you are very sure that you need the performance, so most won't even attempt it.

Some further reading:

http://www.gamasutra.com/view/feature/1830/multithreaded\_game\_engine\_.php \- see the 'data parallel' section. With this model the data is split across several identical tasks and farmed out to individual threads.

http://software.intel.com/en-us/articles/designing-the-framework-of-a-parallel-game-engine/ \- quite dense, describes things at the OS level rather than the game level.

http://drdobbs.com/high-performance-computing/216500409 \- not game specific, but completely relevant in terms of telling you how you need to divide up the tasks.

http://www.itfgaming.com/news/tech-focus-crysis-2-and-the-future-of-cryengine-3 \- half-way down this interview is an anecdote about how they migrated to a task based system.
> 11 votes

# Answer
When I did mobile games we first developed a 'gold' version (ie. a fully functionnal game) and then we split it up in 3 major versions (big screen, middle sized and small screen). These ones was further converted into 11 versions: demanding graphics (read takes much memory / cpu) vs low profile etc. (there were a couple 'special platform versions too).

The biggest problem was (that was my job among others) to isolate the platforms needed and determine those versions and how to create them (ie. big-screen but Low profile should be a downgraded version of big screen / hi profile or should it be middle sized screen / lo profile made big screen?).

Of course we coded with this in mind so games were very loosely attached to the screen size.

HTH

\[edit\] What I meant was that you need to split up your target platforms in different qualities (ie. 1 core, 2 cores, 1 core but twice as fast ...) Then decide how many virtual targets you want (for example "only one" or "Low, Mid, Hi") Then place all platforms in their respective 'quality' and for Each quality, take the lowest denominator and 'port' the code so it complies with those requirements (ie. works and is fast enough).

It might seem that you must do this with quite much guesswork but you can already find the worst quality with the worst platform. I'd choose every next quality at least "twice as good" as the former, this would probably not generate more than say 3-4 "qualities". If the code is ported from a gold version, any platform not performing good enough could just be retrograded to a lower 'quality' to make it speed up. Any new platform could also quite easily be placed in the right quality.
> 4 votes

# Answer
> I get the feeling that the only way to do this is evaluate how many threads may be run per each device you intend to support, and find out what the lowest common denominator is.

Not necessarily - there may be hope for a more dynamic solution, but this depends on the actual problem you are trying to solve (if any). You're a bit vague in your question, so my answer has to be vague as well.

If the grouping of platforms you are intending to run on have the capability for hardware enumeration via an API, you can use that interface to detect the maximum number of threads the system can handle, and use that as a basis for how many threads your application should create. The only challenge here is finding those APIs; whether or not you go to the OS level, or search for a third-party library, or a cross-platform SDK/API is up to you and depends on the platforms you are trying to support.

> What is the best way to tackle developing in this way (given any cross-platform threading API) considering the following:
>
> ```
> different numbers of cores
> vastly different processing capabilities per core
> A generally different systems architecture with eg. different
>
> ```
>
> latencies for cache, RAM , and I/O access

In my opinion, none of those things should be your concern. Your concern should be building your game. If you hit a bottleneck and decide that it would be better to spawn a separate thread for a specific processor-intensive task, then spawn the thread and let the OS and other lower-level software decide how to manipulate the hardware to handle the threading.
> 2 votes

---
Tags: cross-platform, multithreading, sdl
---


# Question
Title: How can I reduce aliasing in my outline glow effect?
I'm trying to replicate the glowing outline effect in the Left 4 Dead game. The effect causes an objects outline to glow, even when the object is occluded. Here is a screenshot of the effect:

I'm somewhat able to replicate this effect in my OpenGL based program. This is what I'm currently doing:

* Create a color and depth texture that is half the screen size for rendering the glowing objects
* Clear the glow color/depth textures. Color is cleared to black.
* For each glowing object, render it to the glow texture as a solid color
* Perform a separable gaussian blur on the glow texture
* Render the full resolution scene as normal
* Additively blend the glow texture with the normal scene, but use the glow depth texture to mask out the object, leaving just the blurred outline.

Here is a screenshot of my approach:

Here is the fragment shader that combines the glow texture with the scene:

```
uniform sampler2D glowColorTex;
uniform sampler2D glowDepthTex;
uniform sampler2D sceneColorTex;
void main()
{
    vec2 uv = gl_TexCoord[0].st;

    vec4 color = texture2D( sceneColorTex, uv);

    float depth = texture2D( glowDepthTex, uv).r;
    if(depth == 1.0) {
        color += 2.0 * texture2D( glowColorTex, uv);
    }

    gl_FragColor = color;
}

```

As you can see, it seems to work for the most part, but the aliasing on the outline is really bad.

Does anybody have any suggestions for smoothing the inner edge of the outline?

Should I be sampling the neighboring depth values of each pixel and scale the glow based on the number of depth values that equal 1.0?

Or is there a better approach that will produce smoother results?

# Answer
> 13 votes
Maybe instead of checking it against the low-resolution depth buffer you might use the stencil test. When rendering the normal scene, you just render the object that should glow into the stencil buffer (without depth-testing, I think) and then blend the complete glow texture in, but configure the stencil-test to only pass where the stencil buffer is not set, therefore masking out the high-resolution object.

This way you get the exact silhouette of the original object, whereas a smoothing of the edges would only lead to approximate results, but maybe these would suffice for you.

---
Tags: opengl, shaders, glsl, glow
---


# Question
Title: What are the implications of not owning the IP of a character graphic in my game?
I'm currently talking with a design studio for the artworks of my game. They are saying they want to still own the IP of their chracter graphic in my game as they want to sell merchandise with my character idea and their artwork.

I'd like to know what kind of stuffs should I look out for in such an agreement. Does owning the character graphics mean, later they can come up and say me I can't use it in my game?

# Answer
Hire an attorney.

There is no substitute to having some actual legal advice, especially in an instance like this. No one here can give you the advice you *need*.

Business folks who are after a contract over "IP" are usually looking for a way to screw you over. You need an attorney to help you avoid losing your rights.
> 22 votes

# Answer
Ownership gives someone the right to decide who can use something. Allowing someone to use property you own is called a licence. If you get a licence to use the item that they own, you can use it. If you don't, you can't. Any exceptions to that will depend on the precise legal issues in your country, their country, and the relative skills of your lawyers. But the only way you will be sure about what you can use is to either (a) own it, or (b) get a licence from the owner that tells you exactly what you can do with it.
> 2 votes

# Answer
Looks to me like they create the artwork and own everything, but you buy the right for like one game. So if you have the right contract they cannot say you can't use it in your game, but any later game they can say that. And you probably will have to buy the rights again for any later game. But this is all in what you sign. If the contract say you can use the caracter in all later games and they have the rights for any other merchandise - then that's the agreement.

I'd say just read and understand the contract before signing...
> 0 votes

# Answer
As far as I understand it, you have the IP of that character without the graphics, and they have the IP of the graphics without any reference to your character. So, if they want to sell merchandise, you might want to profit from your property and decide where and how it will be used.

Think about your well crafted character with its character name and all the effort you put into that character creation and the graphics you used in a sexual offending picture on a good selling cheap t-shirt. Your game will be disliked and they make money out of it.

If you do not have the exclusive rights of using those graphics, then think about why you want to pay for it at all: They still could give those artwork away for free to anyone, right after selling them to you for big money.

Compare it to this:

1. You buy the exclusive rights.
2. You sell them some rights back, where you can prevent them to abuse your property.
> 0 votes

# Answer
You should also consider if they're able to sell the artwork at a later stage. What if your game is a success and they decide to sell your characters to a rival company. Or hold you to ransom for your sequels. Contracts for these things need to be very, very specific; there's no room for ambiguity within a contract like that, if the terms can be interpreted in more than one way then you could have a fight on your hands in the future. And as greyfade said, the only way to do that the contract is clear, concise and far to both parties is hire a lawyer yourself to go through the contract. It's money well spent.
> 0 votes

---
Tags: legal
---


title: Connecting an AI Agent to a Flash Game

text:
# Question
Title: Connecting an AI Agent to a Flash Game
## Overview

The game is a multiplayer simple real time strategy housed in a Flash application. Players run the Flash client, and are connected to a server written in another language (the language is irrelevant). Players compete against one another in games of 2~8 players.

My aim is create some way for people to create an AI agent to play in the same realm against human players, or other AI agents. Akin to the Broodwar AI competitions, but in a much simpler game.

---

## The current model

has players logging in to the lobby. Games seeking players are listed in the lobby. Once the game acquires the amount of players required to start (defined by the host at game room creation time), the players are then pushed into a game, and leave the lobby. Games then run through to completion; players who disconnect are left stagnant until destroyed or they login again and are reconnected to the game.

---

## In a perfect world

the flash client (Using an MVC type model) would be able to interface in some way with the users AI agent, handing data to the agent, and receiving commands from the agent. In this way the user could observe the game in the flash client while in play, as well as choose games for the agent to participate in. This model would be ideal for debugging purposes, as to not interrupt play on crash, and since commands can only be sent (with malformed commands being ignored, with an error callback) users could pick out major bugs quickly.

---

## However

flash is a prissy little nitwit when it comes to communicating client side to client side. The only *realistic* options I can see would be to create a second client interface in another language (say .Net) that would be used to interface the AI agent, the player would then login to the flash client and enter games/observe in the above mentioned manner. OR the flash client would create a second socket pointed at the local host. A suitable API would be created to manage the communication protocol (as a DLL or similair) that would handle all data values of the game, and sending commands. This API would be extended by the users AI agent, and the player would login to the flash client and join/observe games.

---

## The Big Question:

From experience or observations, what would be the most suitable model for this type of a system? I have no qualms with either, but due to the long timeframe of implementing each system (I work alone) I'd rather start off on the right path, and end up with an easy to use model. Any suggestions at all are very welcome!

# Answer
> 1 votes
So your goal is to provide an interface for developers to plug their AI on your game system. Depending on how much freedom you want to provide to those developers, you have several options.

1. For the largest freedom, do not provide anything but a comprehensive **documentation of your network protocol** as well as a set of IP to connect to (and maybe a test server).

Using that approach, third-party developers are free to develop an AI in any language they are the most comfortable with, as soon as it supports sockets. On the downside, your server have to be quite secure and stable to avoid cheating and attacks. But that should be the case anyway.
2. For almost as much freedom, provides **a library** that allows to connect and interact with your game server. If you want to stick to Flash, you can give the developers an SWC. This way, they could create their own Flash app, that connects and interact with your game server using your library.

This is maybe more flexible, since you can update the library when changing your network protocol, without breaking the third-party applications (or at least, with giving them a quite easy way to update, compared to a random change in the protocol).
3. You could also set up your game client so it will be able to read **client-side scripts**. For example, you could use LUA. This way, you are really sandboxing the third-party code on your very own game client, and you keep all control over the API you'll be providing.

If you'd like to specify your request more deeply, I'd be happy to update the answer with more details.

# Answer
> 1 votes
You could probably use flash.net.LocalConnection for this. This would allow you to implement an API where other flash files can connect to and run commands locally.

What this means is, that you'll have your game client (running in the browser) which exposes methods through `LocalConnection`. Somebody that implements an A.I. for your client could either run an Adobe AIR application, or another SWF file in the browser that connects to your `LocalConnection` and issues commands over it.

This could get cumbersome with lots of exposed methods and requires really good documentation, so that somebody can work with your API.

Another option would be to expose a RESTful web API, that any client can connect to. So the A.I. could be implemented in any language that can issue an HTTP-request.

---
Tags: networking, ai, flash, socket
---


# Question
Title: How to stretch and rotate an image between two points in cocos2d?
I have an arrow image. I want to stretch this image between two given points. I'm retrieving the points from touch locations, so they aren't fixed. When the user touches the iPad, the arrow image should appear and be shown until the touch ends. So if the user touches point A and is moving his finger to point B, the arrow image will be stretched from point A to point B and so on.

How can I achieve that?

# Answer
First you need to compute the distance between points A and B, then you have stretch the arrow to this value. After that compute the angle between A and B, and rotate arrow with this.

The last operation is positioning the arrow. If origin of the picture is in the center, you must place it at the (A+B)/2 point.
> 1 votes

# Answer
I'm writeing this code in c++ since I'm working with cocos2d-x but you just have to translate this code to Obj-c:

```
ccPoint a,b;

image->setposition(ccp((a.x + b.x) / 2, (a.y + b.y)/2));
image->setrotation(atan2(a.y-b.y,a.x-b.x));

float dist = sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
dist = dist / image->boundingbox().size.width;

image->setscale(dist);

```
> 0 votes

---
Tags: cocos2d-iphone, ipad
---


# Question
Title: Why does my game freeze when I try and display a menu?
I make a `MenuScene` when my Game loads, which grabs some intro text from `levelData` and displays it and a button to start playing the level. When the `MenuScene` is created and displayed in `onLoadComplete()` it's fine. However when I display it again when advancing the level (`levelData` is loaded with new data and the `MenuScene` reset) it freezes, showing the game at the point the level was beaten. The menu is not displayed at all. I'm just calling

```
loadIntro();
this.mScene.setChildScene(this.mIntroScene, false, true, true);
this.mEngine.stop();

```

to display the `MenuScene` (the same both times, it works the first time but not the second), where `loadIntro()` is

```
private void loadIntro() {
            this.mIntroScene = new MenuScene(this.mCamera);

            final TextMenuItem intro = new TextMenuItem(-1, mFont, levelData.getIntroText());
            intro.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
            intro.setSize(400, 150);
            this.mIntroScene.addMenuItem(intro);

            final SpriteMenuItem startMenuItem = new SpriteMenuItem(MENU_START, this.mMenuStartTextureRegion);
            startMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
            this.mIntroScene.addMenuItem(startMenuItem);

            this.mIntroScene.buildAnimations();
            this.mIntroScene.setBackgroundEnabled(false);
            this.mIntroScene.setOnMenuItemClickListener(this);

    }

```

What am I doing wrong?

# Answer
Is it possible to use a separate thread for the game action? I'm wondering if the menu being activated is consuming the current thread (this is a guess based on my experience in programming applications in Java that use menus).

I suspect that what's going on is that you have one main thread, and that by activating the menu your code is temporarily halted while the user decides what to do with the menu.
> 4 votes

---
Tags: android, andengine
---


title: XNA: Texture2D.GetData runtime error

text:
# Question
Title: XNA: Texture2D.GetData runtime error
I am trying to get the colors of the top left pixel in an image, I use this code:

```
 using (FileStream stream = File.OpenRead(animationFile))
 {
     animation = Texture2D.FromStream(graphicsDevice, stream);
 }

 Color[] animationData = new Color[1];
 animation.GetData<Color>(animationData, 0, 1);

```

When i run it I get an System.Argument exception saying: The date passed in is too large or too small for this resource"

Anyone know what I'm doing wrong?

Edit: Added code where i load the texture, I have also tried using the Content.Load method, but the result was the same.

# Answer
I don't know why that error is getting thrown, but here is a solutions that works.

```
Color[] animationData  = new Color[1];
animation.GetData<Color>(0,new Rectangle(0,0,1,1),c, 0, 1);

```

We are creating a 1x1 rectangle, and only sampling data from that.

**update**

Ok, I have had some time you look into this more, and I *think* there *may* be a bug in the framework. When you are doing `Texture2D.GetData<T>(T[] data, int start, int length)` it is just an overload for `Texture2D.GetData<T>(int level, Rectangle? rect, T[] data, int start, int length)` and passes in *null* for the rectangle. If you manually do that (ie. pass in null instead of the 1x1 rectangle) you get the same error.

Now, follow the chain down, and it eventually calls

```
private unsafe void CopyData<T>(int level, Rectangle? rect, T[] data, int startIndex, int elementCount,...)

```

This method is way to long to post here (over 220 lines of code in ILSpy), and since I don't have the whole picture it is hard to figure out. However, this little bit is interesting.

```
tagRECT* ptr2 = null;
Rectangle rectangle = default(Rectangle);
if (rect.HasValue)
{
  rectangle = rect.Value;
  ptr2 = ref rectangle;
  if (ptr2 != null)
  {
    *(int*)(ptr2 + 8 / sizeof(tagRECT)) = *(int*)(ptr2 + 8 / sizeof(tagRECT)) + *(int*)ptr2;
    *(int*)(ptr2 + 12 / sizeof(tagRECT)) = *(int*)(ptr2 + 12 / sizeof(tagRECT)) + *(int*)(ptr2 + 4 / sizeof(tagRECT));
  }
}

```

See how `ptr2` is only defined if you passed in a value for the rectangle? Further down the trail (if I followed the correct code path)

```
num5 = <Module>.D3DXLoadSurfaceFromSurface(ptr3, null, (tagRECT*)ptr2, ptr5, null, (tagRECT*)ptr2, 1, 0);

```

and then later we are doing some recursion based on `if num5>=0`. Which recursive cal is actually determined on some other logic I haven't worked out, but I don't think that part matters...famous last words, right? :)

So all that to say this, I don't think that the Rectangle passed is is *supposed* to be null. A few places in the code it looks like they are trying to force the rectangle to have a value of the texture size. Perhaps it isn't working.

Take all of that with several grains of salt. I am in not way qualified as a low level GFX programmer. Maybe someone else here can answer for certain.
> 2 votes

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


title: Drawing slope lines in a confined space

text:
# Question
Title: Drawing slope lines in a confined space
This isn't a game development question *per se*, but here goes...

I have a 50x50 pixel space in which I need to draw five lines: X and Y axes, and one line for each of a `steepest`, `average`, and `flattest` slope.

I'm working with (Java) code that was handed down to me with no documentation or commentary and I've never worked with drawing on a canvas before. Here's the code for a box that measured 175x75 px. This needs to be adapted for a 50x50 area as described above.

```
    DrawingArea canvas = new DrawingArea(175, 75);
    canvasContainer.add(canvas);
    Rectangle rectangle = new Rectangle(0, 0, 174, 75);
    canvas.add(rectangle);
    Line slopeMainLineX = new Line(5, 70, 170, 70);
    slopeMainLineX.setStrokeOpacity(0.5);
    canvas.add(slopeMainLineX);
    Line slopeMainLineY = new Line(40, 70, 40, 0);
    slopeMainLineY.setStrokeOpacity(0.5);
    canvas.add(slopeMainLineY);
    steepestLine = new Line(40, 70, 0, 0);
    steepestLine.setStrokeWidth(3);
    canvas.add(steepestLine);
    avgSlopeLine = new Line(40, 70, 0, 0);
    avgSlopeLine.setStrokeWidth(2);
    canvas.add(avgSlopeLine);
    flattestLine = new Line(40, 70, 0, 0);
    flattestLine.setStrokeWidth(1);
    canvas.add(flattestLine);

    int steepestAngle = Math.round(site.getSlope().getMax());
    int averageAngle = Math.round(site.getSlope().getAvg());
    int flatestAngle = Math.round(site.getSlope().getMin());

    double xPointSteepestAngle = 40 + 120 * Math.cos(steepestAngle*0.0174532925);
    double yPointSteepestAngle = 70 + 120 * Math.sin(steepestAngle*0.0174532925);
    double xPointAverageAngle = 40 + 120 * Math.cos(averageAngle*0.0174532925);
    double yPointAverageAngle = 70 + 120 * Math.sin(averageAngle*0.0174532925);
    double xPointFlatestAngle = 40 + 120 * Math.cos(flatestAngle*0.0174532925);
    double yPointFlatestAngle = 70 + 120 * Math.sin(flatestAngle*0.0174532925);

    steepestLine.setX2((int) xPointSteepestAngle);
    steepestLine.setY2(70 - ((int) yPointSteepestAngle - 70));

    avgSlopeLine.setX2((int) xPointAverageAngle);
    avgSlopeLine.setY2(70 - ((int) yPointAverageAngle - 70));

    flatestLine.setX2((int) xPointFlatestAngle);
    flatestLine.setY2(70 - ((int) yPointFlatestAngle - 70));

```

I'm completely lost here, so any help would be greatly appreciated.

# Answer
> 5 votes
Replace some constants, it might help understanding what happens:

```
0.0174532925 => Math.PI / 180.0
175 => MyCanvas.width
75 => MyCanvas.height
174 => MyCanvas.width - 1
74 => MyCanvas.height - 1
5 => MyCanvas.padding
170 => MyCanvas.width - MyCanvas.padding
70 => MyCanvas.height - MyCanvas.padding
40 => (MyCanvas.height - MyCanvas.padding) / 2 + MyCanvas.padding
120 => MyCanvas.slopeLineLength /* About 40 */

```

Alternatively, to make the horizontal line centered, replace the following value:

```
40 => MyCanvas.height / 2 /* 37.5 in original, not 40.0 */

```

~~Finally, you can calculate the slope line length instead of setting it (to about 50 if you don't want the lines to be too long):~~

~~```
120 => Math.sqrt(
                   (MyCanvas.height / 2 - MyCanvas.padding)
                   * (MyCanvas.height / 2 - MyCanvas.padding)
                 + (MyCanvas.width - MyCanvas.padding * 2)
                   * (MyCanvas.width - MyCanvas.padding * 2))

```~~

EDIT: Scratch the last part, obvious brain fart on my side. You should just pick a value between `(MyCanvas.height - 2 * MyCanvas.padding) / 2` and `(MyCanvas.width - 2 * MyCanvas.padding)` for `MyCanvas.slopeLineLength`.

---
Tags: java, html-canvas
---


# Question
Title: How do I show the current view from the viewport on my map?
I'm doing HTML5 Canvas development and currently have a large viewport (on the left) and a map (on the right). Like this:

I need to show on the map what is currently being viewed in the left. And I'm at a lost on how to calculate this. This is how I want it to be:

I am manipulating the main viewport via a transformation matrix. like \[1, 0, 0, 1, 0, 0\]

This is decently common functionality in different games and apps. So I assume there are resources on how to do it. But I haven't been able to find any.

# Answer
> 1 votes
I'm going to assume the following:

* you wish to do something like you posted in Picture Nr. 2.
* you have the relative position of the viewport in Space (x,y)
* the map on the right is static and depicts the entire space

I'll call the Main (left) Camera/viewport "View", the right one "Map" and the red Rectangle marking the position on the Map as "Rect". and I'll use some pseudo language as I'm no HTML5 Expert.

```
Rect.left   = (View.x / TotalSpaceWidth) * Map.Width
Rect.top    = (View.y / TotalSpaceHeight) * Map.Height
Rect.right  = Rect.left + View.Width / TotalSpaceWidth
Rect.bottom = Rect.top - View.Height / TotalSpaceHeight

```

If your Map on the right is not Static, you will need to adjust the above by the corresponding offsets.

To incorporate rotations, simply rotate the Rect by the given angle.

I hope this was what you were looking for

---
Tags: maps, html5, html-canvas
---


title: GLSL woes involving texturing

text:
# Question
Title: GLSL woes involving texturing
I'm a beginner to OpenGL and GLSL especially, and I'm having a lot of trouble getting textures to display via shaders. My shader code compiles without any warnings or errors, but I seem completely unable to render my texture. In fact, nothing's being rendered at all; I'm getting a blank screen. Here's my current, simplified code (written in D, but should function almost exactly as it looks as if it were in C++):

```
int main(string[] argv) {
    try {
        ilInit();
        iluInit();
        ilutInit();                 // GOTCHA: These two calls need to be in order!
        ilutRenderer(ILUT_OPENGL);  //
        glfwInit();
        if(SDL_Init(SDL_INIT_VIDEO) > 0) writeln("ERROR");

        // Create an OpenGL context and window.
        const int VWIDTH = 1600;
        const int VHEIGHT = 900;
        const int WIDTH = 1280;
        const int HEIGHT = 720;
        glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 8);
        glfwOpenWindowHint(GLFW_AUX_BUFFERS, 1);
        glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
        glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
        glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_FALSE);
        glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
        glfwOpenWindow(WIDTH, HEIGHT, 8, 8, 8, 8, 0, 0, GLFW_WINDOW /+ GLFW_FULLSCREEN +/);

        GL.bindClassicVersions(true);
        GL.bindModernVersions(true, GLVersion.GL33);
        GL.bindExtensions(true);    // Returns GL_INVALID_ENUM

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, VWIDTH, 0, VHEIGHT, -100, 100);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        // Set clear color
        glClearColor(0.392, 0.584, 0.929, 1);

        // Set GL enables/disables
        glShadeModel(GL_SMOOTH);                                // Enables smooth shading
        glEnable(GL_TEXTURE_2D);                                // Enable 2D texturing
        glEnable(GL_BLEND);                                     // Enable alpha blending
        glDisable(GL_DEPTH_TEST);                               // Disable depth testing
        glDisable(GL_CULL_FACE);                                // Disable face culling
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        //glDepthFunc(GL_LEQUAL);                                 // The depth test type

        // Initialize and compile shaders
        GLuint vertShaderId, fragShaderId;
        vertShaderId = glCreateShader(GL_VERTEX_SHADER);
        fragShaderId = glCreateShader(GL_FRAGMENT_SHADER);

        immutable(GLchar)* vertShaderSrc = toStringz("#version 330
in vec3 vertex;
in vec2 texCoord;

out vec2 fragmentTexCoord;

void main(void) {
    fragmentTexCoord = texCoord;
    gl_Position = vec4(vertex, 1.0);
}
");
        immutable(GLchar)* fragShaderSrc = toStringz("#version 330
uniform sampler2D firstTexture;
in vec2 fragmentTexCoord;

layout(location = 0, index = 0) out vec4 fragColor;

void main(void) {
    fragColor = texture2D(firstTexture, fragmentTexCoord);
}
");

        glShaderSource(vertShaderId, 1, &vertShaderSrc, null);
        glShaderSource(fragShaderId, 1, &fragShaderSrc, null);

        glCompileShader(vertShaderId);
        tge.shader.Shader.checkCompileLog(vertShaderId);
        glCompileShader(fragShaderId);
        tge.shader.Shader.checkCompileLog(fragShaderId);

        GLuint programId = glCreateProgram();

        glAttachShader(programId, vertShaderId);
        glAttachShader(programId, fragShaderId);

        glLinkProgram(programId);
        tge.shader.Shader.checkCompileLog(programId);

        glUseProgram(programId);
        checkGLError();

        // Load texture
        auto texture = new Texture2d(r"res/test.png");
        texture.load();

        bool running = true;
        clearGLError();
        while(running) {
            // Clear viewport
            glClear(GL_COLOR_BUFFER_BIT);

            // Bind texture ID
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, texture.textureId);
            checkGLError();

            // Set texture uniform value
            auto loc = glGetUniformLocation(programId, "firstTexture");
            checkGLError();
            glUniform1i(loc, 0);
            checkGLError();

            // Render
            glBegin(GL_QUADS);
                glTexCoord2d(0, 0); glVertex2d(-0.8, -0.8);
                glTexCoord2d(1, 0); glVertex2d( 0.8, -0.8);
                glTexCoord2d(1, 1); glVertex2d( 0.8,  0.8);
                glTexCoord2d(0, 1); glVertex2d(-0.8,  0.8);
            glEnd();
            checkGLError();

            // Swap front and back rendering buffers
            glfwSwapBuffers();

            // Add a tiny delay if no work is being done in the loop.
            //glfwSleep(double.epsilon);

            // Check if ESC key was pressed or window was closed
            running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED);
        }
    }
    catch(Throwable t) {
        Logger.log(Severity.Error, t.msg);
    }

    return 0;
}

```

I'm guessing it's something simple I've overlooked due to being new. Any help would be appreciated!

# Answer
> 2 votes
One thing I noticed is that you commented out the actual color finding procedure:

```
    //fragColor = texture2D(firstTexture, fragmentTexCoord);
    fragColor = vec4(1, 0, 0, 1);

```

Another Problem:

```
    glVertex2d(-1, -1); glTexCoord2d(0, 0);

```

should be:

```
    glTexCoord2d(0, 0); glVertex2d(-1, -1);

```

in all the lines

---
Tags: opengl, glsl
---


title: Tile based game engine for WP7?

text:
# Question
Title: Tile based game engine for WP7?
I showed my friend a demo of what I was doing with the farseer physics engine on the windows phone and he wanted to know if farseer would be good for a game he wants to develop. It's a tile based game so I said I don't think farseer would be the best choice (correct me if i'm wrong).

Are there any tile game engines for windows phone? Think tile based like the original Zelda.

# Answer
> 3 votes
Farseer is a physics engine, **not** a game engine. Which one is he looking for?

If he is looking for a game engine check out FlatRedBall. Alliteratively, if he is looking for something help create the maps, check out tIDE. It has a UI for laying down tiles, and a "engine" component to draw them in your game.

If he wanted, he could even mix the two. Use FRB for the screen management, GUI, etc... and use tIDE to help draw the maps. There is really no reason why that can't be done.

---
Tags: windows-phone-7
---


# Question
Title: Why is programmable pipeline( GLSL ) faster than fixed pipeline?
So I'm teaching myself GLSL and am trying to figure out why it's suppose to be faster than the fixed function pipeline.

The reason I am having a problem is that from my understanding , the shaders you create are replacing sections of the pipeline that were there before. So, how's simply providing your own version speeding things up?

The only thing I can think is if you tried to supply say your own lighting equation before, you would have to do the calculation on the CPU, but now you can do the calculations on the GPU which will be faster.

Am I understanding this correctly?

# Answer
> 28 votes
Shaders you create aren't going to be your own version of fixed-function pipeline(FFP), but a custom vertex- and pixel-manipulating operations to achieve something cool and complex.

Many things you do via programmable pipeline(PP) will work faster than their possible FFP implementations, because PP reduces the number of passes or amount of combiner and cubemap magic required to render these hypothetical things in FFP.

Imagine implementing such a common thing as per-pixel lighting in FFP with only interpolated vertex data and sample texture in your hands. It's not even possible to do it "honestly", only hacks for special cases depending on faithful precalculated cubemaps and some serious blending. With PP it becomes a matter of colorizing a dot product between light direction and vertex normal.

All in all, PP turns slow and impossible into fast and possible. But if you decide to write a shader to implement the same algorithms used in FFP, you would find out that FFP will be slightly faster because it's very hardware-optimised.

# Answer
> 15 votes
In theoretical terms the programmable pipeline is slower than the fixed function pipeline. No general purpose processor can compete with a special case processor. The original fixed function pipeline was little more than a bunch of logic gates in a line which is as fast as theoretically possible.

However, these days the programmable pipeline is the norm. So the hardware is instead geared towards the programmable pipeline. Having lost the initial efficiencies of having a circuit specifically created for one certain data flow, it must accommodate the most common case, which is the shader-based approach. However for backwards compatibility options, the fixed function pipeline is still made available - but the cost is that the old fixed functions have to be transated into shaders, which may well incur a cost. This would explain the performance difference.

# Answer
> 1 votes
The main reason I could think of is a phase in fixed pipeline, that your program doesn't need it. for example image a game where all lights are static, you can easily implement a shader that doesn't even try calculating for dynamic light. in this case you shader runs faster than a precompiled shader that is checking some equations for dynamic light (a general purpose shader). there are other examples too, you can easily think of many aspect that should be considered for a fixed pipeline but you can ignore implementing in your own GLSL codes.

# Answer
> 1 votes
That's it exactly, your shaders are replacing parts of the pipeline. But often your shaders are specialized towards a specific effect you want to achieve and don't handle every possible special feature that might be activated, therefore being simpler than a shader that emulates the complete fixed-function pipeline. Whereas the fixed-function path has to take into acount many things and OpenGL features you might just not want to use (or haven't even heard about).

And the days where you had the fixed-function done in special hardware (opposite to a fully programmable hardware) are over, what probably happens when you use the fixed-function pipeline is, that your driver just loads its own special shaders that implement the fixed-function paths. But these might be very complex, to provide each and every feature the fixed-function pipeline offers.

---
Tags: opengl, glsl
---


# Question
Title: How can I rotate a Texture2D into / out of the screen?
I am drawing a Texture2D onto the screen and have the need to rotate the texture forward, in a 3D way. I'm using the SpriteBatch Draw() method and it only allows limited 2D rotation around the Z axis. From tons of research online I have boiled down the solution to passing either an effect or matrix to SpriteBatch's Begin() method; however, after many hours of trial and error I haven't come up with anything working.

# Answer
> 1 votes
I sort of got it. Maybe with some tweaking you can get it the rest of the way.

first in the **Update**, I get the amount to rotate by

```
var ks = Keyboard.GetState();

if (ks.IsKeyDown(Keys.Down))
    xAxis += 1f;
if (ks.IsKeyDown(Keys.Up))
    xAxis -= 1f;

Xtransform = Matrix.CreateRotationX(MathHelper.ToRadians(xAxis));

```

then create an effect and apply the transformation. The `Matrix.CreateOrthographicOffCenter` is just to position our camera. It is assuming a 800x600 screen. We then multiply it by our rotation transform.

```
BasicEffect e = new BasicEffect(GraphicsDevice);
e.World = Matrix.Identity;
e.View = Matrix.Identity;
e.TextureEnabled = true;
e.Texture = sprite;
e.Projection = Matrix.CreateOrthographicOffCenter(0, 800, 600, 0, 0, 1) * Xtransform;

```

Now in **Draw** just apply the effect to the SpriteBatch.Begin method (using the 4th overload). I say it sort of works because it only rotates TOWARDS the screen. It disappears when you rotate away. The picture below shows what it looks like before (top) and after (bottom). This is what you wanted, right? I know it just looks squished, but it is a 2d texture. It isn't meant to bend that way :)

---
Tags: xna, spritebatch
---


# Question
Title: Am I going to regret using a color based collision detection system?
I'm just getting started build my first game with XNA (I'm experienced with C# but not games).

I'm building a pretty simple top down 2d shooter. I read this tutorial on using a color based collision system and it sounded really cool to me. http://www.xnadevelopment.com/tutorials/theroadnottaken/theroadnottaken.shtml

It means I can quickly make levels just using any graphics program and not have to define my scenery (walls, trees etc) in terms of collision boxes etc right?

However I can see that going down this path means that perhaps the calculation for determining whether fast moving objects like bullets intersect walls etc becomes more difficult potentially because you cant' do basic geometry intersection type calcs.

Is that right? Am I going to regret going in this direction if my game gets more complex over time? Worth just investing in the creation of a level editor to define my scenery in terms of geometry?

Any advice for a noob very much appreciated!

# Answer
> 6 votes
You're spot on with your observations regarding the capabilities of a bitmap based collision approach.

This method provides a really easy way to edit your levels with any program that can output a bitmap (any image editing program). This system is also really flexible when you want to define different types of ground. Say `green` for mud, and `red` for a solid underground. You then easily query the current pixel and determine the type of underground the player stands on. Even ramps (gradients from ground type A to B) are possible without much problems.

Problems arise with collision detection. It's easy to detect an intersection with another object (just do a pixel-test), but it's hard (computationally expensive) to find out what orientation the object you collided with has. This is especially important when you need a surface normal to deflect objects correctly.

Also really fast moving objects can be an issue, especially if you have thin (eg. 1 pixel wide) objects to collide with. There's this question that covers this topic already.

In the end it all depends on what kind of game you want to create and what resolution (in terms of collision detection/resolving) you need. The bitmap based approach works best, when a large portion of your world is static. But it also allows you to implement stuff like destructible levels quite easily.

Since you didn't mention the type of game you want to create, it's now up to you to decide whether or not a bitmap-based collision approach would be beneficial for your game. Good luck.

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


title: Is Tetris public domain?

text:
# Question
Title: Is Tetris public domain?
is the concept for Tetris in the public domain or is there someone who is still collecting royalties on the concept? I mean, if I were to write a variant of Tetris would I owe somebody some money? Thanks.

# Answer
The game, name, and all associated works of Tetris are owned and trademarked by The Tetris Company.

The concept of tetrominos, however, are not owned by anyone. Though The Tetris Company's website indicates the term 'Tetriminos' is in fact trademarked.

Whether you can create a clone of Tetris under another name is certainly up for debate. Recently a 'Tetris-clone' named Blockles was removed after litigation from the Tetris Company was brought against it. I have not been able to find the game in question to see just how close to the original Tetris game it was.
> 32 votes

# Answer
Tetris has been programmed in 1984 and sold commercially ever since. Since his author is not dead yet (I think), and certainly not dead for 70 years, it's definitely not in the public domain.

It's not an abandon-ware either because there's at least one company that claims to have the rights and wants to make money out of it. Now, as to who really owns the rights, that's highly questionable, as you can see in the Wikipedia article.
> 5 votes

---
Tags: legal
---


# Question
Title: GLSL - Rewriting shaders from #330 to #130
I recently created a game (LD21) that uses a geometry shader to convert points into textured triangles/culling. Since I was under the impression that the support for #330 was widespread I only wrote #330 shaders, but it seems that a lot of not so old hardware only support #130 (according to GLView)

Now, since I'm only familiar with the #330 core functionality I am having trouble rewriting my shaders to #130. The fragment shader was quite trivial to rewrite, but I've only managed to get my vertex and geometry shader down to #150.

So, is it possible to rewrite the shaders, or would it require a lot of changes in my rendering engine?

# Geometry shader

```
#version 150
layout(points) in;
layout(triangle_strip, max_vertices = 4) out;
uniform mat4 oMatrix;
in VertexData
{
    vec4 position;
    vec4 texcoord;
    vec4 size;
} vert;

out vec2 gTexCoord;

void main()
{
    if(vert.position.x>-4f && vert.position.x<4f && vert.position.y>-2f && vert.position.y<2f)
    {
        gTexCoord=vec2(vert.texcoord.z,vert.texcoord.y);
        gl_Position = vert.position + vec4(vert.size.x,vert.size.y,0,0);
        EmitVertex();

        gTexCoord=vec2(vert.texcoord.x,vert.texcoord.y);
        gl_Position = vert.position + vec4(0.0,vert.size.y,0,0);
        EmitVertex();

        gTexCoord=vec2(vert.texcoord.z,vert.texcoord.w);
        gl_Position = vert.position + vec4(vert.size.x,0.0,0,0);
        EmitVertex();

        gTexCoord=vec2(vert.texcoord.x,vert.texcoord.w);
        gl_Position = vert.position;
        EmitVertex();

        EndPrimitive();
    }
}

```

# Vertex shader

```
#version 150
#extension GL_ARB_explicit_attrib_location : enable

layout (location = 0) in vec2 position;
layout (location = 1) in vec4 textureCoord;
layout (location = 2) in vec2 size;
uniform mat4 oMatrix;
uniform vec2 offset;
out VertexData
{
    vec4 position;
    vec4 texcoord;
    vec4 size;
} outData;

void main()
{
    outData.position = oMatrix * vec4(position.x+offset.x,position.y+offset.y,0,1);
    outData.texcoord = textureCoord;
    outData.size = oMatrix * vec4(size.x,size.y,0,0);
}

```

# Answer
First of all, you won't be able to use `struct`s for varying data (changed by 1.50), but you still can use `in` and `out` instead of `attribute` and `varying`. Additionally you have to write into the builtin variable `gl_Position` in the vertex shader (changed by 1.40). So in your vertex shader substitute the declaration of `outData` with something similar to

```
out vec4 texcoord;
out vec4 vSize;       //size already used

```

and use `gl_Position` instead of `outData.position`.

I'm not sure if the ARB\_explicit\_attrib\_location extension is already core, so maybe you have to add

```
#extension ARB_explicit_attrib_location : require

```

to use the `layout` syntax or just set the attribute locations in the application by calling `glBindAttribLocation` before linking the shader, if this extension is not supprted.

In the geometry shader change the decralation of vert to something like

```
in vec4 texcoord[];      //names have to match vertex shader, of course
in vec4 vSize[];

```

Although you only get a single input (as you're using points), they still have to be arrays, I think (although always index with `[0]`, when used). Change the use of `vert.position` to `gl_PositionIn[0]`.

Next, I think the `layout` syntax for the geometry shader has been introduced in 1.50, so you might have to set the geometry shader layout in the application by means of `glProgramParameteri`.

I have to admit, that I have not much practical experience with geometry shaders or the modern syntax, as I still sit on 2.1 hardware, but all these changes can be deduced by looking into the respective specifications. Just look at the shader info logs if compilation (or linking) fails to gain some hints about what could be wrong.

The missing of the `layout` syntax in both the vertex and the geometry shader are the only things that might require some small additions to your application code, but I'm not completely sure if they are really unsupprted, so try them last.

Also, feel free to update your question if I missed anything and the shaders still don't work, maybe this time with some error messages from the GLSL compiler.
> 5 votes

---
Tags: opengl, glsl
---


title: iOS custom memory allocator

text:
# Question
Title: iOS custom memory allocator
I'm about to start writing an iOS game and I'm going to use mainly C++/C for the core gameplay logic.

I really like pre-allocating everything in the game and try to avoid any dynamic allocations as much as possible. With my own C++/C code it's not a big deal. However there are some ObjC libraries which I'd like to re-use and I'm not sure how to inject my custom memory allocator to Cocoa based classes.

Is there any central 'inject point' in Cocoa where I can do that?

# Answer
> 4 votes
This is all highly theoretical but you may be able to use categories (Mac Developer Tips) to override NSObjects (Apple Developer) alloc and dealloc methods.

---
Tags: ios, objective-c, memory-efficiency
---


title: Network Message Format Specification

text:
# Question
Title: Network Message Format Specification
I'm working on a TCP turn multiplayer game.

I've read many tutorials and stuff, and they all said to use Async IO, but, none of than give practical examples on how to do it.

I was thinking that in every TCP data stream sent, the client would have to send who is he, and what he's doing. Is it really necessary? What's the best way to deal with host identifying? If I should deal with this at all...

Should I check in every message if he's who he's claiming to be? There's any comprehensive game packet analysis avaiable on the web? I think I would learn much from this kind of source.

EDIT: I'm doing a server/many-clients model.

Thanks, Julio Rodrigues

# Answer
Let me try answering that from positions of RTS (think of it as TBS where each turn is 100msec).

There is separate thread for receiving and sending messages, it has it's own buffer and is black-box to the rest of the game (the game should know nothing about protocol and format). The game sends commands to networking unit and receives complete commands as they are available and verified to be complete.

When networking unit receives a new message it appends it to buffer and checks if buffer has a complete command. That is why each message has a header specifying contents length and CRC. That is ASync part of it.

How to identify the host? That depends on your network layout, is peer-to-peer or centralized server or .. ? If you trust your clients to do the computations (not advised for serious gaming) then there's no host at all, Everyone trusts everyone to supply valid data. If you have a separate host (could be running as stand-alone task on one of players machines) - it does all the computations and clients act as terminals, doing only View-Controller roles.

**EDIT:**

We use TCP module from OverbyteICS (that is one more layer between the networking module and Net) and it does it for us, each time new connection is made it is assigned new "stream". So when message arrives we know the "stream" who sent it, but in networking module we keep remap table, so that in lobby all players have UIDs and in game all players are IDs 1..8 (again, game knows nothing about networking UIDs).

As for specific details I can't say how it's made inside OverbyteICS, but we have possibility to launch local server and 1-8 clients on the same PC (all having same IP 127.0.0.1) and they are all distinct in game, so this means OverbyteICS takes care of that.
> 3 votes

# Answer
This isn't necessarily an answer, but whenever I have network architecture questions, I refer to this wonderful document about how Unreal Engine does it:

http://udn.epicgames.com/Three/NetworkingOverview.html

It's way more than you need, but it's a great read and you'll likely be able to use concepts from it.
> 3 votes

# Answer
Async IO is just a general term for handling input and output. How to actually implement that depends entirely on the platform and language you're using. Usually the result is that you just set up a connection and then you have callbacks which get called when data arrives on the connection.

> I was thinking that in every TCP data stream sent, the client would have to send who is he, and what he's doing. Is it really necessary?

No, it's not necessary. TCP is a connection based protocol, between 2 end-points. For as long as the connection is up, you know it's the same person on the other end, so they only need to identify themselves once.

> What's the best way to deal with host identifying?

You can get the host's IP address and port from the network API you use, when connected. Again, how to do this depends on the API. A remote IP address and port pair is a unique identifier for incoming TCP connections.
> 1 votes

---
Tags: networking
---


title: Heuristic Calculation for pathfinder

text:
# Question
Title: Heuristic Calculation for pathfinder
I've been modifying a pathfinding example from XNA Pathfinding example as described in my previous question Link to question here I had an issue where the character moved kept moving back and forth in a line. John McD suggestion made the brilliant I alert the way that the Heuristic calculation so that any nodes on the existing path had a lower value.

From what I've debugged in the project the new calculation seems to work fine, despite that the problem still persists. I was wondering if I implemented the Heuristic method wrong.

This is the method which houses the A\* algorithm

```
/// <summary>
/// This Method looks at everything in the open list and chooses the next
/// path to visit based on which search type is currently selected.
/// </summary>
/// <param name="result">The node to be visited</param>
/// <returns>Whether or not SelectNodeToVisit found a node to examine
/// </returns>
private bool SelectNodeToVisit(out SearchNode result)
{
    result = new SearchNode();
    bool success = false;
    float smallestCost = float.PositiveInfinity;
    float currentCost = 0f;

    if (openList.Count > 0)
    {
        foreach (SearchNode node in openList)
        {
            currentCost = Heuristic(node);
            // The heuristic value gives us our optimistic estimate
            // for the path length, while any path with the same
            // heuristic value is equally ‘good’ in this case we’re
            // favoring paths that have the same heuristic value
            // but are longer.
            if (currentCost <= smallestCost)
            {
                if (currentCost < smallestCost)
                {
                    success = true;
                    result = node;
                    smallestCost = currentCost;
                }
                else if (currentCost == smallestCost &&
                    node.DistanceTraveled > result.DistanceTraveled)
                {
                    success = true;
                    result = node;
                    smallestCost = currentCost;
                }
            }
        }
    }
    return success;
}

```

This is the method which does the new Heuristic calculation

```
/// <summary>
/// Generates an optimistic estimate of the total path length to the goal
/// from the given position.
/// </summary>
/// <param name="location">Location to examine</param>
/// <returns>Path length estimate</returns>
private float Heuristic(SearchNode location)
{
    int Nodecost = 10;

    foreach (Point point in Currentpath)
    {
        if (location.Position == point)
            Nodecost = 7;
    }
    return location.DistanceTraveled + location.DistanceToGoal + Nodecost;
}

```

This is the method which adds the point to their respective list once

```
/// <summary>
/// This method find the next path node to visit, puts that node on the
/// closed list and adds any nodes adjacent to the visited node to the
/// open list.
/// </summary>
private void DoSearchStep(TileMap tileMap)
{
    SearchNode newOpenListNode;

    bool foundNewNode = SelectNodeToVisit(out newOpenListNode);
    if (foundNewNode)
    {
        Point currentPos = newOpenListNode.Position;
        foreach (Point point in level.OpenMapTiles(currentPos, tileMap))
        {
            SearchNode mapTile = new SearchNode(point,
                StepDistanceToEnd(point),
                newOpenListNode.DistanceTraveled + 1);
            if (!InList(openList, point) &&
                !InList(closedList, point))
            {
                openList.Add(mapTile);
                paths[point] = newOpenListNode.Position;
            }
        }
        if (currentPos == endPlace)
        {
            searchStatus = SearchStatus.PathFound;
        }
        openList.Remove(newOpenListNode);
        closedList.Add(newOpenListNode);
    }
    else
    {
        searchStatus = SearchStatus.NoPath;
    }
}

```

# Answer
Wait...

```
node.DistanceTraveled > result.DistanceTraveled

```

shouldn't that be:

```
node.DistanceTraveled < result.DistanceTraveled

```

Otherwise it's trying to pick tiles with a slightly longer path, no?
> 0 votes

---
Tags: c#, ai
---


# Question
Title: XNA - Use Mouse To Rotate & Arrow Keys To Scroll A Linearly Wrapped Texture:
Using XNA I'm working on my first, relatively simple, videogame for the PC.

At the moment my game window is 1024 X 768 and I have a 'Starfield' linearly wrapped background texture 1280 X 1280 in size whose origin has been set to its center point (width / 2, height / 2).

This texture is drawn onscreen using (graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2) to place the origin in the center of the window.

I want to be able to use the horizontal movement of the mouse to rotate my texture left or right and use the arrow keys to scroll the texture in four directions.

From my own related coding experiments I have found that once I rotate the texture it no longer scrolls in the direction I want, it's as if somehow the XNA framework's 'sense of direction' has been 'rotated' along with the texture.

As an example of what I've described above lets say I rotate the texture 45 degrees to the right, then pressing the up arrow key results in the texture scrolling diagonally from top-right to bottom-left. This is not what I want, regardless of the degree or direction of rotation I want my texture to scroll straight up, straight down, or to the left or right depending on which arrow key was pressed.

How do I go about accomplishing this? Any help or guidance is appreciated.

To finish up there are two points I'd like to clarify:

\[1\] The reason I'm using linear wrapping on my starfield texture is that it gives a nice impression of an endless starfield.

\[2\] Using a texture at least 1280 X 1280 in conjunction with a game window of 1024 X 768 means that at no point in it's rotation will the edges of the texture become visible.

Thanks for reading.....

Update # 1 - as requested by RCIX:

The code below is what I was referring to earlier when I mentioned '***related*** coding experiments'. As you can see I am scrolling a linearly wrapped texture in the direction I've moved the mouse relative to the center of the screen. This works perfectly if I don't rotate the texture, but once I do rotate it the direction of the scrolling gets messed up for some reason.

```
public class Game1 : Microsoft.Xna.Framework.Game
{

    GraphicsDeviceManager graphics;

    SpriteBatch spriteBatch;

    int x;
    int y;

    float z = 250f;

    Texture2D Overlay;

    Texture2D RotatingBackground;

    Rectangle? sourceRectangle;

    Color color;

    float rotation;

    Vector2 ScreenCenter;

    Vector2 Origin;

    Vector2 scale;

    Vector2 Direction;

    SpriteEffects effects;

    float layerDepth;

    public Game1()
    {

        graphics = new GraphicsDeviceManager(this);

        Content.RootDirectory = "Content";

    }

    protected override void Initialize()
    {

        graphics.PreferredBackBufferWidth = 1024;

        graphics.PreferredBackBufferHeight = 768;

        graphics.ApplyChanges();

        Direction = Vector2.Zero;

        IsMouseVisible = true;

        ScreenCenter = new Vector2(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2);

        Mouse.SetPosition((int)graphics.PreferredBackBufferWidth / 2, (int)graphics.PreferredBackBufferHeight / 2);

        sourceRectangle = null;

        color = Color.White;

        rotation = 0.0f;

        scale = new Vector2(1.0f, 1.0f);

        effects = SpriteEffects.None;

        layerDepth = 1.0f;

        base.Initialize();

    }

    protected override void LoadContent()
    {

        spriteBatch = new SpriteBatch(GraphicsDevice);

        Overlay = Content.Load<Texture2D>("Overlay");

        RotatingBackground = Content.Load<Texture2D>("Background");

        Origin = new Vector2((int)RotatingBackground.Width / 2, (int)RotatingBackground.Height / 2);

    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {

        float timePassed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        MouseState ms = Mouse.GetState();

        Vector2 MousePosition = new Vector2(ms.X, ms.Y);

        Direction = ScreenCenter - MousePosition;

        if (Direction != Vector2.Zero)
        {

            Direction.Normalize();

        }

        x += (int)(Direction.X * z * timePassed);

        y += (int)(Direction.Y * z * timePassed);

        //No rotation = texture scrolls as intended, With rotation = texture no longer scrolls in the direction of the mouse. My update method needs to somehow compensate for this.
        //rotation += 0.01f;

        base.Update(gameTime);

    }

    protected override void Draw(GameTime gameTime)
    {

        spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);

        spriteBatch.Draw(RotatingBackground, ScreenCenter, new Rectangle(x, y, RotatingBackground.Width, RotatingBackground.Height), color, rotation, Origin, scale, effects, layerDepth);

        spriteBatch.Draw(Overlay, Vector2.Zero, Color.White);

        spriteBatch.End();

        base.Draw(gameTime);

    }
}

```

# Answer
Yes, the "sense of direction" goes get messed up, but only because of how you are thinking about it.

Take your mouse, rotate it 90\* to the left, and then get your cursor to move to the top of the screen. Notice how you need to move your mouse to your left to get the cursor to move up? That is because your mouse doesn't change what "UP" is when you rotate it. You can do the same thing by leaving your mouse alone and rotating *yourself* around your desk. Move to the side. see how your mouse is rotated, but it isn't, right? you moved :)

I guess an easier way to think about it is two people are standing facing each other. The one says "Move Left" so the other one does. "No, not your left, **my** left".

OK, so how do you code around it? Well, unless there is some API I haven't heard about all you need to do is calculate the desired movement vector based off the current rotation.
> 2 votes

---
Tags: xna, c#, textures, rotation, mouse
---


title: Snake4d - a 4 spatial dimensional game

text:
# Question
Title: Snake4d - a 4 spatial dimensional game
I wrote a little 4 spatial dimension game, it's a 4D snake. The rule are the same as the game for the old Nokia cell phone - eat the food, don't cross yourself, don't go out of the borders.

What do you think of the idea? How do I make a better graphic of the UI? Do you have any suggestion? Like this actually seem a DOS game ...

Here is a little explanatory video: http://www.youtube.com/watch?v=8IUnqm8j4BE

And here there is a new version I did with OpenGL and C++: http://www.youtube.com/watch?v=NaeqUp3jbls

Moreover I have a question, which from the two representation above you like more? Or better, do you have any idea how to represent the 4 dimension at the best?

Btw any comments, suggestions, and questions are appreciated about the UI, the game concept, etc.

# Answer
> 3 votes
Some thoughts:

Your first video refers to Time when introducing your fourth dimension. *Time is not a spatial dimension* and, therefore, is a metaphor that will only serve to confuse your audience.

From a quick Google search, I wasn't able to find any useful information about how to render 4 spatial dimensions onto a 2D screen but there must be some out there. The math behind 3D -\> 2D is a right about at the limits of my mathematics mastery so I can't begin to postulate any effective ways to render an additional dimension. But, there's likely someone working on such research right now somewhere; you'll just need to find it.

The complexity of understanding movement between 4 dimensions is likely going to be beyond the grasp of much of your audience unless you spend a lot of time adjusting and catering to players through prototyping and playtesting. The difficulty of this dimensional leap is somewhat facetiously (but still applicably) addressed in this XKCD comic.

I'm not sure if you've heard of a game called Miegakure. It's a 4D platformer in which the player can shift between which 3 of the 4 spatial dimensions are visible/accessible. Unfortunately, the game is not yet released but there are some demo videos available on the game's site. Perhaps its approach to 4 dimensions could be helpful to you.

Good luck!

---
Tags: c++, opengl, 4d
---


# Question
Title: Other procedural material generators for Unity?
In the new version of Unity 3.4, unity announced that they would now support procedural materials (which is awesome, by the way). While I was researching it, I found this in the manual:

> Allegorithmic's Substance Designer can be used to create Procedural Materials, but there are **other applications** (3D modeling apps, for example) that incorporate the Substance technology and work just as well with Unity.

I don't have Allegorithmic's substance designer and don't plan on buying it soon. What other applications or 3D modeling apps can make procedural materials that work in Unity?

*Edit*: I found that Allegorithmic has a program called Player. But it is on Windows only. I'm on mac.

# Answer
> 2 votes
They emailed me.

> 3DS Max and Maya both use substance materials: http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=substance
> Take a look there for vids and tutorials.
> Unfortunately unity cannot import settings for substances edited in Max Maya at present, so you need to set them in both or use a dummy material in the source 3D package - I hope that helps!

---
Tags: textures, unity, procedural
---


# Question
Title: What are some easy to use 3D painting programs?
I'm looking for an (easy to use) "3D painting" program, a program that lets me load up a UV-mapped mesh, some textures and lets me 'paint' with those different textures.

Exactly like all those terrain painting programs (Unity 3D has one integrated for example) but for a generic mesh, not just a height map.

Cheap is better of course but ease to use is the most important.

Script support is a big plus though.

# Answer
> 4 votes
It's really easy to do on-surface painting with Blender: either 2.49b which has the better documentation, or 2.5 which has the vastly improved interface. I would check out the "Johnny Blender" tutorials on youtube for Blender in general, though I'm not sure if the guy who made them covers this particular topic.

And of course, it's totally free, and supports scripting through python, and there are tons of export scripts and so on out there for different formats eg. FBX.

# Answer
> 4 votes
Try out Sculptris \- free, easy to use, and can be used to create high-quality organic models as well.

# Answer
> 3 votes
There's mudbox. It's free if you're a student (non-commercial).

---
Tags: 3d
---


title: C++ Model loading API?

text:
# Question
Title: C++ Model loading API?
I'm looking for **the most** capable C++ model loading API.

So far I've found tons of ply, obj, and other such file format loaders. But the libraries I've found tend to load just **one** model type, and this requires you to learn quite a few api interfaces?

Is there One API To Load Them All, One API To Parse Them, One API To Bring Them All, And In the Vertex Buffer, Bind Them?

# Answer
> 9 votes
Assimp seems to be a good choice and I will be testing this with my next project. It supports a huge array of formats including supporting bones and animations. Not just for model loading, but for changing from format to format, computing vertex and face normals, splitting meshes, and triangulating polygons. It is available under the BSD license.

---
Tags: c++, models, loading
---


# Question
Title: To what platforms can the blender game engine build to?
I used to use the BGE until I found that unity can build to lots of different platforms. What platforms does the BGE support?

# Answer
> 2 votes
Windows, linux and mac. Although google may have helped a little, I think you might find more answers here: http://blenderartists.org/forum/forumdisplay.php?34-Game-Engine

I think it is better to use Blender to make the assets and Unity as a game engine. I only use Blender as a hobby for modelling and scripting but I think Unity will provide a better base for game development. It helps that there is a free indie version and this year they created a steam like store where you could sell a game making distribution that much easier. Sometimes the blender game engine does not play so nicely with some graphics cards, you might find evidence of this frustration in the forums.

---
Tags: blender, blender-game-engine
---


# Question
Title: How do I check if a key is down in XNA when I'm only given a string that has the key's name?
I'm trying to get access to the keyboard state in XNA from an embedded JavaScript runtime.

I'd like to do something similar to the following, but I can't seem to figure out how to get from "Left" to Keys.Left, in one line, for all 100+ keys or so.

```
js.SetParameter("XNA_Keyboard", new {
    keyDown = (Func<string, bool>)((name) => {
        return keyboardState.IsKeyDown(Keys[name]); // ! Can't index keys enum by name
    }),
});

```

Is there some kind of reflection that will make this easier?

# Answer
> 5 votes
```
js.SetParameter("XNA_Keyboard", new {
    keyDown = (Func<string, bool>)((name) => {
        return keyboardState.IsKeyDown((Keys)Enum.Parse(typeof(Keys), name, false)); // ! Can't index keys enum by name
    }),
});

```

That should do the trick, assuming the names match the C# ones.

---
Tags: c#, xna, code-reflection, metaprogramming
---


title: Storing and Finding Art Assets

text:
# Question
Title: Storing and Finding Art Assets
I've started down a line of art asset development that will allow me to (hopefully) reuse and improve assets for several games.

But how do I go about storing and finding them?

Let's say for example I decide to focus on RPGs for ~2 years. I would create items, monsters, etc. and store them somewhere. How would I categorize them and make them easier to search later on?

Is the best solution "use directories with broad categories like landscape/items/monsters/etc.?"

# Answer
> 1 votes
You can always use a Wordpress installation for it. It has an image gallery, and allows you to upload images and tag/categorize them (if you use one image per post).

# Answer
> 2 votes
What's wrong with using directories with broad categories?

You can just put more specific categories if you find that you really have too many assets within a directory.

You could just organize it this way:

`ArtAssets`

which contains:

`Landscape` -\> (only if you have a lot of landscapes) `Forest`, `City`, `Sky`, etc.

`Items` -\> `Weapons`, `Armors`, `Potions`, `Miscellaneous`, etc.

`Characters` -\> `Enemies`, `Players`, `NPCs`, etc.

I'd say start out with very broad categories and if you find yourself having to search a lot through a category to find an asset, get more specific categories.

# Answer
> 1 votes
Alienbrain asset manager is a good start.

---
Tags: art, asset-management
---


# Question
Title: Can someone explain radiosity lighting to me?
I already have the basics of ambient occlusion down. I have a raycaster and am capable of shooting rays about a hemisphere uniformly. It seems like those are the basics of what are needed for radiosity but I don't know where to go from there. Do I find how much light comes from each face? (I'm making my game out of cubes like minecraft) After that what do I do?

# Answer
> 9 votes
Indeed, that is all you need for radiosity. There are two different (but equal) formulations. The first is to "radiate" or shoot light from each patch (in your case probably a face), and the other is to "gather" or receive light into each patch. If you iteratively do this enough times, you get radiosity.

The first step is to figure out where light originates from because in either method there must be a light source. If you are going to do the gather method, I must warn you that it does not handle point lights very well. You must seed patches with light (calculate it separately) or you get odd results. In the radiate method you emit from the point lights as normal but ignore them as receivers from other patches.

You can stop after any number of bounces (or iterations), but the more you do, the better the solution. You have an easy time of patch creation as you can consider each side of your cubes as a patch. If you want something more detailed you can subdivide those faces even farther.

In a radiating example, this could be used as a basis for your loop:

```
while(!done) {
   foreach Patch a {
     a.shootRays(n);
     foreach ray r {
       Patch b = r.firstIntersectingPatch();
       float modifier = 1 / ((distance(a,b)^2)
       b.incidentLight += (a.exidentLight / n) * modifier;
     }
   }
  foreach Patch a {
    float modifier = a.absorption;
    a.exidentLight = (a.incidentLight * modifier) + a.emission;
    a.incidentLight = 0;
  }

  done = goodEnough() ? true : false;
}

```

For a gather method, you would have the slightly different first loop:

```
      foreach Patch a {
         a.shootRays(n);
         foreach ray r {
           Patch b = r.firstIntersectingPatch();
           float modifier = 1 / ((distance(a,b)^2)
           a.incidentLight += b.exidentLight * modifier;
         }
         a.incidentLight /= n;
       }

```

The first modifier is used for per patch modification of the incoming light. The most common use would be falloff from distance as I did above. The second modifier is for global modification of incoming light like material absorption. The a.emission variable would be 0 for most patches.

Only those that are light sources (or directly affected by point light sources if you are using a gather method as noted above) should have non 0 emission values.

The goodEnough() function could be many things. It could be just counting the number of iterations, or it could be looking at the total amount of light in the scene, or it could be some other test you devise. This part is really up to you and what you think looks good enough but still finishes in a reasonable amount of time.

The more rays you shoot, the more accurate your solution but the slower the process. The same goes for number of patches and number of iterations through the loop. How you store the final light value is up to you. It could be in a texture, or stored as a value in your cubes, but I don't think this would be feasible to do in real-time with a decent number of patches.

# Answer
> 3 votes
On the link bellow you will find one of the most excellent explanations of radiosity:

It is worth reading even if you know it well. So funny :)

---
Tags: lighting, minecraft-modding, radiosity, global-illumination
---


title: OpenGL vs physics?

text:
# Question
Title: OpenGL vs physics?
I am very new to game programming and I am in my first project. I have come to a point that I need expert advice:

Now for the game physics to be able to work on objects, it needs to know each object's position and its orientation in 3D space. As part of the simulation and due to objects moves (position change) and changes orientation (rotation).

Does this mean that rotation and translation calculation are done twice ? One in physics and the other is done using glTranslate and glRotate before drawing the object ?

IMO this should not happen. Also calculating translation and rotation in physics part will cause them to use the CPU instead of the GPU which will affect performance.

How is this done by experts and what advice do you give about efficient game architecture to handle such situations?

# Answer
> 16 votes
There are a number of reasons why rendering and physics pipelines have traditionally been kept discrete. Bear in mind as I list these, that this is not just about games. Your question touches on any application that uses a 3D rendering technology like OpenGL, it's competitors, or it's forerunners.

* Not every application that use 3D, needs physics. Remember that OpenGL wasn't just built for games, its usage covers everything from medical simulations to modelling sales statistics, air traffic simulations to complex chemical reactions, and so on and so forth.
* Any system which serves too many purposes becomes diluted in terms of efficiency. A graphic pipeline has to be *incredibly* fast. The moment you start introducing points where that pipeline has to interface with other subsystems such as the main system memory (where your code resides), you are going to experience order-of-magnitude reductions in efficiency. The hardware on your graphics card is very specifically narrowed down and ultra-optimised for *pushing pixels*, at great cost and many years of highly competitive research.
* The nature of the mathematics and data structures surrounding physics operations (particularly collision detection and resolution, without which there really *is no physics*) is largely different from the mathematics required for rendering.
* There are solutions that deal with physics in hardware. But unlike the way in which we render, the way in which we perform physics in any given situation differs widely. The most fundamental indication of this is that Newtonian physics is not one-size fits all; there are other ways of modelling physics mathematically that are more appropriate in other situations, such as Hamiltonian mechanics. And in games particularly, every individual game may choose to model its physics differently, whether in 2D or 3D. These need not even reflect real-world physics! -- because a game is a product of the imagination. In other words, physics are ultimately part of your game dynamic, and that may change from game to game -- let alone all of the other solutions to which technologies like OpenGL are applied.
* Accurately simulating physics on a vertex-by-vertex level is, for the most part, not presently a viable option. Given the high poly counts of models in most games, and the inherent difficulty of collision detection involving concave polyhedra, it is not as simple as just calculating physics off the model provided. For many if not most 3D games, bounding volumes in the form of cylinders or boxes are used to simplify collision detection, where that sort of level of collision detection is even required. Given current technology, the level of processing involved wouldn't leave much room for the rest of your game logic to run. Even Nvidia's PhysX requires complex, concave polyhedra to be decomposed down into simpler convex polyhedra, for physics simulation.
* Your graphics card is producing *perspective* with the transformations it performs. That is different from the transformations performed in physics, which have nothing to do with perspective as such -- it is simply calculating basic positions and orientations in your world. If you know about MVC, you will understand that there is a distinct difference between the data you hold in your application, and how your *present* that data.

The computer technology industry is driven by need, and while visualisation is an almost universal need, physics simulations are by no means universal either as a requirement or in terms of their respective implementations.

So my advice is, stop worrying about going against the grain and start focusing on how to do the two things you need to do: rendering and physics. You aren't going to get at the data in your graphics card's processing pipeline (CUDA/OpenCl are exceptions): you push in triangles and material data, it pumps out your 3D world as moving image.

---

As a final aside, your question is not without sense. The desire for a combined basis for physics and rendering, and the fact that floating-point math can be much slower than fixed point, shows us why voxel technologies are seeing a huge resurgence of interest: they simplify the entire world down to grid-positioned, axis-aligned convex polyhedra. This vastly improves performance, by reducing the amount of floating-point vector math needed for physical operations, as you are now working primarily in a spatially-subdividable, instanceable, integer-indexed grid. This same grid can be used for both rendering and physics, particularly as you may use different grid resolutions for these two distinct subsystems (when using an octree-based solution such as SVOs).

---
Tags: opengl, physics
---


# Question
Title: Techniques for bot movement in (first person) shooter games
I was wondering what kind of technologies were used in FPS games to move bots around the level. I know the pathfinding is done using waypoints or navigation meshes but how do the bots actually rotate and move over those paths? Is something like opensteer used for that, if so, which particular parts?

# Answer
(Optional) The navigation mesh approach is just an extension of the waypoints approach, that allows "wandering". In other words, you can use your navigation mesh to get back to a waypoint graph, by taking the centroid of each polygon in the navigation mesh. (If you are pre-generating the navigation mesh, you can just store the original source points; this way you don't have to recalculate the centroids later).

(Mandatory) Now once you have nothing but a waypoint graph, you need to do a search for the shortest path between A and Z. A is where the entity in question is; it wants to know how to fulfill some goal, and that goal generally has a physical location associated with it, which is Z. Now apply something like the A\* algorithm for shortest-path search, to that waypoint graph. The output will be a single linear list of nodes indicating the shortest path to your destination, {A..Z}. Now move your entity: This should be a simple matter of moving your entity along a straight line betwen A-\>B, B-\>C etc. to Z. Each time you reach another node in the path, fire off an event (or whatever) and then start moving to the next one until Z is reached.

Rotation? Well just like in real life, you turn around to face where you're going, don't you? So have the entity rotate before she heads off toward the next node. You can even begin her moving slowly at first while she's rotating, to look more fluid.
> 4 votes

---
Tags: ai, first-person-shooter, behavior
---


# Question
Title: How do you keep the gameplay and music in sync in a rhythm game?
What's the best way to program a rhythm based game in XNA? (Some sort of game like Dance Dance Revolution) Would you use the built in GameTime? What logic would you use to make sure the game constantly stays in sync to the music? Any tips would be much appreciated!

What I am basically asking is how you would keep the gameplay in sync with the music. For example in DDR how would I correctly sync the arrows to the beat of the music?

# Answer
> 4 votes
In XNA it should be simple as the mediaplayer class can report its position while playing back something, use that position (at least that's what I did when I did a 2D scene playback that had to sync perfectly to a music track). It can also be set, so you can do decently accurate scrubbing.

# Answer
> 0 votes
You can use as a base those midi trackers for xna:

http://xnasfxrsynth.codeplex.com/

http://sharpmod.codeplex.com/

this way you can do a perfect sync with the notes in an easy way.

---
Tags: xna, game-design, music
---


title: Finding asset files in Linux games

text:
# Question
Title: Finding asset files in Linux games
What is the usual method of storing 3D models, textures, sounds and scripts (e.g. Lua files) during development and in a release? I am developing a game with my friends in mainly C++; in the prototyping phase we only had a single texture that was saved as a C header with the GIMP, but of course, this approach does not scale well and increases compilation times greatly.

Under Windows, the usual practice is to just dump them to the `%PROGRAMFILES%` subdirectory in which the game executable resides, perhaps arranging them in an appropriate tree structure. However, on Linux the picture seems a lot more complicated. The executable usually resides in `/usr/bin`, whereas applications store their other files in `/usr/share`, and I think it would be an extremely bad practice to put non-executables in `/usr/bin`. However, the directory structure during development is totally different.

I could come up with two different possible solutions:

* Let the executable find the asset files relative to itself, and install the game to `/opt`. Then place symlinks to `/usr/bin`. During development, the relative path of the assets to the binaries is the same as during deployment.
* Access the files with an absolute path which is defined as a preprocessor symbol. Let the build process (in our case, raw `Makefile`s) take care of defining it as it is fit.

Both approaches seem somewhat inelegant to me in one aspect or another. Is there a common practice in the game development industry about this?

The only relevant questions I could find were Determining the location of installed/on disk game assets and Directory paths for resources and assets, but those did not address the problem of running "from the source tree".

# Answer
> 7 votes
`../lib/programname` or `../share/programname/`, relative to the `dirname(3)` of `argv[0]`, depending on if the assets are architecture-dependent or not.

This is the same standard as all other Linux (and most non-Mac Unix) programs.

If you want to run from "the source tree",

1. You should get a real build system and do a build, because you never "run from the source tree", you run a built executable, which your build system spit out somewhere, and it can copy or link assets into place just as easily.
2. If your build system is too crappy, just also check `.` or `./assets`, etc., and then look into a new build system later in development.

Unlike happy\_emi says, you should definitely provide a way to override this with environment variables. It is exactly what they are intended for.

---
Tags: assets, linux, filesystem
---


# Question
Title: Creating an Android Game using Java and c++
What's the best way to go about this? I've never coded using two languages before, let alone for an android phone

# Answer
Using the Android NDK you can build a native library in C/C++ and by exporting the functions as native you can call your functions as if it was standard Java code once you've initialised the library. There's plenty of tutorials available on getting started with the NDK as well as samples provided by Google.

It's important to note that the NDK isn't necessary for a lot of purposes, see the FAQ:

> When to Develop in Native Code
>
> The NDK will not benefit most applications. As a developer, you need to balance its benefits against its drawbacks; notably, using native code does not result in an automatic performance increase, but always increases application complexity. In general, you should only use native code if it is essential to your application, not just because you prefer to program in C/C++.
>
> Typical good candidates for the NDK are self-contained, CPU-intensive operations that don't allocate much memory, such as signal processing, physics simulation, and so on. Simply re-coding a method to run in C usually does not result in a large performance increase. When examining whether or not you should develop in native code, think about your requirements and see if the Android framework APIs provide the functionality that you need. The NDK can, however, can be an effective way to reuse a large corpus of existing C/C++ code.

As for developing on an Android device, I would suggest downloading the SDK (and NDK if your application requires), getting the emulator working, and having a go at the tutorials, reading the technical articles for best practices, and making sure you understand the application fundamentals.
> 3 votes

---
Tags: c++, android, java
---


# Question
Title: Is it possible to have concurrent collision detection where every entity acts at exactly the same time?
There are many algorithms that can be used for collision detection. In many cases we check for an overlap in coordinates of an entity.

If we make a triangle a,b and c. We have 2 entities at a and b heading for a collision at c but each of them are moving at exactly the same time, what kind of algorithm could work?

It seems more like a chess game where you would have to predict every move that the other entity would have to make, if they swerve to the left to avoid a collision will they also run the chance to collide. Is it possible or is it too complex? Would it work for thousands and millions of entities in the same search space?

# Answer
> 6 votes
In your second paragraph, you bring up the issue of simultaneous movement. This is how objects move in the real world (obviously), and if you're interested in physical accuracy you would need to solve your collisions by taking this into account. However, this can very quickly become expensive, so most games perform collision detection by moving objects sequentially (move A then B or B then A, then check for collision). The unrealistic nature of sequential detection tends to be a non-issue and greatly simplifies the computation.

In the third paragraph, you bring up the types of movement the objects might perform on their way to location C. Since the movement step for most games is fairly small, simplifications and restrictions on an object's movement are often employed so that calculations become much easier. An example would be the stipulation that during a single time step, objects are only allowed to move with a constant velocity and cannot rotate.

So, overall, I'd say that the answer to your question is that simultaneous, complex motions of objects *can* probably be simulated by a computer depending upon exactly what they're doing, but it is unlikely that such computations are feasible or necessary to perform in a real-time application. Using a simplified movement model with a sequential movement of objects greatly simplifies the calculations and still looks correct under most circumstances.

# Answer
> 2 votes
The more pertinent question is, does anything in the real world happen simultaneuously? That all depends on what division of time you go down to; seconds, milliseconds, nanoseconds, picoseconds and so on. Eventually you will reach a point where things *aren't* happening simultaneously, because the degree to which you can subdivide time is infinite. This would also also be the case with any theoretical computer system, even one designed for that purpose, due to the fact that no matter how high a timing resolution you specify as a parameter for your hardware design, *there is always a higher resolution*.

Modern collision detection systems work, both inside and outside of the field of games, because it doesn't matter, so long as the collisions happen at what is *perceptually* the same time. The human brain has it's limits to what it can perceive as continuous. Generally frame rates in games don't need to exceed about 60fps for this reason -- same as a flourescent lights running at 50-60Hz AC. And 60Hz is, from what I understand, well above the limits of our rate-of-perception, in order to appear continuous even in worst-case scenarios.

EDIT: This post describes the practical realities, however see Martin Sojka's comment re the theory of time divisibility, below. Thanks Martin!

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


# Question
Title: How hard is it to port games from the PC to other platforms?
I am trying to learn game development with the Unreal Development Kit and Unity, trying both out, and trying to get an idea how they work. For now, I'm mostly focusing on PC games.

How hard is the technical aspect of porting a PC game that I made in the Unreal Development Kit or Unity to another platform, such as Play Station 3, or Xbox 360? is there some kind of option where we can just select the target platform from a combo box and press deploy, or do we need to modify the game for each platform?

# Answer
> 5 votes
UDK and Unity can deploy to both the consoles you mentioned. Of course even in the best case, there are always going to be tweaks needed here and there since different platforms support different things (shader tech, controller types, and so on) and since optimisation may need to be done independently for the different platforms. There may be a few tweaks, or a mountain of them depending on the solution and platforms you intend to support. But yes, that's part of the point of both UDK and Unity. What you'll pay to support console platforms is a whole other matter.

---
Tags: unity, udk, porting
---