# Question
Title: Finding the right directory structure for version control
Recently I've started thinking about how to layout the directory structure for my game engine. And well, I kinda hit a little snag.

There's going to be 2 people working on this project. Me and one of my friends. The problem is how do I do the layout of the directories so that it works nicely with version control (I'm using Plastic SCM. It has really nice features).

I'm thinking of dividing it up into 3 separate things:

1. A source code respository for storing all the C++ code
2. An exported assets repo where my friend can store all his exported data. (Exported as in final version that can be used by the engine).
3. And a raw assets directory where all my friends raw assets go into. These include stuff like psd files and mb files for easier backup and versioning.

What do you think of this structure? Any comments are welcome. I'm really down in the dirt with this one.

# Answer
That's quite neat and clean. Just don't mess with different repos, make this separate directories at the root of your repo. This will of course evolve with your project, but as a startup layout this is way enough.

Your exported assets directory should probably be excluded from version control. It might be a good idea to have a separate "exported code" directory (object files + symbols + executables), to exclude from version control as well.

So, for instance, something like that:

```
repo
├── code
├── assets
├── export *
│   ├── code
│   └── assets

* Excluded from source control

```

It's apparently straightforward to exclude files/directory from version control with Plastic SCM, by using an ignore.conf file.
> 4 votes

# Answer
Let's get to roots of SCM - it is for sources. Now sources are not only text files, they are everything that you use as a source (source codes, scripts, PSD files, sounds). Everything that can be repeatedly generated are not sources (spritesheets, executables, resource packages).

You need to store all sources in one repository for the sake of consistency. Because each and every revision ought to be self-sufficient. You also need to have build scripts to produce application and all its assets from sources. Builds are not stored in SCM because you can always regenerate them.

**EDIT:** Once you put size out of the question, it makes sense to keep all sources in SCM because it's quite often when engine behavior depends on lookup textures, models sizes and shapes, assets count and location (also think TDD). When you have source codes revision A you ought to be very confident in your engine to allow it to work with any other assets revision. Otherwise you need to make a tie that code A works only with assets A, B-B, C-F etc.. and then when you rollback the code you need to rollback assets as well. That ruins SCM idea.

From practice: we were storing paletted textures, but since r2879 we switched our format to full-color textures. Having source textures (some unchanged since r1000) and generation scripts under SCM we don't have a problem of finding right assets/exe combo.
> 1 votes

# Answer
I would recommend using Trunk-Branches-Tags as your top level. Branching is invaluable for experimentation. I am not familiar with Plastic SCM, but my experience with Subversion is that you need to plan for these needs from the outset. Then under the trunk you can set up your files. Otherwise, as for binaries, I like to store the optimized final format and the most up to date source(photoshop, raw video, etc.,) in my repository. The main reason is that most of my tools support Subversion.
> 0 votes

---
Tags: architecture, version-control
---


# Question
Title: What are the differences between EGA and VGA for MSDOS API?
How different is the API for EGA and VGA for MSDOS applications? We're talking about the API that was used in games like Doom, Quest for Glory, Duke 3D, etc.

More specifically, how much work would be involved in changing an application's use of EGA APIs to VGA APIs? or SVGA even? They seem to be fairly similar in terms of interrupt strategies, registers used, etc. Looking for a little more definite answer though, if possible.

---

Forum post that suggests wrapping memory access may provide a partial solution: http://www.allegro.cc/forums/thread/604334

Some basic information on using VGA, but nothing on EGA:

http://www.brackeen.com/vga/basics.html

http://www.wagemakers.be/english/doc/vga

# Answer
> 7 votes
The problem is more complex than simply exchanging out EGA for VGA.

In fact, the VGA interface is what grew out of the EGA interface, which grew out of the CGA interface, which grew out of the MDA interface, which is why you see the interrupt call schemas as so similar.

Basically the idea was "here's interrupt 0x10... and a few simple functions for setting the graphics mode and plotting pixels... go!"

However, that isn't all there is to the story.

For example, very few applications actually used the pixel plotting functionality of 0x10.

Why not?

It was slow.

What did they use instead?

Direct memory manipulation.

Generally, the memory locations for the various display modes started at one of three locations: B000:0000, B800:0000, or A000:0000.

And the code for talking to a 4 color CGA (2 bit) display versus a 16 color EGA (4 bit) display and a 256 color VGA (8 bit) display would be so very different that they would not be adaptable to other pixel depths. You'd basically have to rewrite the entire rendering engine from scratch.

To further complicate things, the popular video mode was 13h, which was 320x200x256.

It also just so happened that the VGA could be tweaked into 320x240x256 (to give square pixels on a 4:3 display) "mode x", which was actually split into four pieces for putting together the video data.

In other words, the games you mention only used the VGA API for one thing: to set the video mode. After that, it was all display resolution specific stuff. They didn't use the setpixel call of int 0x10.

So, the answer is: the int 0x10 "api" (if you want to call it that) was not that terribly different, but it also wasn't widely used for high performance applications (games).

---
Tags: graphics
---


# Question
Title: How do I make my game connect to a server without real IP address?
I'm making an XNA game. When I started, I had a broadband connection with real IP, so I could host servers of any kind without any problem, but now I don't have that connection any more and I want to be able to let players from outside my local network connect to my server again. How do I do that? How do big guys at studios do that?

UPD: I guess it isn't fair to ask two questions in one, I just wanted to know if it's still possible for me to host a server on my connection, and if it's not an option, then how to do it without it (my connection). I believe I got my answers, though.

---

If I had an external dynamic address, I could use dynamic DNS service, but I don't, so I'll have to host my server on another machine (probably rent a server).

# Answer
The big guys, and even quite small guys, buy space on real servers with public IP addresses and real DNS service. It's not very expensive to rent a cloud server.

Services like http://dyndns.org can give your server a stable name, even though it doesn't have a stable IP address. Note that running servers with any significant amount of traffic on your home machine probably violates your terms of service, and will get you in trouble if you attract the attention of your ISP.
> 10 votes

# Answer
I didn't downvote but I can assume you have downvotes because your question seems a little confusing.

It seems like you're asking one of two things, either you don't have an internet connection anymore and you still want to host a game server, in which case you cant, or you have a dynamic IP.

If it's a dynamic IP you need to search the web for a "Dynamic DNS tool". I think "DNS exit" is probably a good choice. What that will do is constantly update your IP to your DNS host. That way you can have some url example.com and the server that tells users what IP to go to will know your current IP.

Being that you're on the internet posting this, people are probably confused. You have an IP. It's either static or dynamic. Since you are likely on a residential internet service provider, it's likely dynamic, meaning your IP changes. That's not so good if you're hosting a server so you need a tool like dnsexit.

Go to whatismyip.com. That's your current IP. You can atleast give that to users for now and test out what you're working on.

All of that said, get a server. Liquidweb, godaddy, rackspace, anything. The big guys have their own data centers with three independant internet providers. The little guys like most on this site have one or more virtual private servers they use from hosting companies. I started using a VPS when I was 12, and they weren't well known at all then. No reason not to.
> 5 votes

# Answer
Looking at DevilWithin and reading all the comments you've made so far, I'm going to have to agree with him. I can't upvote him because I have no rep, but...

The fact that you have access to the internet *MUST MEAN* you have a "real IP". Visit whatsmyip.org for it.

So what IP address are you giving the users? Since you claim it's not a "real IP" I'm assuming (and I may be wrong, but just an example) you're giving them 192.168.x.x or 10.x.x.x, and in either case... it would make perfect sense that they can't connect unless tunneling through Hamachi, because those are local addresses that don't exist on the internet, and won't exist on the internet. The fact that they can use Hamachi though means you're connected to the internet means you're still exposed to the outside world. What you need to do for clients to connect to you:

Take your local IP (192.168.whatever) and go to your router port forwarding page. How you do this is based on what router you have.

Open and forward whatever port you need. Let's say you open port 25040 and forward it to 192.168.whatever. Once you save those settings, you should be able to take your "Real IP" (again, open whatsmyip.org from the computer that's running the server to find out this number) along with the port, and the router will redirect it to your local ip, and clients should be able to connect.

Really hope this helps because this sounds exactly what you're doing from the posts you've made.
> 5 votes

# Answer
This is a general networking issue, not really game development, but it is usually easy to solve.

I assume that you are now behind a router(or anything similar), and when typing ipconfig in the console you only are able to see your LAN IP address.

If you are connected to the internet, you have an IP, that is for sure. Or better, your router device has an IP, and acts as a bridge between the network computers and the external internet, filtering all connections.

If you access the router configuration page, usually accessible by the browser at somewhere like http:\192.168.1.254\\, depending on the device, you probably will find a section for port forwarding, or virtual servers, or anything like that, also depending on the manufacturer and model of the equipment.

By associating a port with your internal ip, you will have the router redirecting all connections to that port, directly to your computer. After this bypass is done, it should work normally.

Some routers also support a feature that actually maps the external ip to your machine, for every port and connection. Careful with this one, but if you feel safe with it, ipconfig will actually show the real ip. A ipconfig/release followed by a ipconfig/renew may be needed to finalize the changes.

Sorry for the clumsy answer, hope it helps.
> 2 votes

---
Tags: networking
---


# Question
Title: How to compute highscores, so that 10 matches will "correctly" compete 100 matches
When computing highscores, it is possible to:

* count **sum** of points (in every match),
* count **average** of points (across all matches).

Sum is vulnerable to: multiple low-quality matches.

Average is vulnerable to: creating new account and playing few high-quality matches.

How to face this problem? Multiply **sum** x **average**? How is this done in practice, e.g. in World of tanks?

# Answer
Is this a PvP game? If so you should look at ELO ratings: http://en.wikipedia.org/wiki/Elo\_rating\_system

There is a pretty basic idea behind it. Each game changes your rating, this change is solely based on your rating and the opponents rating and wheter you have won or lost.

* If you face a opponent stronger or equal to yourself: many points gained from winning, few points lost from losing
* If you face a opponent weaker than yourself: few points gained from winning, many points lost from losing

This system is regulating itself as winning against the same enemy again and again will only inflate the gain from it and if you have a high rating but lose against someone with a lot smaller rating you lose alot again.
> 1 votes

# Answer
If it's a free to play game, I'm not sure how you can protect against someone creating a new account. But integrating highscores with social networks may discourage people from creating multiple accounts as it would be linked to their profile. While also making the highscore more meaningful to be competitive against friends.

The highscore should be the highest score from a *single* match. If you want to have a running total or average they should be ranked separately. Likely the average should be further divided by number of games played so it's clear that the people with the most games played and the highest average are truly superior players.

Also highscore boards can be a daily highscore (for that day or the previous day) and all-time highscore.
> 1 votes

# Answer
Player rank is more a metric of how well or poorly the player performed against their competitors rather than a sum or average of the points scored in a game.

To develop algorithms to create player rankings google Microsoft Truskill or Elo ratings, both will give you ample ways to determine how to generate player rankings and create a leaderboard.

Chuck
> 1 votes

---
Tags: leaderboards, ranking
---


title: Collision organization problems

text:
# Question
Title: Collision organization problems
I just started playing around with c++ and some SFML. I'm going to create a 2D game with top view to test my ability and I came across a very big problem: collision detection and physics. So I see at least 4 scenarios:

1. An object collides with a solid object (that cannot move) so the first object must stop. (Example: a player hitting a wall)
2. An object collides with a movable object (that is not alive so does not move unless pushed) so the first object push that object. (Example: a player that moves a box)
3. Two object (that has proper move) moves and collide frontally so they push each other with the same force so they must stay still.
4. Two object (that has proper move) and one push the other which is going in the same direction: so the second object must move faster or must have more power. This implies also that if more object push themself one back to the other we have that the first gains a lot of push power. (Example: a crowd that push to to get inside a door and that door with x pushing power gets destroyed)

The collision problem is not a problem at all: you just check the player x and y and width and height against the object that is colliding with. The problem is instead: who is supposed to take care of the collision? Let's say that it's the movable object that is pushing that has to take care of it: (1 scenario), it's ok, the one that pushes just reset its x and y to where it was before colliding; (2 scenario) here things start to get a bit tricky: the pushing object must take care also of the object that gets pushed so it has to move that object too; (3 scenario) here we have two pushing object, which one should deal with the collision? (4 scenario) how do we store the pushing power of the object?

Is there general guidelines for that, considering also that the player is not the only mob and that there might be computer guided mobs?

Thanks.

# Answer
> 2 votes
Beside using an existing Physics Engine that can take care of this, there is one -- I guess, pretty popular -- technique for collision detection between moving and solid objects: Binary Space Partitioning.

I have only implement it yet for collision between the player (moving object) and solid map objects, where the idea works as the following. The map is sorted into a tree structure.

When loading the map, you separate the room of the map in the middle (middle does not necessarily be the room separated into two equal halfs, but you can use also the median of all objects in the map).

Now you check for every object, in which half of the room it is, and move it to the corresponding children node in the tree (one for each half). If it lies on both side, leave it in the current node.

Now you can split the children nodes, and so on. You can use a limit, of objects, that must minimum reside into one node. If there are less objects in a node, you won't split it up anymore.

If you have done this, you have a nice BSP-Tree for your map and your solid objects. If you want to check for collision with your player, you just take the position of your player and check it against collision with all the objects, that are in the root node of your tree. Then you look, in which half of the room your player is, and check his/her position against all the objects in that children node. And so on...

With that you reduced the complexity of the collision detection a lot compared to bruteforcing against all other map objects. Bruteforcing has *O(n)* complexity (not regarding your actual collision checks) and binary space partitioning use an average of *O(log(n))*, therefor needs the precalculation.

The same algorithm also works with moving objects, but you will need to move them in the tree, when they are moved on the map.

If you search literature about binary space partitioning, you will find a lot of improvements, how to make it even more efficient.

Of course you will find a lot of implementations of that already in physics engines, but for learning reasons, this is a nice thing to implement :)

# Answer
> 1 votes
Instead of having the objects responding to the collision, create a physics system to take care of that. The system should have a pointer to every 'physical' object and be able to know which objects are static or dynamic, which is heavier or lighter, their speed, etc. The system takes care of all collision resolving.

On another note, you could also try a physics library like Box2D. Unless your goal is to create a physics engine, it's a lot easier/faster to use a library.

# Answer
> 0 votes
If you want to make a game and are not that interested in getting into the nitty-gritty of physics yourself, I'd advise simply using a physics engine, such as Box2D.

If you *do* want to get into the nitty-gritty of physics yourself, well, that is a huge topic that can't really be explained in a couple-hundred-word answer here. I'd recommend picking up a book, such as Dave Eberly's Game Physics. This topic will require some serious study before you'll be able to do anything interesting with it, though. Most books on the game physics simulation are written about 3D physics, but most of the same techniques apply to 2D as well (the main difference is that rotation is much simpler in 2D than in 3D).

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


# Question
Title: Collision detection not working properly
I have some problems with collisions, the collision detection only works either on one x "line", or on one y "line".

Example

Heres the collision code:

```
public void checkCollision() {
    for (int i = 0; i < drawX.size(); i++) {
        if (player.getX() == drawX.get(i) + 16 && player.getY() == drawY.get(i)) {

            player.setLeft(false);
        } else if (player.getX() != drawX.get(i) + 16 && player.getY() != drawY.get(i)) {
            player.setLeft(true);
        }

        if (player.getX() == drawX.get(i) - 16 && player.getY() == drawY.get(i)) {

            player.setRight(false);
        } else if (player.getX() != drawX.get(i) - 16 && player.getY() != drawY.get(i)){
            player.setRight(true);
        }

        if (player.getX() == drawX.get(i) && player.getY() == drawY.get(i) - 16) {

            player.setDown(false);
        } else if (player.getX() != drawX.get(i) && player.getY() != drawY.get(i) - 16){
            player.setDown(true);
        }

        if (player.getX() == drawX.get(i) && player.getY() == drawY.get(i) + 16) {

            player.setUp(false);
        } else if (player.getX() != drawX.get(i) && player.getY() != drawY.get(i) + 16){
            player.setUp(true);
        }

    }
}

```

drawX and drawY store the positions of the tiles.

# Answer
> 3 votes
Player position is not getting increased by 1. So it overpasses the coordinates of the tiles. For example, consider a tile and the player at the following positions. I think size of your tile is 16.

```
|      |   |    |
|player|   |tile|
|      |   |    |
       5   10   26
Player moving right.

```

Now if player position would have been increased by 1. Then x = 6, 7, 8, 9, **10** (gotcha). But usually it is not the case.

Lets say it is being increased by 2. Then x = 7, 9, **11** (overpassed). So use \<= and \>= instead of comparing the positions exactly.

EDITED

```
public void checkCollision() {
    for (int i = 0; i < drawX.size(); i++) {
        //If tile on left
        if (player.getX() == drawX.get(i) + 16 && player.getY() == drawY.get(i)) {
            player.setLeft(false);
        }
        //Otherwise
        else{
            player.setLeft(true);
        }
        //If tile on right
        if (player.getX() == drawX.get(i) - 16 && player.getY() == drawY.get(i)) {
            player.setRight(false);
        }
        //Otherwise
        else{
            player.setRight(true);
        }
        //If tile below
        if (player.getX() == drawX.get(i) && player.getY() == drawY.get(i) - 16) {
            player.setDown(false);
        }
        //Otherwise
        else{
            player.setDown(true);
        }
        //If tile above
        if (player.getX() == drawX.get(i) && player.getY() == drawY.get(i) + 16) {
            player.setUp(false);
        }
        //Otherwise
        else{
            player.setUp(true);
        }
    }
}

```

Try modifying your code as above. Remove the else condition. It should work.

# Answer
> 1 votes
The code is not understood at all and what you want exactly? I can say only you try:

```
public void checkCollision() {
      player.setLeft(false);
      player.setRight(false);
      player.setUp(false);
      player.setDown(false);

      ...
      ...
}

```

and replace "==" to "\<" or "\>"

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


# Question
Title: Intercepting DirectX calls and optimizing the overal performance of games
I would like to use a DirectX proxy dll to intercept (and possibly optimize) the graphics calls being made by normal PC games. I am going to "screen cast" a game with ffmpeg or something similar and then stream it to a handheld, so a lot of things should be skipped to reach a a reasonable balance of encoding time on the server side, as well as keep it reasonably low-bandwith

adaptive things like:

entire frame skipping skipping shader phases reducing texture size nearing the far view plane (resp. culling more objects than usually) are on my TODO list. I already checked out a few implementations of DirectX proxies (even the DirectX SDK has one - PIX), but most of them are used for logging and debugging purposes, and not really for runtime hacking and quality degradation.

I was curious what other existing implementations there could eb out there. I guess, I am not the only one who came with the idea of "screwing up" the graphics quality post-factum, in order to increase better overal performance.

# Answer
> 2 votes
This might not be the answer you're looking for but if you're going to screencast you don't need to touch DirectX at all. Just capture a video of the game and then transcode it and send it to the mobile device on the fly. The only thing you might need to do is to capture at a lower resolution than the game is playing at or you can do this during the transcoding (smaller video resolutions save bandwith). So KISS as always (Keep it simple stupid).

As for the DirectX proxy idea, I think this going to be extremely difficult without fully knowing the driver and DirectX API. A lot of these commands might not make sense when inspecting them one by one but skipping anyone of them might have a catastrophic effect and the result can differ extremely per game. Note that almost all the DirectX commands change some sort of state on which the game might be dependent. For example if you reduce the size of a texture this could either totally screw with shadows and lights or make that billboard appear slightly blurrier, it's hard to tell which one of these two things will happen by just seeing the command "LOAD TEXTURE".

Also note that a lot of the optimizations you might be thinking about are already done in the GPU driver as best as possible. Maybe try tinkering with the advanced options of yours, sometimes you can greatly improve performance that way.

---
Tags: directx, shaders, rendering, tools, optimization
---


title: Texture caching in 2D XNA game

text:
# Question
Title: Texture caching in 2D XNA game
Developing on the XNA framework for Xbox, I have different 2D image resources being used depending on the level. At the end of a level, I'd like to leave as much loaded as is reasonable, so that the next time a level needs that resource, it's already loaded. However, there will be a great many resources, so I'm assuming that it's a poor idea to leave everything loaded always, simply because memory is limited. Is there a good way to know how much to reasonably unload to keep things running smoothly?

My idea: If the .net garbage collector supported soft references (like the JVM), I could change references to any resources not being explicitly used to soft references, and change them back or reload when they're needed again. That way the garbage collector, who knows the state of memory much better than I, can intelligently drop references as needed when loading new content. In other words, a simple cache. This soft reference construct doesn't exist in C#, however; is there an equivalent or some better way to handle this?

# Answer
First of all, probably the nicest way to implement this is by customising `ContentManager` as described in this blog post. Implementing your own content management solution over the top is silly when you can just customise the caching policy of the existing one.

The number one problem with the solution you are suggesting is that most XNA resources are "unmanaged". Check out this answer for a description.

This means that **you cannot rely on the garbage collector to unload resources when memory runs low**. Because the garbage collector cannot see the unmanaged memory - not to mention GPU resources - that many of these objects are using. That is why many of these objects are `IDisposable`.

Now, if you accept that the GC won't tidy up for you automatically, you may consider the idea of invoking the GC between levels with `GC.Collect()`. This would work - but now let's come back to customising `ContentManager` \- because we can get the exact same effect without abusing weak references:

The external interface I am proposing works like this: Right before you start loading your next level, you call:

```
myCustomContentManager.MarkAllAsUnused();

```

You then start loading your next level, calling an overwritten version of `Load` as normal. Once you've finished loading, then call:

```
myCustomContentManager.UnloadAllUnused();

```

Internally you could implement this by maintaining two resource caching dictionaries in your custom content manager (the default `ContentManager` only has one). An "in use" dictionary and an "unused" dictionary. On a load request, check both dictionaries, and move the loaded resource to the "in use" dictionary if it isn't already there.

On `MarkAllAsUnused`, move everything to the "unused" dictionary, and on `UnloadAllUnused`, unload only that dictionary.

Of course, this is an optimisation. If you don't need to be optimising load time, but you still need to optimise memory, there are simpler ways.
> 4 votes

# Answer
You know best what resources are going to be needed in the next level so instead of soft references or using a solution that involves manually loading and unloading all content why not just use a cache (you've talked about it a couple of times). KISS really applies here I think.

So just encapsulate the content manager. Create the new methods AddToCache(...), RemoveFromCache(...) and create a Load method that first checks the cache to see if something is available.

This approach isn't fancy, isn't automatic but I think it might be exactly what you need.
> 1 votes

---
Tags: xna, resource-management
---


title: What's the best 2D animator?

text:
# Question
Title: What's the best 2D animator?
What's the best 2D animator for creating sprite sheet animations for a game? Are there any that match this criteria?

* Cutout animation (I don't want to have to draw every frame)
* Exporting to images
* Simple and lightweight (I don't want something that bogs down my machine and I'm not doing a 2d animated movie, I just want to animate a characters walk/jump cycle)
* Cheap or Free

Preferable it would be opensource, but I'm willing to pay for a good piece of software under $50 dollars

# Answer
There's a piece of software currently in beta called Spriter that had an excellent previous run, and is now forging on ahead for even more features/usability. If I recall correctly, I paid $20 for it in the kickstarter, but you can still buy it and get instant access to the beta. You can find it here.
> 1 votes

---
Tags: 2d, animation, sprites
---


# Question
Title: How to help players find friends in a cross-platform mobile game?
Users on different platforms (iOS and Android) that play the game should be able to find each other and become friends in the game. They must have the possibility to invite other friends as well. The game is PvP so they will also be able to fight one another.

Is Facebook the best way to go about it? (invitation sent by email)

# Answer
> 0 votes
The four major social sites: Facebook, G+, Twitter, and Pinterest are all great for this kind of thing. I would also look into using their email contacts.

But please, ensure you ask your players before you do anything with any info they give you, and don't excessively spam people. It's bad for your game, people's sanity, and the industry as a whole.

---
Tags: cross-platform, facebook, social, pvp
---


# Question
Title: How make a laser path prediction line like a “slingshot cowboy” game?
How so I make a laser path prediction line like a “slingshot cowboy” game in cocos2d or box2d and select the target like "slingshot cowboy" game.

# Answer
Let's consider the basic slingshot mechanism that seems to be implemented here. We know the user can drag the slingshot by defining a vector having its origin at the tip of the downward pointing triangle (like in my figure). The user can define thus vectors that point toward the bottom of the screen (restricted programmatically), and whose radii cannot be larger than a *dMax* threshold.

Whenever the user shoots, the input vector has a length between \[0, *dMax*\]. This interval must map into a range interval: \[*rNear*, *rFar*\].

But since the range in real life is usually not a linear function of the launch velocity, we're free to suppose that the transfer function between \[0,*dMax*\] and \[*rNear*,*rFar*\] is looking somewhat like this:

```
 rangeFunction(l) = (rFar - rNear) * sqr(l / dMax) + rNear

```

where *rFar* is the maximum range (the red circle's radius), *rNear* is the minimum range (the green circle's radius). This function just maps one interval to the other, in a non-linear fashion. I'm using now the `sqr` (x^2) function for below unit positive values. This function should give the user that plausible natural impression we're looking for in such games.. without a lot of mathematics/physics to support it.

In the figure above, the red vector is the one that gives you the shooting direction: just normalize it (divide it through its magnitude) and negate it (add the minus sign to it). Then multiply it with the result from the *rangeFunction(length)* where the *length* is the initial length (before normalization) of this vector.

Now find the angle between the blue and red vector using a 2D cartesian frame and the *atan2* function. Let this angle be *u*.

The point where the projectile will land should be *(r\*cos(u - pi), r\*sin(u - pi))*, where *r = rangeFunction(length)*. That should be it, more or less. Check if this point is "inside a cow's aura" and then kill it, like cowboys are supposed to, right?
> 2 votes

---
Tags: iphone, cocos2d-iphone, box2d, physics, projectile-physics
---


# Question
Title: Correct way to export from blender to ogre format?
When I export from blender to ogre using the blender2ogre add-on, I'm not getting anything besides a scene most of the time and when I get a mesh I never get a material. Is there something wrong with my export procedure or what else could I be doing wrong?

## Update

I can export the basic cube from blender to ogre but when I download a model and try to export it I don't get the meshes.

## Update 2

I tried again and selecting the model in Blender does the difference like the answer here says. I can export an alien and get the mesh and material:

I rename the files:

```
$ ls workspace/DungeonWorld2/assets/objects/creatures/alien/
Cube.001.mesh          Material.002.material  Material.005.material
Cube.001.mesh.xml      Material.003.material
Cube.001.skeleton.xml  Material.004.material
dev@dev-OptiPlex-745:~$ ls workspace/DungeonWorld2/assets/objects/creatures/alien/
alien.mesh          Material.002.material  Material.005.material
alien.mesh.xml      Material.003.material
alien.skeleton.xml  Material.004.material
dev@dev-OptiPlex-745:~$

```

But how do I actually load the material since the alien now turns up in the game with no material but it does render the mesh:

```
    Spatial model3 = assetManager
            .loadModel("objects/creatures/alien/alien.mesh.xml");
    model3.scale(0.3f, 0.3f, 0.3f);
    model3.setLocalTranslation(-40.0f, 3.5f, -20.0f);
    rootNode.attachChild(model3);

```

# Answer
> 3 votes
Ok, as exporting Blender scene and meshes to Ogre using blender2ogre module does works fine for me, I will try to run a very simple test in order to help you point out what is going wrong on your side.

So in order to get something very simple to compare with, I will export the initial Blender scene (the one with the simple cube) without changing anything.

> 1. If I **unselect the cube** and export the scene using the Ogre3D blender module (default settings) I get the following file(s):
>
> * test.scene
> 2. If I **select the cube** and export the scene using the Ogre3D blender module (default settings) I get the following file(s):
>
> * test.scene
>     * Cube.mesh
>     * Cube.mesh.xml (useful to convert to older Ogre mesh formats)
>     * Material.material

The .scene files must be parsed in the code beside the Ogre engine, but the .mesh files can be used directly with or without the .material files.

Obviously, at that point I can see only two reasons to your problem:

* whether you have a problem with the way you select your scene content before exporting
* or with you softs version (Blender 2.6.3 + blender2ogre 0.5.5 doesn't works for me for instance)

*This quick test was done under Linux with Blender version 2.6.3 and blender2ogre version 0.5.7-preview*

If you can, try to make this simple test, and we will see if we can help you further.

---
Tags: blender, ogre, jmonkeyengine
---


# Question
Title: Screen coordinates to a multilevel isometric world
I have an isometric world that has stuff on multiple levels, i.e. it has an XYZ coordinate system, and tiles can be stacked on each other, accumulating screen Y offset as they go. I currently have an algorithm in place that converts the screen coordinates to world XY coordinates, but it doesnt take into account that there might be e.g. a hill under the mouse and selects the tile behind it instead.

Is there a generalized form algorithm for this? I need a generalized form because all the variables are unknown (I'm writing a game engine):

* Tile width (as in the width of a single tile rectangle)
* Tile height (as in the height of a single tile rectangle)
* Tile depth (as in how much Y offset each level contributes)

I suppose one option is run down the map with something like this (pseudo code):

```
p = screenToMap(screenPos)
bestMatch = null

for (x=p.x, y=p.y, z=0; x<mapWidth && y<mapHeight; x++, y++, z++) {
  b = highestPlacedBlockInPos(x, y)

  if (b.z === z) bestMatch = [x, y, z]
}

```

But I'm wondering if there's a better way? This seems pretty ineffective especially if you have a big map.

# Answer
Depending on the specific requirements, it might be better to use a color picking system rather than converting the coordinates back manually.

Basically give every selectable object/tile a unique color and when you render the object also render it's silhouette to a secondary unseen buffer. Then when the user clicks look up the color at the coordinates they clicked and look it up.

This would allow you to ensure that what the user clicks on is what they select. You could select a plane flying high above the ground for example. Or pick out a object in a stack of overlaying ones. It is also more general solution that could work with any rotation and completely different engine types. You can even expand on it to do per-polygon picking in 3D.

Of course it has the cost of some extra memory (for the buffer) additional rendering time (possibly a 2nd pass depending on what you are using to render) and having to keep track of the objects. Neither of which would be an issue on any hardware now days (or decades ago even).
> 3 votes

# Answer
Another approach could be to store your tiles as an array or stack of tiles for each x, y. So let's say ..

```
map[1, 2] = ["grass", nil, "hill"]

```

You can just take the mouse coordinates and calculate the map coordinates and just take the top tile as what the user selected.

The catch to this is that the "hill" tile's coordinates are actually x=3, y=4, z=2. But for rendering and click detection purposes it belongs to x=1, y=2. Note that if you don't actually care about being able to calculate the real coordinates of the top tile, and just want the tile itself, you can leave out the nils. They're just there to preserve depth.

Another upside to this approach is say the player is located at x=1, y=2 and you want to show the tile the player is standing on and perhaps show overlapping tiles at 50% transparency you just draw the top tile at 50% before drawing the player, then draw the bottom tile.

If you don't actually want to store your map data this way you can do something like ..

```
for (x=0; x<map.width; x++) {
    for (y=0; y<map.height; y++) {
        for (z=0; z<map[x, y].depth; z++)
            //not entirely sure how you're storing your tiles
            render_map[x - z, y - z].add(map[x, y].tile_at_depth(z))
        }
    }
}
//Doesn't preserve depth with nils

```

I'm making some assumptions about your map object but I think you get the idea. Hope this helps.
> 1 votes

---
Tags: 3d, isometric, coordinates
---


# Question
Title: What's the difference between a "Release" Xbox 360 build and a "Debug" one?
I've got a build of my game that works on Windows under a release and debug build as expected. When I deploy the debug version of the game to the Xbox, it works as expected and runs the same as on Windows - however when I deploy the release version to the XBOX I get different behaviour within the game.

I'm using a 3rd party library for the collisions (which is where I am seeing differences between the release and debug versions of my game); so I can't see what's actually different but I suspect they have some compiler directive for Debug on the Xbox to the Release version on the Xbox.

As such, I'm thinking that I may need to release my game with the Debug build instead of the Release build but I want to know what issues I can expect by doing so? Are there any significant performance issues between the two build profiles?

# Answer
> 3 votes
One behavior I've seen happen regularly in Debug builds that doesn't happen in release builds: in Debug builds, 'uninitialized' memory (including notably the stack) tends to be memset to 0, and so in particular variables that aren't explicitly initialized will often start with a value of 0; in release mode builds this doesn't happen, so these variables are *truly* uninitialized and will have undefined values. While the compiler should warn you about usage of uninitialized variables, that doesn't always work across function boundaries, and that would be the first thing that I'd look for.

# Answer
> 0 votes
In debug mode the compiler emits debug symbols for all variables and compiles the code as is. In release mode, generally some optimizations are included:

* Unused variables do not get compiled at all
* Some loop variables are taken out of the loop by the compiler if they are proven to be invariants
* Code written under #debug directive is not included.

As for performance, there is probably a very slim margin of 1-2% if at all, usually it runs just the same. Essentially though a release version is when you're done with the game, all bugs are worked out, and its what you release, hence the name.

But there is no significant performance change though. On the other hand though, significant performance change is possible, due to the number of tools available at compile time for the JIT.

> Due to different \[Debugger\] attributes emitted by the compiler. (RELEASE is IgnoreSymbolStoreSequencePoints, DEBUG is EnableEditAndContinue). This attribute does limit the number of 'tools' that the JITter is allowed to use at runtime. In addition the JITter will NOT inline on DEBUG builds

Gotten mostly from this question here: https://stackoverflow.com/questions/2446027/c-sharp-debug-vs-release-performance/2446062#2446062 as well the comment to my answer by Jonathan Dickinson (Thank you for adding that)

Also read comments, and thanks to Drackir for pointing it out.

---
Tags: xna
---


title: Rotating around a non origin point

text:
# Question
Title: Rotating around a non origin point
I've been looking around the forums for some answers to the question I have. I've found some answer that seem to help but nothing that answers my specific question. That question being how to rotate an object in world space around a non origin point.

I have a grappling hook that I am trying to implement inside of a game I am making for a final college project. This grappling hook collides with another object in world space and I then want the player to rotate around this point as if a rope were present.

I have the point at which the grapple collides the point at which the player is located and the origin. I tried the standard translate to the origin rotate and translate back and that did not work.

This is being done in DirectX 9 and it is a C++ game. Any help you could offer would be greatly appreciated. If you need anymore info please ask.

Edit: I should also add that we are doing a vector based storage for this setup. So I store the matrices in vectors(i.e Forward,Direction,Right,Position) and build the matrices on the fly

```
void CSpatialFrame::RotateAbout(D3DXVECTOR3 _Point, float _fDegPitch, float _fDegYaw, float _fDegRoll)
{
    D3DXMATRIX RotationMatrix;
    D3DXMatrixRotationYawPitchRoll(&RotationMatrix, D3DXToRadian( _fDegYaw ), D3DXToRadian( _fDegPitch ), D3DXToRadian( _fDegRoll ));
    D3DXVECTOR3 playerPos = m_Position;
    m_Position = _Point;

    D3DXMATRIX PlayerMatrix;

    PlayerMatrix._11 = m_RightVector.x;
    PlayerMatrix._21 = m_RightVector.y;
    PlayerMatrix._31 = m_RightVector.z;

    PlayerMatrix._12 = m_UpVector.x;
    PlayerMatrix._22 = m_UpVector.y;
    PlayerMatrix._32 = m_UpVector.z;

    PlayerMatrix._13 = m_DirectionVector.x;
    PlayerMatrix._23 = m_DirectionVector.y;
    PlayerMatrix._33 = m_DirectionVector.z;

    PlayerMatrix._14 = m_Position.x;
    PlayerMatrix._24 = m_Position.y;
    PlayerMatrix._34 = m_Position.z;

    D3DXMatrixTranslation(&PlayerMatrix, _Point.x, _Point.y, _Point.z);

    //D3DXMatrixTranslation(&PlayerMatrix, m_Position.x, m_Position.y, m_Position.z);

    D3DXMatrixMultiply(&PlayerMatrix, &RotationMatrix, &PlayerMatrix);

    //D3DXMatrixTranslation(&PlayerMatrix, _Point.x, _Point.y, _Point.z);

    m_RightVector.x = PlayerMatrix._11;
    m_RightVector.y = PlayerMatrix._21;
    m_RightVector.z = PlayerMatrix._31;

    m_UpVector.x = PlayerMatrix._12;
    m_UpVector.y = PlayerMatrix._22;
    m_UpVector.z = PlayerMatrix._32;

    m_DirectionVector.x = PlayerMatrix._13;
    m_DirectionVector.y = PlayerMatrix._23;
    m_DirectionVector.z = PlayerMatrix._33;

    m_Position.x = PlayerMatrix._14;
    m_Position.x = PlayerMatrix._24;
    m_Position.x = PlayerMatrix._34;
}

```

# Answer
Translate the character so that the rotation point is the origin. Perform the rotation. Translate back.

Pretty standard linear algebra an affine transformation stuff. You might consider browsing for an intro to linear algebra for game programmers article and find one that you like. I don't know of any particularly excellent ones myself, sorry. Quite sure they're out there though.
> 5 votes

---
Tags: c++, directx, software-engineering
---


# Question
Title: Why is my mesh generation algorithm not working properly?
I am trying to generate a grid in OpenGL ES, using known methods for triangle strips and stitching as shown in: this post and this post

The code below, generates the vertices for a 4x4 grid with a spacing of 1 unit and then indices for a triangle strip to render the mesh as is commonly done. The coordinates as shown look fine and the indices look fine too. I am just not able to figure out what is wrong. The output is as shown in the attached image.

I hope its something silly that I am overlooking.

```
int total_verts = width * height;
int verts_first_plus_last = width *2;
int verts_between = total_verts - verts_first_plus_last;
int rows_between = height - 2;
int total_indices = verts_first_plus_last + (2*verts_between) + (2*rows_between);
float vertices[] = new float[total_verts*3];
short indices [] = new short[ total_indices  ];

float xCoord = 0f;
float yCoord = height - 1f;
float zCoord = 0f;

for(int x=0;x<total_verts;x++)
{
    vertices[x]   = xCoord;
    vertices[x+1] = yCoord;
    vertices[x+2] = zCoord;

    System.out.print("(" + xCoord + "," + yCoord + "," + zCoord + "),");

    xCoord= (xCoord + xDelta) % width;
    if(xCoord == 0 )
    {
        yCoord = (yCoord - yDelta) % height;
        System.out.println();
    }
}

System.out.println("\n\nIndices:");

int vert_no = 0;
int ctr =0;
int vert_ctr = 1;

boolean fwd = true;
//0,4,1,5
while(ctr < total_indices)
{
     if(fwd)
     {
         indices[ctr] = (short) vert_no;
         ctr++;
         fwd = false;
     }
     else
     {
         indices[ctr] = (short) (vert_no + width);

         if( vert_ctr % width == 0 && vert_ctr < total_verts - width)
         {
             indices[ctr+1] =  (short) (vert_no + width);
             indices[ctr+2] =  (short) (vert_no + 1);
             ctr+=3;
         }
         else
         {
             ctr++;
         }

         vert_no++;
         vert_ctr++;
         fwd = true;
     }

}

for(int x=0;x<indices.length;x++)
{
    System.out.print(indices[x]+",");
}

```

Vertices Generated:

```
(0.0,3.0,0.0),(1.0,3.0,0.0),(2.0,3.0,0.0),(3.0,3.0,0.0),
(0.0,2.0,0.0),(1.0,2.0,0.0),(2.0,2.0,0.0),(3.0,2.0,0.0),
(0.0,1.0,0.0),(1.0,1.0,0.0),(2.0,1.0,0.0),(3.0,1.0,0.0),
(0.0,0.0,0.0),(1.0,0.0,0.0),(2.0,0.0,0.0),(3.0,0.0,0.0),

```

Indices:

```
0,4,1,5,2,6,3,7,7,4,4,8,5,9,6,10,7,11,11,8,8,12,9,13,10,14,11,15

```

# Answer
You are overwriting your vertex data by writing 3 floats but only incrementing the index once. You might want to change your loop to increment 3 at a time or multiplying by 3.

```
for(int x=0;x<total_verts;x++)
{
    vertices[x]   = xCoord; // should be vertices[3*x]
    vertices[x+1] = yCoord; // should be vertices[3*x+1]
    vertices[x+2] = zCoord; // should be vertices[3*x+2]
    ...
}

```

You could have detected this by printing out the contents of the vertices array afterwards.
> 6 votes

---
Tags: opengl-es, dynamic-mesh
---


title: loading a sequence of obj in java

text:
# Question
Title: loading a sequence of obj in java
I have 90 obj for an animation and currently using LWJGL. How would I be able to load them in sequence for 3000 seconds (a frame every 33 milliseconds)?

# Answer
> 0 votes
My first suggestion: **don't use Wavefront .obj for animation**. You're getting tons of keyframes for your data, but you have hope of interpolating between them, unless you make absolutely sure the indices stay the same. Instead, why not try COLLADA? It supports vertex animation, skeletal animation and simple node transformations, with a lot less keyframes.

In answer to your question: I would suggest loading the future frame you want to display while displaying the current one. This is known as double buffering. So if your animation is 3 frames:

* Load frame 0
* Load frame 1
* Display frame 0
* Load frame 2
* Display frame 1
* Load frame 0
* Display frame 2

This ensures that you always have something to display, even if loading a frame takes a bit longer than you anticipated.

---
Tags: java, obj
---


title: Publish Python Game

text:
# Question
Title: Publish Python Game
I wrote a Python game in for a group project using Pygame. Now we wanted to package it into an executable but I can't seem to do it. When I was working with C# through Microsoft Visual Studio it had a really simple publish feature. Is there an editor that can do that for Python with external libraries?

# Answer
> 1 votes
I've had luck compiling to executable using PyInstaller. Another possibility, as Luiz mentions, is py2exe.

Both of these tools have options to bundle all of the python libraries into the executable if you want, making it easy to distribute. Either of these might have issues with whatever libraries you might be using, so it might be easiest to check the forum of the libraries you're using to see if they have a recommendation.

# Answer
> 4 votes
Well, I'm really new in Python's World. But maybe py2exe can help you.

# Answer
> 0 votes
The technical part of publishing is described correctly in Luiz's answer, but publishing also involves licensing your game, usually. For that, I suggest you use the Mit license, if you plan to make it unprofitable and aopen-source.

---
Tags: python, publishing
---


title: Unicode Usage in Video Games

text:
# Question
Title: Unicode Usage in Video Games
When programming Windows games, do you use multibyte character settings or Unicode character settings? I'm under the impression that professional companies today use the Unicode setting to make future localization and translations as easy as possible. Is using wchar's a good practice for modern games?

While I'm thinking about the subject, what is the difference between multibyte character sets and Unicode sets in Windows? Is it UTF-8 vs. UTF-16?

# Answer
I turn to the always-excellent Qt documentation regarding the `QString` class:

> QString stores a string of 16-bit QChars, where each QChar corresponds one Unicode 4.0 character. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.)
>
> In addition to QString, Qt also provides the QByteArray class to store raw bytes and traditional 8-bit '\0'-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application's market at some point. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (e.g., with Qt for Embedded Linux).

And this how I use the class in my games: `QString` for everything, unless I absolutely need the performance. It's very nice, because you don't have to worry about encodings *at all*. `QString` also provides methods to convert its internal representation to ASCII, UTF-8, Latin-1, and UCS-4.

But if you don't want to use Qt (understandable), my advice would be to do everything in UTF-8. It's the most flexible codec and it provides backwards-compatibility to ASCII. It is, however, a bit of a hassle to work with.

Further reading from the trenches: Wolfire talks about supporting Unicode in file paths They decided to go for UTF-32, because that's the common ground between their platforms.
> 4 votes

# Answer
I would avoid the use of wchar and tchar as they are Windows only, while you did specify Windows in your post I think it's always good to have portability.

The short answer is use UTF-8 everywhere you can.

If you really only want to deal with windows then use the Microsoft only characters.

UTF-16 is used in Windows, Java, Qt, and a few other places. But it's not because it's the best choice, it's actually a historical artifact. Originally there was a thing called UCS-2 which was 16-bit characters but a codeunit and a codepoint where the same thing. It only covered the Basic Multilingual Plane which was though to be enough back then and Windows and Java both jumped on board.

But since then we have needed to go beyond the BMP (for example China has thousands of characters, also they have come up with their own encoding system that is government mandated just to mess with things more GB 18030 but that's another issue).

In order to give backwards compatibility UCS-2 become UTF-16 which now meant that a codepoint could be represented by multiple codeunits (the 16 bit blocks).

What this means is that UTF-16 and UTF-8 must have every character analysed to check to see if it's 1 single code point or multiple (if you want to truncate the length of a name for example you can't just do it on bytes or you may get half a UTF codepoint and end up with gibberish). UTF-32 doesn't have that issue so some people incorrectly recommend just using UTF32 everywhere for 'efficacy', but they are wrong as every UTF encoding things must still be analysed as you now have glyphs that can be made up of multiple codepoints (for example adding a accent to a letter).

UTF-16 and UTF-32 both use more memory (UTF16 can save some if your encoding something like Chinese), now days it generally isn't such an issue but there's no sense in doubling the amount of memory you use. With video games though it's probably much more of an issue. Also with UTF-16/32 endianness is an issue.

UTF-8 is normally much smaller and much more widely supported. You don't need to use any special char's, but you do need to use special library functions when manipulating text (are you getting the size of the string in bytes, the number of codepoints or the number of visible glyphs?).

With video games, you normally control the text rendering. So using whatever you want internally should be fine, you only have to deal with conversions for external API's.

With Windows, Microsoft have their own non-portable functions that accept tchar/wchars so if your using them you will need to convert to UTF-16. For games, this is probably only an issue with things like setting the window title, message boxes and filenames (which have other issues such as slashdirection). I'm not sure how Direct X does text rendering though.
> 4 votes

# Answer
Generally, **yes** you should

```
#include <tchar.h>

```

and use wide-character strings where possible.

The `TEXT()` macro will prepend an `L` to a string if `_UNICODE` is defined in your compiler settings (which it always should be!)

```
TCHAR* str = TEXT( "some string" ) ;

```

Becomes

```
WCHAR* str = L"some string" ; // _UNICODE defined

```

Or

```
char* str = "some string" ; // _UNICODE NOT defined

```

I know it's annoying, but I have this function

```
wchar_t* getUnicode( const char* ascii )
{
  int len = strlen( ascii ) ;
  WCHAR * wstr = new WCHAR[ len+1 ] ;

  MultiByteToWideChar( CP_ACP, 0, ascii, len, wstr, len ) ;
  wstr[ len ] = 0 ; // add null terminator

  return wstr ;
}

```

to convert an ASCII character string to `WCHAR` where required.

I know it's annoying, but you should probably get used to it and stick to `TCHAR` and `WCHAR` wherever possible.
> -1 votes

---
Tags: windows
---


# Question
Title: How do I render an animation where some frames appear twice?
I am animating a sprite. The sprite has 7 different frames, but the animation is 10 frames long. This is because 3 of the original frames appear twice in the animation:

```
3 -> 4 -> 5 -> 6 -> 4 -> 3 -> 2 -> 1 -> 0 -> 2

```

Frames 2, 3 and 4 appear twice. This avoids having to store duplicate frames in the spritesheet.

How can I render the animation in this sequence with repeated frames?

# Answer
> 4 votes
1. Record your animation sequence into an array;
2. Remember the step you show at this frame;
3. When next frame is coming, make the step increase, if step becomes more than animation length - set it to 0 again;
4. Now you have looped animation.

---

```
AnimStep: Byte; // Currently displayed animation frame
AnimSprite: array [3, 4, 5, 6, 4, 3, 2, 1, 0, 2]; // Array of frame ids in a loop
AnimLength: Byte; // total array length

Render
{
  ..
  AnimStep = (AnimStep + 1) mod AnimLength; // Increase by 1 and reset to 0 at the end
  RenderSprite(AnimSprite[AnimStep]);
  ..
}

```

# Answer
> 2 votes
```
var animationSequence = [3, 4, 5, 6, 4, 3, 2, 1, 0, 2];
var currentFrame = 0;
var totalFrames = animationSequence.length;

// to advance a frame which will wrap round once it reaches the end
currentFrame = (currentFrame + 1) % totalFrames;

// to get current frame
var animationFrameToPlot = animationSequence[currentFrame];

```

An example to see it working in jsFiddle

---
Tags: animation, javascript, spritesheet
---


# Question
Title: How can multiple clients be out of sync if they use the same RNG seed?
I have been working on a client-server architecture to enable LAN play for my open source game, Aigilas. In its current state, players stay synced in all running instances of the game but enemies and particle animations are out of sync.

What I cannot understand is how players are the only entities staying synced. I run the clients in lockstep, requiring the latest input states from each client to be announced before taking a turn in the game world. When the game world is built, I seed the random number generator (RNG) with a seed determined by the server. This seed appears to affect the RNG as expected; each client has the same procedurally generated game world and players start in all clients at the appropriate locations.

Particle animations and AI are chosen based on player positions and the RNG. How is it possible for them to become out of sync when the players are always in sync? To the best of my observations of both the game screen and the logs, players never go out of sync with respect to their positions. That leads me to believe that the RNG in C# is not acting deterministically across all clients.

The basic workflow for the game's client\<-\>server communications are as follows:

1. Server starts
2. Client starts and gets RNG seed from server
3. Client tells server when keys are pressed/depressed by a user
4. Once a game has started, server tells all clients the current state of each player's keyboards
5. Once an update has been received from the server, one turn of the game is simulated
6. Repeat step 4

If there are any specific questions targeting a specific portion of the code, then I am happy link to the appropriate page on GitHub.

# Answer
> 8 votes
My guess is that the rng's are generating at different speeds. For instance, if a game is updating at 60 times per second, then theoretically it should be in sync with other games updating at that time. But if a game is updating at a different time, it will either generate future or past numbers generated by the master generator(the server).In other words, are you generating a random number at fixed time?

# Answer
> 1 votes
This completely synced approach only works if the (gameplay) framerate of both games is the same and unsynced values aren't used in sync-relevant calculations (for example isLocalPlayer or getCurrentTime), also the input has to be executed on all clients at the same frame and everything needs to be calculated in the same order.

If you need random numbers outside of the sync-relevant calculations you need two RNGs, one which is synchronized, and one which is not. This is because with every number you generate the seed changes, so for some results it must be called in the same order and with the same frequency.

# Answer
> 1 votes
> particle animations are out of sync.

Does this matter? Normally I would not be running particle animations off the same random number generator that I use for important gameplay anyway.

> That leads me to believe that the RNG in C# is not acting deterministically across all clients.

Why not simply log the results? Every time you generate a random number, log it. Then compare the lists from 2 clients.

---
Tags: xna, c#, multiplayer, client-server, random
---


# Question
Title: Normalization of Vectors: Return a copy of the result or alter the object itself?
When calculating the normal of a vector, which is considered canon:

Returning a copy:

```
Vector2D Vector2D::Normalize() const {
    double a1 = GetX();
    double a2 = GetY();
    double a3 = GetZ();
    double length = GetLength();
    assert(Math::IsEqual(length, 0.0) == false);
    if(Math::IsEqual(length, 0.0)) {
        throw Exception("Can not normalize a Null Vector.");
    }
    return Vector2D(a1 / length, a2 / length, a3 / length);
}

```

Or altering the object itself?:

```
void Vector2D::Normalize() {
    double a1 = GetX();
    double a2 = GetY();
    double a3 = GetZ();
    double length = GetLength();
    assert(Math::IsEqual(length, 0.0) == false);
    if(Math::IsEqual(length, 0.0)) {
        throw Exception("Can not normalize a Null Vector.");
    }
    SetTerminal(a1 / length, a2 / length, a3 / length);
}

```

P.S. `IsEqual` verifies the following: `(std::fabs(a - b) <= 0.0001)`

# Answer
> 8 votes
You should have both versions, but not in the same place.

A function that takes a simple object like a vector generally should not modify it. Why? Because then you couldn't do this:

```
normalize(vec3(0.3, 0.0, 0.0));

```

If `normalize` takes a `vec3&`, then you can't pass it as a temporary in C++. You must use a named variable, for no real reason. It's also a lot harder to use it as part of an expression:

```
normalize(someVec + someVec);

```

At the same time, if you have a vector, it's not a bad idea to want to be able to normalize it in-place. For that, you use a member function, which is your indication that you're *modifying* the object, not simply returning a new one.

So your member `normalize` should be non-const, but your free function version should take its argument by `const&`.

# Answer
> 3 votes
There's no reason not to have both.

That said, I would lean towards returning a copy. It makes the code using your math library much more natural and readable. Some reasons for modifying in place were performance concerns, but honestly modern compilers do not have any trouble with optimizing away returned copies of temporaries. Turn on SSE2, fast math, and LTCG on MSVC 2010+ (or the equivalents in GCC 4.5+) and you'll be unlikely to optimize any gnarly "fast" API better than the compiler can optimize an easy to use "naive" API.

(As always, benchmark and check any optimization assumptions.)

# Answer
> 2 votes
I would always have both, because:

* I don't want to have to use clone/copy methods every time I need a modified copy.
* I don't want to have to type a whole assignment statement every time I want to modify the original.

I suggest implementing both, and using naming to distinguish them: eg. `normalize()` modifies the object in place, and `normalized()` returns a normalized version of the object.

# Answer
> 0 votes
I really like the approach where the vector itself gets normalized. Why? Because in a lot of cases you won't need the original vector after normalization. If you do, a `clone` or `assign` method should be simple to implement and help in these cases.

So if I need to keep my original vector and a normalized copy:

```
Vector2D vectorCopy;
vectorCopy.assign(myVector);
// or vectorCopy = myVector if you're implementing this in
// a language that allows operator overloading
myVector.Normalize();

```

What I encountered quite a bit when working with vectors is that I want to normalize a vector, but know about the length it had beforehand. With a bad Vector class implementation, this would look like this:

```
float length = myVector.Length();
myVector.Normalize();

```

This will use a square-root twice which is totally unnecessary. Especially when you use operations like this frequently (eg. several times in an update loop), you're going to start appreciating implementations where the `Normalize` method also returns the length of the vector before normalization:

```
float length = myVector.Normalize(); // <3 <3

```

# Answer
> 0 votes
Another consideration I would offer in favor of returning a copy would be to make your vector class immutable. This could simplify any future development involving asynchronous operations (a likely scenario where vectors are concerned). https://stackoverflow.com/questions/7970438/immutable-data-and-locking is a simple discussion. There are plenty of other deeper discussions on the subject.

---
Tags: c++, vector, normals
---


# Question
Title: Strange behavior for "make x face y" algorithm (with video)
I know, I know, on the internet there are a lot of tutorial on how to get the angle between the center of two objects or "make x face y".

I have this code:

```
//  (180 / PI = 57.3065)
float AngleBetweenVectors(sf::Vector2f, sf::Vector2f);
float AngleBetweenVectors(sf::Vector2f a, sf::Vector2f b){
   return 57.3065f * atan2(b.y - a.y, b.x - a.x);
}

```

that get the angle, and then this code that I use to set the rotation:

```
float angle = AngleBetweenVectors(player_p, cursor.getPosition());
player.setRotation(angle);

```

where `player_p` is the player center position (a 50x50 square sprite), `cursor` is the cursor sf::Sprite I use and `player` is the player sf::Sprite.

But when I run it it gets this kind of problems: video here

As you can see on the border of the terrain it gets a little bit tricky. Why is that? I'm using two views, and this is the code of the main loop regarding views and drawing:

```
window.clear(sf::Color(0, 0, 0, 255));
window.setView(camera); // camera view
// start drawing
    terrain.draw(); // terrain blocks
    window.draw(player); // player sprite
    window.setView(cursor_camera); // cursor view
        window.draw(cursor); // cursor sprite (the circular one)
// end drawing logic
window.display();
window.setMouseCursorVisible(false); // no mouse pointer please

```

The player sprite in the video is the orange one, the black circle is the cursor sprite. The player sprite is moved via WASD and the cursor sprite via mouse movement. Thanks.

# Answer
Looks like you're mixing coordinate systems. Your cursor is in screen space; your player is in world space. So, when you move a couple of screens down, the player has a Y value of something like 2000, but the cursor position will be between 0 and 1000, so the angle will always end up looking back up the screen.

Either transform the position of cursor into world space or the position of the player into screen space before you calculate the angle between them. You don't actually change the underlying value, just calculate the transformed value in order to perform the comparison.

Usually in 2D top-down games the difference between screen space and world space is just that screen space is offset from world space, to represent where the camera has moved to. So the coordinate space transformation would look like this:

```
sf::Vector2f screenToWorldSpace(sf::Vector2f screenPoint)
{
    // Take a copy
    sf::Vector2f worldPoint(screenPoint);
    // Translate it based on the camera/screen's current offset
    worldPoint.x += camera.GetRect().Left;
    worldPoint.y += camera.GetRect().Top;
    // All done!
    return worldPoint;
}

```
> 2 votes

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


title: Help with Music Rhythm Game (Cocos2D)

text:
# Question
Title: Help with Music Rhythm Game (Cocos2D)
I'm basically new to the whole idea of Cocos2d.. i am aware of CocosDhension.. however, i still cant get the idea of working around it..

My idea, i would like to try to create something like "Tap Tap" .. a simple game.. where music is played and notes fall till the points where u have to hit the notes.

Question: where do i start from here as i have no idea how to go around this.. i have a basic logic in my head whereby i analyze the beat of the music and drop the notes accordingly?

can someone please give me a head up about this?

help is much appreciated!

thanks!

# Answer
> 1 votes
For this kind of game you have many possibilities to do. It depends what you really want. If you know the musics in advance (already packaged into your application) the most simple is to create your own file format with its own structure. Then you can join each music file with the description file which contains the time of each beats.

Otherwise if you want analyze the sound in live, I don't think CocosDenshion is a good choice. You should consider to use the Apple Audio Unit framework. It is best way to have a low level and performant audio analyzer. However it is hard to use.

I hope it should help you, but I can't given you more details about the implementation.

---
Tags: cocos2d, music
---


# Question
Title: RPG combat and gold/exp reward equations
I have a game that I'm creating, but I'm running across issues in keeping the ratios between high and low level players similar in the battle and reward equations. Obviously a higher level player should receive less experience, but have the upper-hand in battle when fighting lower level players and monsters. Here is how I'm calculating things currently:

Battle starts If player.dex \> enemy.dex Accuracy = ((player.dex - enemy.dex)/2)\*20

If player.dex \< enemy.dex Accuracy = ((enemy.dex\*player.dex)-enemy.dex)/player.dex

Accuracy is a percentage tested against a roll of a 100 sided die.

If accuracy \> roll Hit success

If accuracy \< roll Hit fails

If hit success All of the attacker's damaging items (spiked helms and shields, weapons, etc.) are added together and applied as such: Damage = (player.str + item.damage)-(enemy.dex + enemy.armor)

If the player is fighting a monster, I have a base amount of gold and experience which is modified according to the player: Gold gained = (enemy.gold\*rand(1,10))/player.level Exp gained = (enemy.exp\*rand(1,3))/player.level

If the player is fighting another player, then there will have to be a different equation for the rewards, but I'm not sure how to go about creating that one.

As this is my first attempt at creating (though I'm an avid RPGer), I'm not sure if there is kind of an "industry standard" form of calculating these things or not. I'm also afraid that these equations won't hold up once the player reaches higher levels (say level 50+).

# Answer
> 6 votes
There is no "industry standard" ( why do you think there are so many different systems? DnD/PF/d20, WoD, d6, GURPS, etc... ) when it comes to comparing two players and balancing the game.

@hustlerinc has a pretty good answer that focuses on the difference in player level, and handles it fairly between two people only taking into account their level.

I would revise your equations to something more like this:

> Battle starts If player.dex \> enemy.dex Accuracy = ((player.dex - enemy.dex)/2)\*20

The equation itself looks alright, but you're doing extraneous math. `(player.dex-enemy.dex)*10` gets you the same result. This now shows us the problem: If player.dex is ever 10 above enemy.dex, he will always hit. If your stats are reasonably bound ( something like 8-25 ), should keep more or less balanced. Additionally, what if they have equal stats? neither could ever hit the other.

> If player.dex \< enemy.dex Accuracy = ((enemy.dex\*player.dex)-enemy.dex)/player.dex

This equation just looks terrible. Without knowing the range for stats, this equation makes absolutely no sense.

> Accuracy is a percentage tested against a roll of a 100 sided die. If accuracy \> roll Hit success If accuracy \< roll Hit fails

Standard type stuff. I would actually suggest a different system. Start at 50% chance to hit. Use some sort of curved algorithm to determine the change in chance for one side or the other. For instance, 10v10 = 50%, 11v10 = 59%, 12v10 = 66%, 13v10 = 71%, etc. etc. For every point above the opponent, give them a bonus, but have it be decreasing return per point. Again, it depends on what your proposed ranges are.

> If hit success All of the attacker's damaging items (spiked helms and shields, weapons, etc.) are added together and applied as such: Damage = (player.str + item.damage)-(enemy.dex + enemy.armor)

This could go extremely wrong. Suppose your player is using a ranged weapon ( which is usually based off of dex ), and the enemy is using a melee weapon ( based off of str ). This gives an inherent advantage to melee weapons, mechanically speaking.

> If the player is fighting a monster, I have a base amount of gold and experience which is modified according to the player: Gold gained = (enemy.gold\*rand(1,10))/player.level Exp gained = (enemy.exp\*rand(1,3))/player.level

This I disagree with vehemently. Never divide by player level - you end up making a logarithmic ( reciprocal of x ) curve. Simple put, upon moving from level 1 to level 2, the character now gains half experience and half gold. From level 2 to level 3, he gains two-thirds of what he gained at level 2. Then 3/4, 4/5, 5/6, etc. The difference in gain from one level to the next approaches zero.

There are a couple of ways to deal with experience and gold. I find I tend towards the low multiplier method. Essentially, each level above 1, the amount of experience you need for the next level increases by a low multipler, something in the .125-.25 neighbourhood. However, this is cumulative. You end up with an equation for XP like such: `baseXP * ( ( 1 + XPmod)^level )`

# Answer
> 1 votes
First, I will tackle the problem of Accuracy, since it does actually have a correct solution in my opinion.

The problem with your equation for accuracy is that it depends on the *difference* between the dexterity, not the ratio between them. Here is what I suggest.

AccuracyInPercent = 100 * PlayerDexterity / (PlayerDexterity + OpponentDexterity)

If your random number, between 0 and 100, is less than the Accuracy, then it is a hit, otherwise it is a miss.

This means that no matter how powerful either person is, he will never get hits 100% of the time. It also means that a player with three times the dexterity of his opponent has a three times higher chance of winning.

Another advantage is that this will work with any range of stats.

---

As for the gold that will be rewarded, it *could* be related to the chance that the person wins the battle. There will be two constant numbers involved, **A** and **B**. **B** will be the baseline amount of gold won, while **A+B** will be the maximum amount of gold that could be won.

Gold = **A** * OpponentDext / (PlayerDext + OpponentDext) + **B**

This system means that a weak player beating a strong player will win more gold than vice-versa. This also means that no player will win too much gold from one battle.

One effect of the above equation is that a player with 200 dext will win as much gold by beating a 100 dext opponent as a 2 dext player beating a player with 1 dext opponent. To avoid/increase this, you could change **A** and **B** depending on the players involved.

# Answer
> 0 votes
I would've done it like this:

Player level - enemy level = difference.

Then take the difference, multiply it by the amount you want to decrease reward for each level difference.

decreaseTotal = decrease (for example 0.05) * difference, this would give 0.15 if the difference is 3 levels.

Take the reward and multiply it by reward * (1 - decreaseTotal) and you have a percentage of total reward. In this case 85%.

This is the simplest of solutions.

---
Tags: game-design, game-mechanics, rpg
---


title: How to Align Gun with Bullets

text:
# Question
Title: How to Align Gun with Bullets
I have a top-down 2D shooter. I have an image of a player holding a gun, that rotates to face the mouse. Please note that the gun isn't a separate image tethered to the player, but rather part of the player. Right now, bullets are created at the player's x and y. This works when the player is facing the right way, but not when they rotate. The bullets move in the right direction, but don't come from the gun. How can I fix this?

TL;DR: When the player rotates, bullets don't come from gun.

```
public void fire() {
    angle = sprite.getRotation();
    System.out.println(angle);
    x = sprite.getX();
    y = sprite.getY();

    Bullet b = new Bullet(x, y, angle);
    Utils.world.addBullet(b);
}

```

# Answer
> 6 votes
Let `x`, `y` be the offset of the end of the barrel from the (unrotated) sprite's center, and `theta` the angle of rotation (counter-clockwise)

Then the barrel's offsets `x2`, `y2` for the rotated sprite can be calculated like this:

```
x2 = x * cos(theta) - y * sin(theta)
y2 = x * sin(theta) + y * cos(theta)

```

# Answer
> 0 votes
Telling by what you describe, the gun of the character has an offset from the player center point. So you must calculate the initial position of the bullet, it should be the end of the gun barrel.

# Answer
> 0 votes
It's not easy to tell form the code you provided (what does addBullet do? where does it draw the bullet in relation to your sprite?) nor is there information about your sprite in general (how big it is, where the origin point of it is).

However, I would hazard a guess that your gun is not located at the X,Y coordinates that the Sprite returns. However, those are the coords you pass to your bullet-drawing routine, which I am guessing draws your bullets at the point you specify.

You need to determine the offset of the gun from your sprite's origin point, and then modify your x and y values before calling addBullet:

```
public void fire() {
    angle = sprite.getRotation();
    System.out.println(angle);
    //One option, where the gun's offset from sprite origin
    x = sprite.getX() - sprite.getGunOffsetX();
    y = sprite.getY() - sprite.getGunOffsetY();

    //Another option, where you store the gun's position on the sprite
    x = sprite.getGunX();
    y = sprite.getGunY();

    Bullet b = new Bullet(x, y, angle);
    Utils.world.addBullet(b);

```

}

---
Tags: java, rotation, shooter
---


title: Get position of tile in tileset

text:
# Question
Title: Get position of tile in tileset
How can I get the position of tile 14 (or any other) when only knowing the following:
Tile ID: 14
Rows: 4
Columns: 7

The end result should be 2x4.

# Answer
> 4 votes
```
Column = TileID mod Rows
Row = TileID div Rows

```

so in most programming languages your example would be:

```
col = 14 % 4;
row = 14 / 4;

```

# Answer
> 9 votes
Such a bijective mapping is much easier to express if your tile indices and rows/columns are zero-based.

```
col: 0  1  2  3
  [  0  1  2  3  // row 0
     4  5  6  7  // row 1
     8  9 10 11  // row 2
    12 13 14 15  // row 3
    ...

```

If you look at the column numbers, as the column number increases by one, so does the tile index. More particularly, there's a pattern that for each row, it starts on a multiple of the row width, and increases by one.

This means that if we could get rid of that term, we would have our column number.

The modulus operator (commonly % in most languages) will take a number in a range \[0,n) and map it to the values 0 through n-1, *wrapping* around.

That is, `7 % 4 == 3`, `8 % 4 == 0`, and so on.

A suitable expression for the column index is thus `col = idx % width`.

For the row, we need an expression that results in the same value for all values in the row. An operation related to modulus is division, so it's likely useful.

`8/4 = 2, 9/4 = 2.25, 10/4 = 2.50, 11/4 = 2.75`, which is almost what we want. We can feed the result of that into the `floor()` operation, which truncates away the fractional part of a floating point result, or in the case of integer division, it's already done for you.

So in summary:

```
zero_based_col =       zero_based_idx % row_width
zero_based_row = floor(zero_based_idx / row_width)

```

---
Tags: grid
---


# Question
Title: Changing DisplayMode seems not to update Input&Graphic Dimension
I'm writing a small game using Slick and Nifty-GUI.
At the program startup I set the DisplayMode using the following lines:

```
AppGameContainer app = new ...
app.setDisplayMode( 800, 600, false );
app.start();

```

I wrote a Nifty-ScreenController for my settings dialog in which the user can select the desired DisplayMode. When I try to set the new DisplayMode within this controller class the game window gets resized correctly but the Graphics and Input objects aren't updated accordingly. Therefore my rendering code just uses a part of the new window.

I tried to set different DisplayModes in the main method to test if it's generally possible to invoke this method multiple times. It seems that changing the DisplayMode only works before I call `app.start()`.

Furthermore I tried to update the Graphics & Input object manually but the init and setDimensions methods are package private. :(

Does someone know what I'm doing wrong and how to change the DisplayMode correctly?

# Answer
> 1 votes
It looks that you have to use ScalableGame as a wapper for your AppGameContainer if you want to have an scalable window etc. at least thats what I found in the API.

You then can use the recalculateScale() method to update the scale of your game. I suppose you have to set the new DisplayMode before (like you try to do it now).

---
Tags: java, slick
---


title: Confused about Content Pipeline

text:
# Question
Title: Confused about Content Pipeline
I'm attempting to get my head around the XNA content pipeline, and how I can use it to simplify my game code. Specifically, I want to define sprites, sprite sheets, and animations as assets and have them automatically available to me in game code.

At the end of the day, this is what I want to be able to do:

* add a new file with *.sprite* extension to my content project
* call `contentManager.Load<Sprite>("NameOfSprite");` and get back a `Sprite` instance

My `Sprite` class looks like this:

```
public class Sprite
{
    public Texture2D Texture
    {
        get { ... }
    }

    public Rectangle? SourceRectangle
    {
        get { ... }
    }

    public Vector2 Origin
    {
        get { ... }
    }
}

```

The purpose of the `Origin` property is not important - it's specific to my game. The point is, I want it to be "packaged up" alongside the texture information.

I've defined a `SpriteData` class as:

```
public sealed class SpriteData
{
    public string TextureFilename
    {
        get;
        set;
    }

    public Rectangle? SourceRectangle
    {
        get;
        set;
    }

    public Vector2 Origin
    {
        get;
        set;
    }
}

```

And I've added a *test.sprite* file to my content project as:

```
<?xml version="1.0" encoding="utf-8" ?>

<XnaContent xmlns:data="MyNamespace">
  <Asset Type="data:SpriteData">
    <TextureFilename>Sprites\Test.jpg</TextureFilename>
    <SourceRectangle>0 5 20 25</SourceRectangle>
    <Origin>30 2</Origin>
  </Asset>
</XnaContent>

```

I have defined a `SpriteImporter` as:

```
[ContentImporter(".sprite", DisplayName = "Sprite Importer", DefaultProcessor = "SpriteProcessor")]
public class SpriteImporter : ContentImporter<SpriteData>
{
    public override SpriteData Import(string filename, ContentImporterContext context)
    {
        using (var xmlReader = XmlReader.Create(filename))
        {
            return IntermediateSerializer.Deserialize<SpriteData>(xmlReader, filename);
        }
    }
}

```

And a `SpriteProcessor` as:

```
[ContentProcessor(DisplayName = "Sprite Processor")]
public class SpriteProcessor : ContentProcessor<SpriteData, SpriteData>
{
    public override SpriteData Process(SpriteData input, ContentProcessorContext context)
    {
        var spritePath = Path.GetDirectoryName(context.OutputFilename);
        var textureReference = new ExternalReference<Texture2DContent>(input.TextureFilename);

        // make sure the texture is built (not sure what else to do here)
        context.BuildAsset<Texture2DContent, Texture2DContent>(textureReference, string.Empty);

        return input;
    }
}

```

Now I'm stuck. If I don't implement a content writer+reader combination then I won't get a `Sprite` out of the content manager - I'll get a `SpriteData` instead, which is not what I want. But my attempt to implement a `SpriteWriter` came up short. I have no idea how to get the texture information from the processor to the writer. Do I need to change the type from `SpriteData` to something else? Is there a sample anywhere that demonstrates how to do this end-to-end?

# Answer
OK, I've found *a way* to do this. Whether it's the best way, I'm unsure. Any input appreciated. The key was to have my processor spit out an intermediate type, known only to my content pipeline. Here is my processor (my importer remains as is):

```
[ContentProcessor(DisplayName = "Sprite Processor")]
public class SpriteProcessor : ContentProcessor<SpriteData, SpriteContent>
{
    public override SpriteContent Process(SpriteData input, ContentProcessorContext context)
    {
        var spritePath = Path.GetDirectoryName(context.OutputFilename);
        var textureReference = new ExternalReference<Texture2DContent>(input.TextureFilename);

        // make sure the texture is built
        var builtTexture = context.BuildAsset<Texture2DContent, Texture2DContent>(textureReference, string.Empty);

        var spriteContent = new SpriteContent
        {
            Texture = builtTexture,
            SourceRectangle = input.SourceRectangle,
            Origin = input.Origin
        };

        return spriteContent;
    }
}

```

Note the new `SpriteContent` type, which is very simple:

```
public sealed class SpriteContent
{
    public ExternalReference<Texture2DContent> Texture
    {
        get;
        set;
    }

    public Rectangle? SourceRectangle
    {
        get;
        set;
    }

    public Vector2 Origin
    {
        get;
        set;
    }
}

```

With this in place, I changed my `SpriteWriter` as follows:

```
[ContentTypeWriter]
public sealed class SpriteWriter : ContentTypeWriter<SpriteContent>
{
    protected override void Write(ContentWriter output, SpriteContent value)
    {
        output.WriteExternalReference(value.Texture);
        output.Write(value.SourceRectangle.HasValue);

        if (value.SourceRectangle.HasValue)
        {
            output.Write(value.SourceRectangle.Value.X);
            output.Write(value.SourceRectangle.Value.Y);
            output.Write(value.SourceRectangle.Value.Width);
            output.Write(value.SourceRectangle.Value.Height);
        }

        output.Write(value.Origin);
    }

    public override string GetRuntimeReader(TargetPlatform targetPlatform)
    {
        return typeof(SpriteReader).AssemblyQualifiedName;
    }
}

```

I'm guessing this could be simplified to use built-in types, but wasn't sure how because they're all `internal`. Lastly, by `SpriteReader` looks like this:

```
public sealed class SpriteReader : ContentTypeReader<Sprite>
{
    protected override Sprite Read(ContentReader input, Sprite existingInstance)
    {
        var texture = input.ReadExternalReference<Texture2D>();
        Rectangle? sourceRectangle = null;

        if (input.ReadBoolean())
        {
            sourceRectangle = new Rectangle(input.ReadInt32(), input.ReadInt32(), input.ReadInt32(), input.ReadInt32());
        }

        var origin = input.ReadVector2();

        return new Sprite(texture, sourceRectangle, origin);
    }
}

```

With that in place, this works:

```
var testSprite = this.Content.Load<Sprite>(@".\Sprites\Test");

```

So that takes care of sprites. Now I need to tackle sprite sheets and animations, but I'll leave that for next weekend.
> 3 votes

# Answer
For a demonstration of how to create a `ContentTypeWriter` and a corresponding `ContentTypeReader` for your Sprite, take a look at the excellent answer to ContentSerializerRuntimeType required in content pipeline?.

To load a `SpriteData` as a `Sprite`, you'll be interested in the `ContentSerializerRuntimeType` attribute. This attribute specifies into which class to load serialized data. I also wrote a blog with an end-to-end example, though it's a more complicated scenario than what you're wanting to do.
> 2 votes

# Answer
I see that you've posted your own solution for how you handled the particular question, but I want to post what I do with my SpriteSheet assets in case it helps you at all. Note that my answer does not define a ContentTypeWriter or ContentTypeReader because I did not need to use any special writing or reading rules. ContentSerializer knows how to serialize/deserialze at content build time / run time because I've used native types. I've supplied classes for the serialized .xnb file generated at content build time and the deserialized final product used at run time.

These are the four classes involved:

```
SpriteSheetData          (deserialized instance of XML data)
SpriteSheetProcessor     (input SpriteData, output SpriteContent)
SpriteSheetContent       (serialized at content build, deserialized at run time to Sprite)
SpriteSheet              (instance used by game)

```

Here's how my classes look (condensed for clarity):

First, define the deserialized instance of the SpriteSheetData:

```
public class SpriteSheetData
{
     public String FileName;
     public int HorizontalFrameCount;
     public int VerticalFrameCount;
     public int FrameWidth;
     public int FrameHeight;
     public int MillisecondsPerFrame;
}

```

Second, process the SpriteSheetData into a SpriteSheetContent:

```
[ContentProcessor(DisplayName = "ContentPipelineExtension.SpriteSheetProcessor")]
public class SpriteSheetProcessor : ContentProcessor<TInput, TOutput>
{
    public override TOutput Process(TInput input, ContentProcessorContext context)
    {
        String fileName = input.FileName;
        ExternalReference<TextureContent> textureReference = new ExternalReference<TextureContent>(fileName);

        TextureContent texture = context.BuildAndLoadAsset<TextureContent, TextureContent>(textureReference, "TextureProcessor");
        BitmapContent bitmap = texture.Faces[0][0];

        TOutput SpriteSheet = new TOutput();
        SpriteSheet.Texture.Mipmaps.Add(bitmap);
        SpriteSheet.FrameCount = new Point(input.HorizontalFrameCount, input.VerticalFrameCount);
        SpriteSheet.FrameSize = new Point(input.FrameWidth, input.FrameHeight);
        SpriteSheet.MillisecondsPerFrame = input.MillisecondsPerFrame;

        return SpriteSheet;
    }
}

```

Third, define the SpriteSheetContent with an attribute to identify its run time type (an instance of this class is generated at content build time):

```
[ContentSerializerRuntimeType("ContentPipelineExtensionLibrary.SpriteSheet, ContentPipelineExtensionLibrary")]
public class SpriteSheetContent
{
    public Texture2DContent Texture = new Texture2DContent();

    public Point FrameCount = new Point();

    public Point FrameSize = new Point();

    public int MillisecondsPerFrame = new int();
}

```

And finally, define the run time type with attributes to determine serialization at run time (an instance of this class is deserialized from .xnb file at run time):

```
public class SpriteSheet
{
    [ContentSerializer]
    public Texture2D Texture;

    [ContentSerializer]
    public Point FrameCount;

    [ContentSerializer]
    public Point FrameSize;

    [ContentSerializer]
    public int MillisecondsPerFrame;
}

```
> 2 votes

# Answer
I think a better approach is to import the images as texture2D assets through your ide. After that you do something like:

`Texture2D tex = Content.Load<Texture2D>(tex_string_name);`

Then reference them by string in your Sprite, Animation, etc., classes.
> -1 votes

---
Tags: xna, xna-content-pipeline
---


# Question
Title: What technology is needed for this mmorts idea?
I've got an idea for an real time strategy game like Starcraft or Age of Empires, but there is only one single massive persistent map or world with thousands of factions and each faction's units/buildings/resources are controlled by up to 64 players in team melee mode. Players can join any map and any faction they want to. Mined out resources respawn after a while if no player base or units are nearby. New players can join any time to an existing faction or create a new faction, which can be open or private. If a faction has no players online at the moment, then the computer takes over in easy mode. Units cannot be upgraded.

My question is what technologies would be included in a game like this? I have programmer background but I'm pretty new to game dev.

# Answer
> 2 votes
I don't envy the position you're in right now. You have a lot of things to research, and it's not entirely clear what it is you should research.

To know what technology to use, you would need a clearer design. But I imagine you don't want to start designing before you know what technology to use.

My advice? Start with a simple game and work up.

Beyond that? Most of the professional game engines will handle networking and 3d models. So it may just be an issue of finding the right game engine.

As for the persistent information management? You'll probably have to write that yourself. That's pretty specific.

---
Tags: mmorts
---


# Question
Title: GLSL - rewriting (geometry) shader from #330 to #130 version
I'm having trouble running example from: https://raw.github.com/progschj/OpenGL-Examples/master/07geometry\_shader\_blending.cpp My graphics card supports only #130 shaders version so I have to rewrite shaders.

I figured out how to fix vertex and fragment shaders. I removed:

```
layout(location = 0)

```

from

```
layout(location = 0) in vec4 vposition;

```

and added this into my source code:

```
glBindAttribLocation(shader_program, 0, "vposition");

```

However I have no idea how to rewrite geometry shader...

```
#version 130
uniform mat4 View;
uniform mat4 Projection;
layout (points) in;
layout (triangle_strip, max_vertices = 4) out;
out vec2 txcoord;
void main() {
   vec4 pos = View*gl_PositionIn[0].gl_Position;
   txcoord = vec2(-1,-1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
   txcoord = vec2( 1,-1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
   txcoord = vec2(-1, 1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
   txcoord = vec2( 1, 1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
}

```

The main problem is how to get rid of `location` here:

```
layout (points) in;
layout (triangle_strip, max_vertices = 4) out;

```

Can someone help me?

**EDIT:** @melak47 - I edited shader, now I'm not getting any error, but window is black.

```
#version 130
#extension GL_EXT_geometry_shader4 : enable
precision mediump float;
uniform mat4 View;
uniform mat4 Projection;
out vec2 txcoord;
void main() {
    vec4 pos = View*gl_PositionIn[0];
    txcoord = vec2(-1,-1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
    txcoord = vec2( 1,-1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
    txcoord = vec2(-1, 1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
    txcoord = vec2( 1, 1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
};

```

# Answer
Your graphics card most likely does not support geometry shaders, which require GLSL 1.50 or higher. Geometry shaders were added in OpenGL 3.2, which is the version that supports GLSL 1.50. GLSL 1.30 is part of OpenGL 3.0 which did not support geometry shaders.

I assume you are using a pre-Sandy-Bridge Intel GPU or are on Linux. Intel's drivers are complete crap before the Sandy Bridge and they don't update their older drivers at all. Linux's standard GPU drivers do not yet support geometry shaders, so you'd need to install the proprietary NVIDIA/AMD drivers if you want geometry shaders.

Update: the Asker's problem was out of date drivers. Especially with OpenGL, always keep Windows drivers up to date. OpenGL support tends to lag heavily, and also tends to be buggy. I've shipped more than a few OpenGL games that had support nightmares on Windows thanks to the drivers. If you're only targetting Windows, consider D3D. If you're multi platform, consider supporting both D3D and OpenGL if you have the time/money/manpower.
> 6 votes

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