title: Game state sharing data

text:
# Question
Title: Game state sharing data
A game is a set of Game States.

Each Game State contains game objects, may be list, may be scene graph or any other data structure.

We can use Game States as Game Locations, too.

**How do you share data between Game States**, for example, hero and his/her inventory when it moves from one location to another?

It looks like Composite (hierarchical) Game State is a good idea. For example,

```
GameState MainMenu
GameState LoadLevel
GameState Gameplay - contains inner states
    GameState Location1
    GameState Location2
    GameState Location3
    GameState MiniGame1 - contains inner states
        GameState LocationInMiniGame1
        GameState LocationInMiniGame2

```

So we can hold shared data (hero, inventory) in Gameplay object. But this approach does not look very correct and flexible. If some objects are outside scene graph (ie in the parent Game State), how would you include it in the scene graph? Via special node type that mounts different scene graphs or scene graph branches together?

If we have stack of active Game States, and each state can contain inner state machine, and scene graphs of different Game States can be mounted into one giant graph, it can become very complex system that is hard to debug.

Very interesting to read your suggestions. How do you organize game data between Game States in your real applications?

(For editors: possible additional tags: OOP, game-state.)

# Answer
> 6 votes
The concept of state stacks is very valuable and very useful in games. One particular game in my memory had the major states of "main menu", "playing a movie", "in game", and "in-game menu", with a centralized place that handled transitioning between these things. It was great because you could push a ton of crap at once and end up where you wanted to be without guessing. E.g. at startup "main menu" is pushed, then "movie" (gamelogo) then another "movie" (dev logo) then a third movie (pub logo).

Then the in-game had a ton of state, and that state was per-level. In this case it didn't make sense to make it a stack, since only one could be active at a time and the endlevel code would take care of transitioning to the next level (after pushing the load/save UI which in this case was part of the main menu).

Each level will likely have a ton of "areas" or sublevels or whatever. There is stuff that exists only in an area (e.g. the monsters), but there is the stuff that transcends the sublevels and is more appropriately "owned" by the level itself or even the in-game state "object". (The game I'm recalling had different player "costumes" in different levels, so it made sense to attach that to the level. Other games might just load a single player model and use it for the life of the in-game state.)

Some states do have sub-states though. These aren't polluting the "main" state stack, these are internal state stacks. E.g. the in-game menu will have a page stack like Ricket discusses so that "back" works uniformly. The memory card handling may be another separate stack too since it runs asynchronous to the rest of the UI.

*In short, put data where it makes the most sense to you, and don't hesitate to move it if another home becomes preferable.*

# Answer
> 9 votes
My suggestion is to not have game states like this whatsoever. Most of your essential game objects exist across and outside of all the states (eg. renderer, resource loading, input, networking, audio), and a massive amount of the rest span multiple states (eg. players, some NPCs, certain resources).

On top of that, the stack system doesn't seem to work well in practice. What if I want to bring up an options menu from within the mini-game - how is that going to differ from bringing it up from the main menu? What if I can quit the whole game from within the mini-game?

I'd ask, what value does this big state system give you? If you need to know what location you're in, store a location object or variable. If you're on the main menu, your GUI object will have a menu panel up; otherwise, it won't. Maybe there's an argument for pushing a new state when you enter a mini-game or cut-scene but I don't think I'd even do it then.

So my answer to "*how do you share data between same States*" is to not have game states at all.

# Answer
> -1 votes
I started learning programming from web development. My first steps were opening notepad, writing some HTML, saving it, and opening it in a browser. Then I wrote another HTML file and saved it. And then I made a link. Suddenly I had two pages which I could go back and forth between.

Then I got into PHP; I could handle user input! I could even save data about an user. I used cookies or the session to save data about the user between pages.

Now just a few months ago, as I was thinking and wondering the same question as you, I realized game states are like PHP pages. They're very discrete, each one being a different view of your application (game, in this case), but they need some shared data. **They need session data.**

Well, in PHP, to store something in the session you just use `$_SESSION['variablename']='value';`. Then you can later retrieve that data, from any PHP page visited by the same user in the same session, by referring to `$_SESSION['variablename'];`. Essentially, it's a **global** array, and in PHP you can easily add values to an array so it's essentially equivalent to a **Map**.

So if you want to go this route, then add a "global" Map which acts as your "session" data. This will hold all of the data that needs to be shared between game states. Or simply make it a "global" object and add all the variables you need; this is entirely up to you, based on your needs. (obviously an object will get much better performance than a Map) **\- when I say "global", I mean make it available to all of your game states. You shouldn't make it available to any other objects which don't need it. This can be done, for example, by a variable inside the gamestate namespace, or a package-private Singleton in a language like Java.**

Note this is only one way to do it. I really kind of like the way you want to attach the data to the parent Gameplay object; but in my state system I didn't really account for sub-states so I was just thinking of the PHP way.

---
Tags: architecture, state
---


title: Custom Content Package for Files

text:
# Question
Title: Custom Content Package for Files
I am about to purchase quite a few model packs from a website for prototyping my game. In the contract it states that I must protect them as to prevent the public from gaining access to them.

I remember working with the Valve games, they used .gcf (game content file) that basically was an archive of all the content for each game. They packed in sound/materials/models/maps/etc. I figured it might not be a bad idea to develop something similar to this, and just write a small tool to let me add/remove files from it.

Problem is I really have no idea how to go about starting on something like this. I tried Google but I didn't even know what to search for. If anyone has any ideas, links that might be of use, or anything else I would greatly appreciate it.

# Answer
> 9 votes
Store your data in a slightly obscure archive format such as 7-Zip.

Give them a different file extension so that a casual user can't easily open them with their zip program.

Use physfs to read and access those files. It also lets you work with files in your local directory too, so you can easily test new resources without rebuilding your packages. Highly recommended.

Consider very trivial encryption on the content, eg. XOR encryption. Write a little batch file or script to build your packages, encrypting the data as it goes in, and use the same function to decrypt the data in your game.

This won't keep a determined user out - nothing will. But it will be good enough to satisfy the requirements of your model packs.

# Answer
> 8 votes
If you're just prototyping, then I wouldn't worry about packing your assets into a GCF/ZIP/PAK file; the public isn't going to see your prototype!

Furthermore, Valve's GCF provides as much protection for your content as a ZIP file would - i.e. zero. The file is not encrypted; you can download GCFScape to browse and extract its contents.

It's not worth putting the effort into creating your own pack file system unless you have specific needs *right now* that aren't being met by ZIP files or the OS's own file access mechanism; in fact, the only reasons I can think of are:

* Content obfuscation (keeping your files free from tinkering has its uses; I still suggest its overkill for your current needs),
* Storing additional per-file metadata in a game specific way to help data-drive your content in some way,
* Getting around the OS's filesystem limitations, such as needing to access thousands of small files quickly, or ensuring contiguous data access. (This is a defacto need when working on consoles.)

# Answer
> 3 votes
This requirement is, well, bullshit.

Since the game can access the data, and the user has access to the game, if he is skilled and determined enough he'll manage to reverse-engineer the format you used to store the data and grab the eventual key if you were fool enough to encrypt it.

You cannot add security. I repeat: you **just CANNOT add security**. You can only add obscurity, and obscurity is totally pointless, since - as I said - an user with enough skill and determination will just break it.

Don't sign anything that asks you something that can't be done.

# Answer
> 1 votes
A lot of times I notice that custom content packages tend to be a .zip or .rar archive with a different extension. Of course, this is no good if the web site wants custom encryption of some sort.

# Answer
> 1 votes
A few ideas:

1\] Have you used a standard model format (eg .obj, or .x) or do you use a custom model format when loading directly into your game? If you've got a custom format, and one would have have to reverse engineer your model format to get it into a useful form, then you've already got some level of protection against the opportunistic asset ripper.

2\] Kylotan's point about XOR encryption is excellent, except to note you can encrypt using a pseudo-random number generated sequence (possibly seeded by a hash on the filename) to avoid long sequences of zeroes in your source data showing your encryption string. Of course you'd have to in-place decrypt your files immediately after they're loaded, but breaking your encrypted file into restartable blocks will allow you to kick off in-place decryption on multiple threads if this really became a load-time burden. But I seriously doubt this level of "protection" is required - particularly, as others have said, the determined ripper will get around it. eg. by intercepting the draw calls by using a DLL detour library, and reading back the vertex buffers/index buffers directly.

3\] You'd have to ask the original asset provider about their requirements for protection, but it could just be a matter of adding a blurb about asset copyrights to your program splash screen and/or to your EULA.

---
Tags: game-design, c++
---


title: Precomputing Visibility

text:
# Question
Title: Precomputing Visibility
Having noticed that UDK (Unreal) and Unity 3 include similar pre-computed visibility solutions that unlike Quake are not dependent on level geometry, I've been trying to figure out how the calculation is done.

The original Quake system is well documented: You divide the world into convex volumes that limit both the camera and the geometry. Each volume has a list of all the other volumes that are visible from it.

Visibility would be computed by firing rays at some random distribution of points in the target volume and see if any hit. And because the position of the camera in the source volume could have an effect, those thousands of rays would have to be fired from multiple places in the source cell.

So what I'm wondering is if there's any been fundamental change to this basic scheme in the intervening 15 or so years? I can see how to adapt it to a UDK/Unity scheme that has regular source volumes and deals mostly with arbitrary meshes as the targets, but is there a better way than stochastic ray testing?

# Answer
> 8 votes
On the exact analytic visibility side:

Rather than casting a gazillion ray in the hope that N=gazillion is actually enough, there are researchers who have developed analytic algorithms, which will compute exactly which triangles, objects or cells are visible from another cell (i.e., the same result as if you case an infinite set of rays).

See Shaun Nirenstein's exact visibility page for a set of publications on this subject. You may note that one of the authors of the 2005 paper is the CTO of Umbra Sotware (the visibility middleware paired with Unity 3). I don't know whether or not this technology is used in the Umbra product or not. For scenes with specific structure (i.e., cell/portal), an analytic solution is covered nicely in Seth Teller's 1992 thesis here. Jiri Bittner's thesis also presents an analytic solution.

Generally, analytic visibility is hard to get right (mathematically complex, numerical issues, speed, etc.), but if done right it would make for a compelling piece of middleware.

On the ray casting side:

The algorithm you described has been around since the late 80's (see Towards Image Realism with Interactive Update Rates in Complex Virtual Building Environments).

There have been many advances in the ray-casting approaches in the last few years. Researchers have devised algorithims that choose fewer, but better rays using heuristics, and also may compute visibility over multiple cells simultaneously. See the papers on Peter Wonka's page (Guided Visibility Sampling and Adaptive Global Visibility Sampling). These get great results.

Probably the class of technique that is still used the most today in practice is the GPU accelerated hemicube algorithms. These just sample visibility from a set of points by rendering a 6 sided cube map and reading back object/triangle/cell indices as data. Occlusion queries can also be used to reduce the amount of data read back. Algorithms based off this tend to be easy to implement and give good results in practice (fast as hell, since they use the GPU), but the sampling distribution (millions of rays cast from a realtively small set of single points), may make it take longer to converge on an accurate solution then one would think. This technique tries to choose better visibility cube source locations than a simple uniform or random sampling.

There are plenty of other visibility techniques (hundreds). I suggest reading some of the background chapters in the theses linked to, if you want to know more.

---
Tags: graphics, pipeline
---


# Question
Title: How can I copy or back-calculate definitions for an entire b2World?
I'm working on a platformer where I'd like to be able to move or copy bodies between multiple Box2D b2Worlds. The desire has cropped up three times now - moving objects between documents in my editor, moving the player between levels in normal game play, and giving the player a preview of a non-trivial projectile they can shoot in the game, which seems to be most accurately done by simulating the world for a few seconds ahead.

It *looks like* I can make a parallel world the "long way" - for each body in the world, copy the body data back into a def and re-create it, then copy the fixtures on it in the same way, then do the same for joints; re-set all the velocities; and if it's a "move" rather than a "copy" delete the original one.

I was wondering if someone has already written this code (and if so, was it actually a workable design or not?), or if Box2D has some affordance for doing this within its API which I am missing.

# Answer
> 1 votes
Thanks for reminding me about this.

The answer, is *no, you can't do this in stock Box2D*. Joints don't have enough accessors to get back a correct JointDef. You can back-def-ify simple bodies, but nothing jointed, and the simple bodies are usually trivial enough you wouldn't need to do a copy of the world to predict their motion accurately anyway.

---
Tags: c++, physics, box2d
---


# Question
Title: How do I render a mirror or other reflective surfaces?
I just wondered how to create a mirror within a 3D game? My suggestion is/was to trace rays, hitting the "mirror" object then drawing a picture of a second cam onto the "mirror" object which is located at the original camera's mirror "point" by using the hit side of the mirror object as mirroring plane.

We would have to use the one ray coming from the center of the original camera to determine the point where the center of the vision is located on the mirror plane.

# Answer
If you are using OpenGL, the OpenGL FAQ section 9: Transformations covers exactly how to do this. And no, it doesn't involve raytracing, as that's understandably a very inefficient (but high quality) way to accomplish this.

9.170 How do I render a mirror?

Here is essentially what the FAQ entry says, and the example code demonstrates:

* Set up a reflected view matrix. Doing this for axis-aligned mirrors is explained in the second paragraph.
* Draw the scene
* Restore the view matrix and clear the depth buffer
* Render the scene again; the actual mirror geometry in this scene should be translucent or entirely transparent, in order to show through to the previously rendered mirrored scene.

Obviously there is a lot of room for optimization. When rendering the reflected scene, you should probably as much culling as possible, since mirrors are typically small and the default off-screen culling won't kick in for the geometry which is on screen but not seen through the mirror. You can also render just a simplified version of the scene through the mirror. For effects, and to obscure the user from noticing the reduced quality, you could apply a shader (e.g. blur, or maybe bright/washed-out) when you do your mirrored render.

I imagine, if you're using DirectX, the procedure would be much the same.
> 14 votes

---
Tags: graphics-programming
---


title: How to draw a charts by flash cs5

text:
# Question
Title: How to draw a charts by flash cs5
Hey all , I want to make something more interesting in my game some thing like a **charts Analysis** for a flash game. **When THE PLAYER FINISH THE GAME** . The score appears in charts . I want to integrate it with ***actionscript3*** .

**NOTE**

The game is 60 seconds only I want to draw the score of the user in Y-axis And the Time in X-axis .

I read before about highcharts, but i didn't get much information if there are something easier I'll be grateful . something like that

# Answer
> 1 votes
Yahoo also has a As3 Charting-library available: http://developer.yahoo.com/flash/astra-flash/charts/

# Answer
> 2 votes
I am not sure if you are asking about how to get the data or how to draw the chart. In the second case you might want to have a look at Google Charts drawing service: http://code.google.com/intl/en/apis/chart/docs/making\_charts.html

---
Tags: game-design, flash, actionscript-3, analytics
---


# Question
Title: Rendering arbitrary text in XNA using Windows API?
In Andrew's comment on my other question, he noted that it was possible to render text to a Texture2D using the Windows API, instead of drawing the text directly with a SpriteBatch. How is this done? I'm guessing there's an intermediate step before writing the image data to a Texture2D.

I'm asking because this would allow me to render Unicode characters on-the-fly, instead of needing to pre-render all the needed glyphs using a SpriteFont (too many glyphs in Korean and Japanese to make this route infeasible, sadly). Thanks!

# Answer
Using some reflection, you can grab the Direct3D surface pointer from a Texture2D. From there, you can use any APIs that can render to a DX surface. I did this recently to host XNA content with WPF's D3DImage (with alpha channel support). DirectWrite can render to a DX surface, and you might even be able to use managed APIs. The DirectX .NET wrappers in that link only support Direct3D 10 and 11, and not Direct3D 9 (which XNA uses AFAIK). However, you still might be able to get it to work. On a side note, if you want to render vector graphics, you may be able to use a similar approach to interoperate with Direct2D. Naturally, none of this will work on any XNA-supported platform other than Windows.
> 4 votes

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


title: Is Civ V as moddable as Civ IV?

text:
# Question
Title: Is Civ V as moddable as Civ IV?
Civilization IV was a highly moddable game, and many great mods/games were built off it <sub>(Fall From Heaven 2 being my personal favorite)</sub>.

Does Civilization V have the same opportunities for modding that Civilization IV offered?

# Answer
As I recall, Firaxis has discussed plans to release an SDK for Civ V (as they did with Civ IV), but I do not believe they have released one *yet*. If and when the SDK is released, you will be able to mod Civ V like there's no tomorrow.

You can be reasonably sure this will happen--mods are a big deal in Civ V, and the game even has a built-in mod browser.
> 4 votes

---
Tags: modding
---


title: Handling game states for Android

text:
# Question
Title: Handling game states for Android
Currently developing a game for Android. I went through a tutorial to get sprites, loop, etc. up and running, and it all works fine. The way it is currently set up is that Main creates a canvas, the canvas then runs a thread which has the while loop calling update() and display() functions in the canvas class. All of the game code and classes are essentially called from the canvas.

My question is, how do I expand this to include multiple screens/states, like menus, level selection, options, etc?

# Answer
> 2 votes
It's probably not appropriate to have Canvas be the controller of everything. You probably want to create a Canvas and hand it to something else to draw into.

The way I'd set it up would be something along these lines:

```
static public void Main() {
   InputGatherer input = new InputGatherer();
   GameSimulation sim = new GameSimulation();
   Renderer renderer = new Renderer();

   // the renderer will internally create a canvas,
   // which is irrelevant to the outside world.

   boolean done = false;

   while (!done) {
      input.Update();
      sim.Process(input);
      sim.Render(renderer);
   }
}

```

---
Tags: java, android, state, game-loop
---


# Question
Title: How do I build games with scripted actors?
**The idea**

I have an idea for a game. A few games, actually, that can built on top of the same general design.

There is a game world that the player and the other actors exist in. The player can get information from the world about his surroundings. The player can also interact with the world, picking up an object for example. Now, I would like the same thing to be possible for other, scripted actors. They are the player's competition. Instead of navigating the world and performing actions based on human input, a script should decide what they do.

**An example**

I want to do this using a 2d world eventually, so I might as well give the example I want to build:

There is a 2d world with objects of various sizes and shapes. Every actor has their own field of view. They get information from the world about the objects in their field of view. For the player, this information is displayed on the screen of the user. The player navigates the world by user input.

Scripted actors navigate the world in a scripted way. They walk in a general direction, they follow a wall or things like that. Their scripts should be able to get the information about the objects in their field of view and act on it. If an other actor is detected in their field of view, they should walk in that direction for example.

All of this should happen in pretty much real-time.

The information gotten from the world (showed to the player, and given to the scripted actors) in this case would be something like a collection of "what", "where", and "in what orientation".

**The question**

My question is: how I can program this effectively and efficiently?

I am thinking to build this with C and Lua. C++ is also an option. I would store the game state and display the graphics using C. The part that I don't know how to handle is the interaction between C and Lua. Not programming-wise, but design-wise. The interaction between the world and the scripted actors.

Should C provide the Lua actors with information, and then have the Lua actors call C functions that change their direction, move a step forward, etc? Will this work in real-time?

I realize that this question is broad, but I think it's not unreasonable. There are obviously ways to do this and I would like to know some.

# Answer
I'd recommend not writing long scripts for actors, and instead just having each script be an instant 'reaction' script - ie. it runs and terminates quickly and decides a state for the actor to be in. So, I'd implement a few event handling functions in script, to be called as a result of significant in-game events, and an update script which is called once a frame or something. Pass in a small amount of context about the event in question, and the script should be able to call back into C++ functions to query the environment, set new objectives, etc. For the most part the important changes to behaviour and state should occur on the C++ side: the scripts should be limited to querying the current environment and quickly making a decision, passing that back to the engine.

So for example, you don't continually call a script which then calls a C++ function to say "take a step forward", you call one saying "move me to X,Y" and then the normal C++ update loop will do that without reference to script for the next few seconds. When you arrive, you might call a script (eg. 'on\_arrival') where the NPC can choose its next goal.

I don't recommend trying to run actors via long-running scripts with lots of loops, conditionals, and storing state within the script, because this quickly becomes a concurrent system, and concurrent systems are REALLY HARD. If you use native threads to handle each character, you're going to hit multithreading bugs very, very quickly, unless you fully understand the implications of such a design (which sadly can't be explained in a single StackExchange post). If you decide to use some sort of user threads (eg. Stackless Python tasklets, Lua coroutines, etc) then you still need to understand the implications of cooperative multitasking - eg. being able to yield up control to other actors (ie. why `while (1) { do_nothing(); }` is not going to work for a sentry), and also to appreciate that even if your game is 'thread safe' the logic is not necessarily 'coroutine-safe' - a variable in one coroutine can easily become invalidated by another.

eg:

```
function duel():
    self.aim_at_foe()
    self.shoot_foe_dead()
    self.celebrate_victory()

a = new Sheriff()
b = new Outlaw()

run_both_at_same_time(a.duel(), b.duel())

```

What happens when the loser (whoever it is) tries to execute 'self.celebrate\_victory()' and your system discovers that 'self' now refers to a dead actor? Or if it's reference counted, what if it allows a dead actor to celebrate his victory?

Of course, some people are used to this sort of problem and know what they're doing; anybody in that category can ignore much of the above. :)
> 5 votes

# Answer
I would recommend to use C++ and polymorphism (one of basic principles of OOP).

You can create a general Character class. It contains character's location, position in the world, inventory and other data, also virtual functions for updating and rendering character. Than you can subclass it with NPCharacter and PlayerCharacter.

Method `PlayerCharacter::update()` listens to user input events and updates Character's state accordingly.

Method `NPCCharacter::update()` implements some AI logics and controls NPC in any way you want.

You can create LuaCharacter also. `LuaCharacter::update()` simply calls Lua script that does the same thing as NPCCharacter, but from the script. Some games really call Lua script every frame. If you are concerned about performance, it is better to minimize Lua calls, you can use Lua to implement callbacks and listeners to user input or other events only (no need to call these scripts every frame).

```
foreach (characters as character)
   // we do not know what type of character it is - Player, AI, LuaScripted etc.
   // they all are updated in the same manner
   character.update();

```

---

The same can be done using composition and component-based approach, too. Just add different components to your game objects. For example, AICharacterCleverComponent, AICharacterDumbComponent, LuaScriptedAIComponent, PlayerInputControlComponent etc.
> 2 votes

---
Tags: game-design, c++, c, lua
---


# Question
Title: Float, double or both for 2D Vector class?
I'm currently writing a small cross-platform OpenGL-based 2D game engine for our studio. When I researched which 2D Vector class to use, I stumbled across three different design paradigms:

* Float & Call-by-value, like in this Gamasutra article. Seems to be fast but offers little precision (see also this Thread). Pro: Fast, portable and compatible with most libraries.
* Double & Call-by-reference. If I understand the above article right, I could also use 2 double precision variables instead of the 4 float numbers. According to the above thread double's still slower than float.
* Template for double and float: The widely popular book "Game Engine Architecture" uses templates to make it possible to use float and double as needed. The obvious downside is code bloat. Also, I doubt it that the code can be optimized without basically writing two classes, anyway.

I would appreciate to learn what solutions you're using in your in-house engines and how precise e.g. popular game engines are, so I can decide what solution I'll implement in our engine. In the moment I'm thinking about simply using float precision and live with it.

# Answer
I always use float unless I have a reason to use double, much as I use int unless I have a reason to use int64\_t.

Floats have no problem doing precise integer arithmetic up to 224, which is what most people are (mostly irrationally) afraid of. Doubles do not solve the problem of common values being unrepresentable exactly - whether you get 0.10000001 or 0.10000000000000001, you still must make sure your code considers it "equal" to 0.09999999.

Doubles are slower on every platform you'll care about writing games, take twice the memory bandwidth, and have fewer specialized CPU instructions available.

Single-precision floats remain the standard for hardware graphics interfaces, both on the C/C++ side and inside shaders.

You'll probably need a double vector at some point, but it should be used when needed, not by default.

As for templating - you're right, for maximum performance you'll want to specialize the templates manually anyway. Aside from that, I ran some tests for some templated code over the weekend (making a 4-ple IntRect and FloatRect), and found that the templated version took about 20x longer to compile than just repeating the code, which amounted to about 15 lines. Repetition sucks, but waiting for compiles sucks more - and it's not like I'm ever going to need a StringRect or FooRect.
> 10 votes

# Answer
The Microsoft XNA game framework has a Vector2 class which uses floats. This would be my personal biggest reason for going with floats, as I trust the wisdom and experience of the XNA team to be much greater than my own.

I found it rather interesting to read the answer in this Stack Overflow question: "Float vs Double Performance". There is also a gamedev.net thread with some discussion of double performance in GPUs. I think it's safe to assume that doubles are slower than floats, at least in many GPUs, and I personally always used the float OpenGL functions over their double counterparts. This may not apply nowadays, but if you consider that not everyone who runs your game has the latest GPU with native double support, I think this is reason enough to use floats and gain that extra bit of performance.
> 3 votes

---
Tags: mathematics, cross-platform
---


# Question
Title: Where can I obtain the latest stable aggregated builds of JOGL?
I have checked many different sites including jogamp but couldn't manage to find any zipped,rared or jared collection of builds and javadocs.

# Answer
> 1 votes
Essentially, all the files at JogAmp can be found at http://jogamp.org/deployment/.

The latest build can be found at http://jogamp.org/deployment/jogamp-next/. I can't attest to its stability, so I don't know if it is a "latest stable" build or not, but I think it is. There's not a clear definition of what they mean when they suffix something with "-next".

You can browse around other builds by just exploring the folders at http://jogamp.org/deployment/.

---
Tags: java, 3d
---


title: What is Serialization?

text:
# Question
Title: What is Serialization?
I have been around programming for a while as a hobby, but I did not start seeing this concept until recently. I have google'd "what is serialization" numerous times, but I never actually get any sort of definition, usually just examples of how to do it. I am seeing it around the Ogre forums, the Bullet forums, and every other forum I go to, so I think it is about time I actually understand what it is, and why to use it.

*Edit*

To clarify, I am looking more for why to use it, especially in the sense of game programming. For example, the Bullet Physics API talks a lot about serializing a mesh, so I want to understand why that is.

Thank you :)

# Answer
From the boost.serialization documentation: *Here, we use the term "serialization" to mean the reversible deconstruction of an arbitrary set of C++ data structures to a sequence of bytes. Such a system can be used to reconstitute an equivalent structure in another program context. Depending on the context, this might used implement object persistence, remote parameter passing or other facility. In this system we use the term "archive" to refer to a specific rendering of this stream of bytes. This could be a file of binary data, text data, XML, or some other created by the user of this library.*

In other words, serialization is any process that transforms objects in memory into some kind of bytestream, and *deserialization* does the reverse, taking a bytestream and transforming it back into objects in memory.

The term "serialization" does not imply anything about the format of the bytestream. It may be an efficiently packed binary format, or a loose XML or YAML description. It may even be source code in the original language itself, or in another programming language, such as JSON, which is a subset of JavaScript. The exact format of the serialized stream should be chosen based on how you intend to use it.

Serialization is a built-in feature of many languages and environments - for example Java and Python. In lower-level languages like C and C++, one must use (or write) serialization libraries, as the mechanism provided by the language is usually not good enough - it cannot follow or serialize pointers and references, and is subject to endianness issues, for example.

Wikipedia has a decent article on serialization.

Serialization is used extensively in games (and all software) for many purposes:

* Loading the list of all spells in the game from resource files.
* Saving and loading the game.
* Recording the state of things (e.g. player positions and inventories) to a SQL or object database.
* Invoking remote function calls over a network or other IPC link.
> 7 votes

# Answer
As I understand it, serialization is just the concept of taking an object or a set of objects, transforming them into a byte stream (for data storage, or network transmission, etc.) and then later reconstructing the original object from that bytestream ("deserialization").

Whimsical: It's a bit like a Star Trek teleporter, now I think of it.

A number of libraries exist for this, each of which deal with the little niggles that tend to get in the way (like bytestream endianness and such).
> 6 votes

# Answer
To serialize something essentially means to change it into a series. This is necessary if you want to send something over a network or write it to a file, because both of those expect a series of bytes. So it's generally a fancy term for the save and load systems. In the case of Bullet, it's simply taking the mesh data and saving it out in a form that Bullet can effectively use. You can save this out and load it in later without needing to re-analyse your meshes.
> 3 votes

# Answer
Serialize/De-serialize is simply prepping and writing/reading objects to/from disk.
> 0 votes

# Answer
I personally use serialisation for networking. Outside of that I don't really have much use for it. If you want to know why it's used in Bullet, the best chance you have of getting an answer is by asking in the Bullet forums or reading the documentation.
> -3 votes

---
Tags: c++, serialization
---


# Question
Title: Distinction between constant and changeable game objects in save/load game?
Do you distinguish constant and changeable game objects when you save/load game? If yes, how do you do it?

If not to save constant objects (for example, mountains and trees), we optimize memory usage and save/load time. But functional requirements for the game can change. Now you want trees to be mutable and destroyable. It can screw up all previous game states. Trees were not saved =\> saved game map is interpreted as the prairie without trees.

# Answer
> 3 votes
Saved games should either:

* Completely describe everything, whether mutable or not. This is the safest way, and easy, but does use a lot more space. It doesn't really use more *memory*, since you need the trees either way. It just uses more persistent storage, which there is plenty of on anything that's not a Nintendo DS. It also means you can't fix bugs in levels without players having to restart the game to get the bug fix.
* Describe *differences* between the default map state and its current state. This solves the tree example you give. The save game says nothing about trees; therefore the trees are in their default place on the map. It means you cannot do the reverse - change something from mutable to fixed - but there is obviously no way to do that and preserve the save file accurately.

---
Tags: state, loading
---


# Question
Title: How do I get and install the Android SDK on my Ubuntu OS?
I heard that it would be a lot easier to do java type games and then move on to Android gaming? I AM a total beginning but with motive and I have been reading about it from several sources, including similar questions on this site alone. But I need to know specific things from experienced users.

As for getting the SDK and Eclipse on the computer, I'm having trouble with it, I am running Ubuntu btw so exe files are useless. But I have tired terminal use but I kind of failed because I don't think the SDK and Eclipse are installed, just downloaded. Ubuntu users especially, I can use help from you seeing how complicated Ubuntu can be compared to windows "click install" setups.

Also if you guys really suggest me learning Java first (which is still a big question cause I don't want to waste time with something I don't want to really use, but getting the feel of gaming is pretty important I know) I am looking at this tutorial:

http://zetcode.com/tutorials/javaswingtutorial/

And it talks about using swing toolkit, but idk how to get that exactly, I tried searching. Sorry for the noobness, but gotta start somewhere and I'm new to this site so I'm really hoping you guys can really help me. I want to make simple games to put on the android market, and then advance.

So going to the tutorial above, it just kind of starts with giving me coding and whatnot which is fine, just copy it but idk where exactly to do all this on (Swing toolkit?) so I can't even start with that.

But really I want help getting this SDK and Eclipse/plugins on my computer and then I can continue with this guide:

www.rbgrn.net/content/54-getting-started-android-game-development

Which is the main guide that I probably should follow, and would be great if some expert skims it a little at least to see if I should start with that guide and skip the java. But again, I'm stuck on the SDK stuff.

Sorry for the long questions, I am new and I really want to get out of this beginner stage, it's the worst part. Tank you to all and if you want my facebook or AIM to help me through with IM to at least get this SDK and stuff installed fine with Ubuntu OS, ask please (:

# Answer
**About game programming**

* Learn the basics of programming in the most fun and inspiring way you can, and don't be discouraged that you won't have anything good enough to release on the Android marked right away.
* Aim for small mini-projects that can help you understand the different aspects of programming.
* Don't bite over more than you can handle. Not understanding things is really demotivational.
* Understand the game loop.
* Get something visual up and running fast.

Some of the most memorable mistakes I made as a complete newbie were:

* Creating new objects every frame of my game. Memory allocation is slow, garbage collection ( the deletion of unused objects ) even slower. If your mobile game does this your mobile will run out of juice pretty fast.
* Incrementing my game logic every frame by a fixed rate instead of a function of the time spent between frames.
* No overall arcitechture or idea of how I would connect different parts of the logic that has to be handled in a game.

**About embedded games programming**

Although Java is a great language for beginners, the Android platform is not.

I am currently working on a game engine for Android. What I can tell you is that making games is hard. Even more so on embedded systems because of limited hardware capabilities.

**About the javax.swing library**

I started with Java and swing as my first programming language and GUI toolkit. It was a great way to get started. The first year of programming I made more mini-projects than I have ever made since.

The swing library is built into the standard libraries in standard Java, but is stripped out of the Android specific Java that runs on the Dalvik VM.

All you need to do to use swing is to have an import javax.swing.\*; statement in the top of your code file.

**GPWiki**

Lastly, I would like to direct you to these pages:

gpwiki - How do I get started

gpwiki - Beginner FAQ
> 2 votes

# Answer
The Swing library is part of the Java platform since Java 1.2, so you don't need to download the library separately. You can start following these tutorials right away assuming you got the JDK (Java Development Kit) installed.

Do you already know Java? You might want to invest some time in learning that before you start learning game programming in Java. If you already know another language such as C++ then it shouldn't be hard for you to pick it up, otherwise you need to spend some time learning how to program. The Java Tutorials are a good place to start. There are tons of other tutorials and books on programming, Java, and game development.

I know you really want to get started with making games, and don't want to go through learning java, game programming, and then Android programming, but it is worth it. You *can* start making a game for Android right away, but you'll get stuck sooner or later; you need to learn all of this one way or another. I completely agree with Nailer's answer and you should realize that learning to make games will take time and effort. You said that learning Java might be a waste of time but I strongly disagree, learning new skills is never a waste of time, even if you don't end up making a game using Java.

Assuming you got the latest Ubuntu version (10.04, or even 9.10), you can use the Ubuntu Software Center to download Eclipse and all of the other libraries required by it. You can find the software center through the Applications menu, and then just search for "eclipse" in the top right search box and install it. If you have an older Ubuntu version then you might need to download Eclipse from the official website. You probably need to download the JDK(`sudo apt-get install sun-java6-jdk` in the terminal) before you download Eclipse. Once you have both Eclipse and the JDK you can proceed to download the Android SDK and follow Google's quick start guide or this more detailed guide. Here are two more guides for you: , . Note that you just need Eclipse and the JDK to follow the Swing tutorials, but make sure you create Java applications and not Android ones because Swing is not part of the Android platform.

If you have any problems with following these guides or with installing any required programs and libraries on Ubuntu, you can always ask at the Ubuntu Stack Exchange site or the Ubuntu Forums.
> 1 votes

# Answer
If you're using Ubuntu and want to install Eclipse then then go to Application-\>Ubuntu Software Center. Then type Eclipse into the search tool at the top, you'll see a list of packages, just click the ones you need. I think you need to install Eclipse and eclipse-pde for plug-ins.

For setting up the Android SDK check out this tutorial. http://lgjsheron.wordpress.com/2010/07/01/installing-eclipse-and-the-android-sdk-on-ubuntu-10-04/

If you want more help on the programming side of things then you should check out this book: http://www.amazon.com/Pro-Android-Games-Vladimir-Silva/dp/1430226471 I've used it in the past and it was pretty helpful.
> 0 votes

---
Tags: android
---


# Question
Title: How do I load chunks of data from an assest manager during a loading screen?
I'm developing an Android game. Basically I want to pre-load all graphics/sounds when the app is first loaded. But I also would like to show a progress bar as this is happening. Here is a snippet of Java/Android code to display a progress bar while doing some work:

```
public class LoadingScreen extends Activity {

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loadingscreen);

    progressBar = (ProgressBar) findViewById(R.id.progress);

    //---do some work in background thread---
    new Thread(new Runnable()
    {
        public void run()
        {
            while (progressStatus < 100)
            {
                progressStatus = doSomeWork();

                //---Update the progress bar---
                handler.post(new Runnable()
                {
                    public void run() {
                        progressBar.setProgress(progressStatus);
                    }
                });

            }
            //---hides the progress bar---
            handler.post(new Runnable()
            {
                public void run() {
                    progressBar.setVisibility(8);
                }
            });
        }

        private int doSomeWork()
        {
            try
            {
                //---simulate doing some work---
                Thread.sleep(50);
            } catch (InterruptedException e)
            {

            }
            return ++progress;
        }

    }).start();

}

```

My question is: how do I design my Asset Manager to load "chunks" of data (bitmaps and sounds/music) in the `doSomeWork()` function? Would it be some sort of stack that I keep popping off the next asset to load? How do I determine how much of the progress bar I should increment after loading a "chunk" of data?

Is there a better way to approach this or is this the correct way?

# Answer
> 3 votes
I would've gone for the asset manager having a stack of data it needs to load. If there's an easy way to go about it, there's the option of adding to a size counter as you add elements to the stack - this means you could increase varyingly. So instead of a large texture and a quick sound effect both increasing loading by 10% say, it could increase by 13% and 2%, for example.

Then pop off each piece of data as you load, handling errors and the like, and increase the amount of bar visible.

I think that there's nothing wrong with that way, but I'm pretty sure someone would be able to give something more complex around here. :P

# Answer
> 0 votes
Why don't just say `100% = resource count`? Resource loaded =\> increment.

I suppose you want to use stack to manage dependencies between resources? Push resource. Push dependencies... etc. Than you have 2 passes:

1. collect resources in stack (count resources)
2. load resources (increment status bar)

---
Tags: graphics, assets, android, loading, preload
---


# Question
Title: Managing a complex game storyline or quests system
What kind of methods are best used managing complex story lines in a game? A simple story is basically linear line with stops, so that would not be that difficult, but a more complex one is basically an elaborate directed graph, with certain requirements to move between nodes. So how does one effectively store and maintain a complex game storyline that has multitude of paths and goals?

# Answer
Depends on exactly how your system is put together. If it's simple branching, then just treating it as a linear story with some flags to tell exactly what path you're on (or if you prefer to visualize this way, a binary tree structure where each node is a story choice point and the current place in the story is a pointer to one of the nodes). A slightly more involved story with multiple paths that can cross over each other could be modeled as a directed acyclic graph using the same technique.

What if you have multiple story arcs going on simultaneously, like a typical "open world" quest system where the player may have several quests at once? If the quests don't interact with one another, you can just treat each of them as its own separate linear or branching mini-tree. What if they do modify each other? Here's my preferred option:

A modified directed graph, where each node represents a quest. Here you have two basic kinds of arrows between nodes: "activate" and "deactivate". In this way, completing a quest might open up new quests, and it also might invalidate old quests that no longer make sense (for example if you're given a set of quests, each of which is to help a different side of some warring factions, completing one quest might auto-hide the other quests if you want to force the player to pick one side and stick with it). You'll also want to store in each node its current status: active (currently visible to the player), inactive (has never been visible to the player), completed (player has finished the quest), failed (player has seen the quest but it was later inactivated, for example by the completion of a separate competing quest).

Amusing side note: every system that works for a quest/storyline, also works for an individual conversation tree with an NPC, and vice versa. So if you find a suitable conversation system for your game, ask yourself if it's worth modifying that for the story system as well.
> 4 votes

# Answer
The Neverwinter Nights toolset includes an interesting attempt to solve this problem, known as the Plot Wizard. It didn't originally ship with the toolset, so you may need to try it again if you did some module development years ago. Here's a lengthy tutorial that goes over the different components designed to engineer an RPG plot.

The basic summary is that the "plot wizard" allows you to construct storyline and quests from the top down. For instance you can tell it to generate the relevant scripting for a "fetch 10 things" quest, which leads into a fedex, which leads into a custom scripted thing. The wizard will then generate a series of linked components that are tied to the plot script, and then allows you to place them in the world. This allows you to easily move NPCs or enemies around in the world without breaking any scripting connections.

I don't know of any other commercial games that use this technique (most seem to use a ton of one off variables that are checked via scripts), but I've always felt this was a reasonable base for building a complete rpg or adventure-style game.
> 9 votes

# Answer
Formal grammars are an essential way of describing plots.

For example, Vladimir Yakovlevich Propp proposed a grammar for a typical folk tale in *"Morphology of the Folk Tale"*.
> 2 votes

---
Tags: management
---


# Question
Title: Zune same features as WP7? (gesture, accelerometer)
We don't have zune HD in Canada (yet) just wondering if it has the same programmable features as WP7? Like gestures and accelerometer.

Basically if I am just making a game, with screen controls (thumbsticks on the screen) is this an easy port to zune?

Thanks!

# Answer
I'm not as familiar with the WP7 API as I should be but I've done some Zune XNA programming and you have access to the touchscreen and accelerometer fairly straightforwardly. I can safely assume a port between the two would be relatively painless.

You get a list of `TouchLocation`s from XInput and you can do what you will with them. Each touch has an ID that allows you to identify drags/swipes.

The Accelerometer just gives you a 3D vector showing the current acceleration (with 0,-1,0 being the norm due to gravity). This tutorial gives a good example of using the Zune's interface.
> 3 votes

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: Which programming language to use for tools?
I use C++ as my language as choice. However, I generally use Python to write helper utilities and tools.

My worry is that as my game engine continues to grow it's getting tedious to reimplement some of its features in Python.

There has got to be a better way.

Here are the options as I seem them

* Keep on keeping on.
That is often the answer in a cooperate environment. Maybe it has some merit.
* Build bindings for Python (yuck) and have it use pieces of the engine directly.
* Start building the tools using C++ instead.
I already use QT in the Python tools to provide a GUI when needed. It doesn't seem like it'd be that much harder to use QT in C++ instead. However I'm worried my tool productivity will go down. I generally strive to apply much less rigidity in tool code than I would in shipping code.

So what is common practice, use the same language for tools, or use a more RAD friendly one?
What if you use a language that differs from the language of the game which do you use? How do tools interact with the game engine link to it directly or fake it?

# Answer
What do the tools do? Presumably, you mean tools for generating and editing data files which your engine can load, and not e.g. your profiler and debugger.

You're working on a data-driven engine. You can apply the same philosophy to your tools - *write data-driven tools*.

For example, let's say you are using protobufs. The protobuf libraries for C++ and Python will let you save structures in one and load in the other, no problem. But why not go a step further, and generate the tool UI from the protobuf schema as well? It won't be a great UI, but UIs for most game data are just string key / typed value pairs, and that's trivial to generate using Python and the UI library of your choice. And if it's a *really* bad UI, at most you committed yourself to the work you're doing now anyway, by writing a custom one from scratch.

At my last job, we used this style as a first-pass on (almost) every editor. Some of them stayed that way forever; a giant sheet of key/value pairs is a pretty good way to edit inventory item data, for example. For editors that needed more structure, such as the editor that assembled character models from parts, we had a custom top-level layout, with sub-panes generated this way (e.g. we placed the "Tattoos" pane by hand relative to the "Bone Scaling" pane, but their contents was dynamically generated from the structure schema).
> 5 votes

# Answer
I make all my tools using the Qf Framework, that way they're fairly easily cross platform. There's also loads of well maintained bindings for Qt, including Python Qt bindings.
> 0 votes

---
Tags: tools
---


# Question
Title: How can I easily test & visualize different math things?
For example, I've asked about the breakout formula to calculate the ball bounce. Inside of XNA, I don't know where I would code this and to even display something I would need a lot of code.

Is there something simple way visualize math formulas such as the one above?

# Answer
> 0 votes
I tend to reason through problems on plain old **pencil and paper**. There's just nothing quite like it; it's completely unstructured.

Otherwise, I mean, there are math problems like Maple, Matlab or Mathematica (those are the popular three) but they of course have a learning curve.

Figuring out that particular problem was mostly just a matter of reasoning; define exactly what you want to accomplish, what variables you need (intersection point, velocity of ball, distance of intersection from center of paddle, minimum and maximum speeds), and then determine **how to go from what you have to what you want**.

Sometimes maybe it just takes being familiar with the math too, or having solved similar problems or understanding different angles of the problem. For example, I had already seen similar problems like this one in my Calculus classes, so it was pretty easy for me to tackle. Math is important in game development.

---
Tags: physics, simulations
---


# Question
Title: Ipad - actionsheet not showing all buttons in landscape mode when keyboard is present
I am developing an Ipad application. It supports both landscape and portrait mode. The app has keyboard.It also shows an action sheet with 4 buttons when required. In portrait mode it works perfectly. But in landscape mode action sheet only show 2 buttons when keyboard is there .Without keyboard it show all 4 buttons. Any solution?

# Answer
I dont undertand what you mean with "Actionsheet", but the trick here is that you have to subscribe to be notified that the keyboard will show and then move your buttons to a place where they can be displayed.
> 1 votes

---
Tags: iphone, ipad
---


# Question
Title: Error on new XNA 4.0 game project - No suitable graphics card found
Any ideas on how to fix this? According to what I remember about XNA 3 was that when running the application from scratch, I would get a blue colored windows with nothing rendered.

Any suggestions?

**EDIT!**

I right clicked the project and selected Properties and changed the Game Profile from **Use HiDef** to **Use Reach**. Now the familiar blue tint window is showing as expected.

What am I losing if I choose the limited API and why did I even have to choose this for it to work?

# Answer
> 8 votes
To answer your follow up question:

> What am I losing if I choose the limited API?

This blog post explains the differences between Reach and HiDef. In a nutshell, the Reach profile does not allow the use of some of the more advanced graphics card features. But it runs on more hardware.

# Answer
> 2 votes
XNA Framework HiDef profile requires a DX10 capable video card.

If you have a DX10 capable card, make sure your latest display drivers are installed.

If you don't have a DX10 capable card go into project properties and change the profile from HiDef to Reach.

Edit: I see you answered your own question, but to answer your question about what you will be missing:

Probably antything related to DX10. I can't remember the exact differences in my head, but lighting and particle effects are two areas where DX10 excels over DX9.

---
Tags: xna, xna-4.0
---


# Question
Title: What are the big advantages of shaders ? What is doable with them, and what can't be done without them?
I don't really know when vertex and/or pixel shaders became available for consoles and computers, but what could we do without them ? I don't really understand what is achievable with shaders and what is not without them, and what are the true advantages while using them.

I guess the advantages of using shaders are performance and better flexibility, but on the other hand, I am quite speechless when looking at the syntax...

I think a really good rendering quality can be achieved without using them, but I'm not sure which one...

# Answer
Shaders facilitate graphics rendering that is both flexible and efficient.

Once upon a time all graphics were done in software. This was very flexible, but not very efficient.

In the mid 90s add-on graphics cards became popular because they vastly accelerated graphics, but at the cost of flexibility. Writing pixels became a lot cheaper but reading them became much harder and/or slower.

Now that graphics are faster, and technology has improved (or become more affordable, depending on how you look at it), some flexibility can be added back into the graphics pipeline. Shaders give you this flexibility. The syntax is quite low-level because the hardware it is aimed at is also quite low-level. It's a compromise.

Really good rendering quality can indeed be achieved without them, depending on your definition of quality. You can stick to CPU-based graphics, if you don't mind those graphics being quite slow. Or, you can use the GPU and used the old fixed-function pipeline, which gives you a subset of the shader functionality. Whether that subset is "really good" or not is subjective - it was certainly good enough for many years - but you miss out on some interesting modern rendering techniques as a result, as the fixed function pipeline has no way of performing the completely arbitrary transformations on vertices and pixels that shaders can perform.
> 10 votes

# Answer
The fixed pipeline is rather limited. Something as simple as *Phong-Shading* already requires a shader (the shading capabilities of the fixed pipeline end with *Gouraud-Shading*). The possibilities that open up with shaders are huge. Some of them are: better shadowing-techniques, ambient-occlusion, normal-mapping, etc.

That doesn't mean you can't create great looking games without shaders though. AFAIK Torchlight only uses fixed pipeline and looks awesome. Also: If you're doing 2d graphics, you'll probably be fine with fixed pipeline only.
> 3 votes

# Answer
Just some examples that are hard to do without shaders:

* Normal mapping
* Parallax mapping
* Cartoon rendering
* Bloom
> 2 votes

---
Tags: 3d, shaders
---


# Question
Title: Need help choosing the right networking approach/platform for an RTS
I have been thinking for a while about making an online 2D RTS-like game. (2-6 players in a match, up to 50-60 units, no AI). The key thing here is that I want the game to be playable in a browser, so it'll have to be either flash or java applet, both using TCP sockets. At first I was entirely focused on flash because of a higher market penetration and accessibility. However, after reviewing different networking approaches I am unable to make a choice.

I really liked lock-step simulation approach where server and every client are running the exact same simulation, until I realized that it's going to be tough as hell (if not impossible) to implement exactly the same logic in two different languages, one of them being actionscript. This is where java comes in. With java client and server can share simulation related code - that may as well cut the development time in half.

But then there is another approach, where clients try to simulate (or rather extrapolate) the game state correctly as long as possible, but they don't have to do it right - at some point they are going to receive the full state snapshot an adjust accordingly. Flash looks like a viable option again, but still, lock-step simulation seems so much more straightforward, as there is no "adjusting" part.

So are my assumptions correct? What would you suggest?

# Answer
> 5 votes
Every RTS that I know of uses lock-step simulation for it's network model, more or less for the same reasons:

With lock-step you only need to exchange inputs which drastically reduces the amount of bandwidth required. If you were to use the interpolation/extrapolation approach, with 60 units x 6 players worth of state x 6 players to send to - whoever is hosting will need a lot of upstream bandwidth.

Furthermore, with lock-step you guarantee that everyone sees exactly the same things happen which is very important for an RTS to feel fair and be strategic. In the extrapolation case you could see on your screen that you're winning a battle only to find upon receiving a new snapshot that you've actually lost. And the worst case is that you could've won that battle if only you knew you were losing it.

One final benefit, lock-step makes cheating harder since anything shady you do locally will cause a desync. You would have to cheat everyone's simulation not just your own.

---
Tags: networking, rts
---


title: Tiles and a walkable path

text:
# Question
Title: Tiles and a walkable path
My game a sidescrolling platformer. I've created my own Tile app which in the end export an xml file detailing what each 32x32 space (in the entire image) contains (environment, platform, etc.). I get how to use it for static things/collision detection and quad trees and so forth but still have no clue how to use this map xml file for keeping my character on a path in my background image which in my case is a hill with lots of odd curves.

Also, yes, there are tutorials on tile movement, but they are mostly movement from a top-down view which is slightly more trivial to implement. 80% of the image in my game is just a pure background and the very bottom are bricks covered with grass with some weirder angles. The thing is, I can have mixed tiles of empty space and grass which contains a part of a curve so I don't know how I would want the player leg to interact with this. Can anyone give me an idea or an example?

# Answer
> 1 votes
As long as I understand you have two problems:
1- you don't exactly know where the curves begin end or their functions.
2- where your characters feet touch.

If your characters collision behavior means just its Y position and keep its feet above the curve then:

1. Get your characters begin X and end X. Let's say x1,x2 to these.
2. Assuming you don't know what background there's someway you should get the image pixel data from the background falling between x1 and x2.
3. Then apply an edge detection algorithm(you may find immense number of libraries and code snippets around) to your partial background.
4. Edge detection will provide the edges of your background in white or black so looping down from the max y value of your platform you can find where the first edge pixel is. You may threshold the resulting edge detected image for better results.
5. Place your charater where the first edge is found.

Note that if your curves on the background are very ambiguous edge detection may fail but I think this solution will be a swift and adequate one.

# Answer
> 0 votes
Someone else with more knowledge of the subject should write a more thorough answer, but in an attempt to give you an answer (since nobody else has)...

You should start by implementing pixelwise collision detection, or triangles (mesh collision) if they approximate your terrain well enough. Then, in order to accurately place your character's feet on the ground, perhaps rig your sprite with virtual bones. They could be controlled by a physics engine for best-looking results. Or, if you go the triangles way, you could also have a triangle collision mesh for your sprite, and borrow some of the techniques usually used in 3D games in order to calculate the best angle/distortion of the collision mesh onto the terrain.

---
Tags: collision-detection, tiles
---


title: Protobuf vs Lua for custom file format

text:
# Question
Title: Protobuf vs Lua for custom file format
I'm defining a custom/simple file format for loading textures in my game. I narrowed my choice of file formats to two options:

I chose Lua, because my game is already using Lua, I wouldn't need to add protobufs to the build. Eventually, I'll use the engine to build a network game, at which point I'll add protobufs it's just that I don't need it yet and have other pressing needs in the engine.

However, I'm kinda stuck. Most (all?) of my support tools I write in python. I can't find a small clean Lua module for python. That means my python tools end up parsing the Lua syntax by hand. It's not too onerous as file format uses a very small subset of Lua, but still annoying.

So now I'm second guessing myself, *Should I have picked protobuf instead?*.
Then I promptly third guessed myself, *Am I just afflicted with wanderlust and should stick with a solution that already kinda works?*.

So which would you pick (or already did)?
And more importantly why?

---

My thoughts.

### Lua

```
texture
{
   width=8;  --#256
   height=7; --#128
   format=GL_RGB;
   pixels= [=[
<binary-data-here>]=];
}

```
* **+** "plain" text format
Technically only the meta data is plain text but base64 encoding just for the sake of plain text is silly.
* **+** parsing is trivial as the engine already supports Lua.
* **-/+** easy (not trivial) to generate, and can be easily verified with luac.
* **-** python tools have difficulty parsing

### protobuf

```
message Texture {
   required uint32 width = 1;
   required uint32 height = 2;
   enum Format {
      GL_RGB = 0;
      GL_RGBA = 1;
      ...
      GL_LUMINANCE_ALPHA = N;
   };
   required Format format = 3;
   required bytes pixels = 4;
}

```
* **+** protobufs are well tested and optimized
* **+** they will be needed eventually to do network communication
* **-** networking isn't part of the engine yet (and wont be for some time, the next few games don't need it).
* **+** trivial to parse
* **+** trivial to generate
* **-** complex binary format, impossible to edit, or verify by inspection.

# Answer
Personally, I'd question why you're writing support tools in a different language than your game code. That seems like a dubious idea. :)

I've used both Lua and Protobufs rather extensively. I've been using Lua lately, mostly because it is really ridiculously easy to merge them into a Lua-based game. However this is just a preference. They'll both work fine for nearly all purposes - unless you have a strong reason to change, I'd just stick with whatever you have.

Two things to note:

* Gzipped Lua is surprisingly compact.
* Protocol buffers do have a text output option which is easy to edit and verify.
> 4 votes

# Answer
I would pick protobufs. The temptation to do clever things with Lua would be too strong. First I would cave and write basic arithmetic because I can just eval it in Python. Next I would let myself use intermediate variables because they're easy to parse out. Eventually I'd need Lua-in-Python for any tools I wrote in Python, and then I'd want to go back in time and stop myself.

Protobufs also support schemas, which can provide *structural and semantic* validation; luac will only provide *syntactic* validation.

**However...**

Protobufs are *not* needed for network communication, so don't choose them for that reason. You can gzip Lua and send that just as easily, if you have the code written to serialize/deserialize Lua objects.

(If I was doing this from scratch, I would pick neither, and use YAML. The protobuf syntax, especially the manual field numbering, annoys the crap out of me.)
> 5 votes

# Answer
I choose Lua. Only having the possibility of insert some check functions in the last moment or to prototype some features is more than enough for me. However I'm assuming that performance isn't an issue because we are working in a network environment.
> 1 votes

---
Tags: lua
---


# Question
Title: What are the biggest pitfalls to consider when developing a new game?
I actually just started tracing (thanks David Young for the nomenclature correction) a couple of new web-based games for Facebook a few weeks ago and I have just been inundated with mental blocks and time sucks from re-coding. I am working on something similar to the turn based (Vampire Wars) style RPG. I have the skills to code a game but I am slogging through trying to get the design patterns right and make the product match what I see in my mind's eye.

Normally when building a website I like to 'think in code' and I find it faster for me to just change the code/HTML to tweak it in. This is probably because I am VERY comfortable in what I do and I know what to expect as I've done it over and over again. At this point with game development I find myself starting on paper again (like I used to with websites) and I wonder if this is just my lack of focus and intuition with game logic or if this is an appropriate way to roll my thoughts out in advance of coding.

I would appreciate some advice on how to correctly attack this problem and keep myself on-task. I am quickly learning how much differently a game engine is from a standard business website! Every time I do get something in place it just feels mooshy and incomplete and it's becoming darned frustrating.

**Extended**

As an example, the battle engine that has been giving me so much issue recently takes a simple attack skill and then makes a random roll between -50% and +50% and then multiplies the original attack skill against that percent. The same thing is done with defense and then I mesh those to determine if any damage is done against the enemy health. I guess I should realize I am in over my head when I started asking myself if that is even the right way to do it, or if there even IS a 'right' way. One major fault I found with this is two characters around the same level can have several 'rolls' where the attack is -50% and the defense is +50% so I end up with some EXTREMELY long battle sequences where nobody does anything. FAIL

Maybe my post should have been asking for suggested links describing simple game logic.

**End Extension**

Thank you all in advance!

# Answer
> 22 votes
adding too many features. Focus on the core of the game, build it, then if everything works well then add features. People get too focused on adding cool things, and never getting anything done.

# Answer
> 14 votes
This is a great article about how to prototype a game. From your question is seems like you're missing the idea of what a prototype is supposed to be.

**Prototyping: You’re (Probably) Doing It Wrong**

Blurb:

> **Mistake #4: Building a system, not a game**
> When you’re making a prototype, if you ever find yourself working on something that isn’t directly moving your forward, stop right there. As programmers, we have a tendency to try to generalize our code, and make it elegant and be able to handle every situation. We find that an itch terribly hard not scratch, but we need to learn how. It took me many years to realize that it’s not about the code, it’s about the game you ship in the end.
>
> Don’t write an elegant game component system, skip the editor completely and hardwire the state in code, avoid the data-driven, self-parsing, XML craziness, and just code the damned thing.

**Edit:**

I'm adding this just to clarify the difference between Prototype and Tracer Code.

**Always remember: A Prototype is designed to be thrown away! Tracer Code is not.**

**The Prototype Pitfall**

> ...The tracer code approach addresses a different problem. You need to know how the application as a whole hangs together. You want to show your users how the interactions will work in practice, and you want to give your developers an architectural skeleton on which to hang code. In this case, you might construct a tracer consisting of a trivial implementation of the container packing algorithm (maybe something like first-come, first-served) and a simple but working user interface. Once you have all the components in the application plumbed together, you have a framework to show your users and your developers. Over time, you add to this framework with new functionality, completing stubbed routines. But the framework stays intact, and you know the system will continue to behave the way it did when your first tracer code was completed.
>
> The distinction is important enough to warrant repeating. Prototyping generates disposable code. Tracer code is lean but complete, and forms part of the skeleton of the final system. Think of prototyping as the reconnaissance and intelligence gathering that takes place before a single tracer bullet is fired.

More Information about the Tracer Code design, from **The Pragmatic Programmer**

**Tracer Bullets and Prototypes**

# Answer
> 4 votes
Pitfalls: Not Separating your logic from your data. Not testing that your data produces the desired results.

From your comment on Joe's post:

> You want me to code a battle engine for monster encounters, BOOM! I have re-written my engine at least three times this week and I never feel good about it. I mean, the math works, but when I try it out it just feels wonky. Does that make sense?

It sounds like you're conflating engine with data here. Your monster encounter engine should be driven by data. If the data that affects your game balance/fun is wrong, there should be no need to completely rewrite your engine - just tweak your balance variables until it feels right.

However, because balance variables are sometimes interdependent, changing one variable to better one scenario can have a vast (negative) effect on other scenarios.

In order to test that your newly tweaked data doesn't muck up a whole bunch of other cases, it's useful to keep a few test cases around and make sure they aren't broken after tweaking. Here's an admitedly contrived example of how you would test this.

```
TestResult TestPlayerKillsMonsterDuringAttack(PlayerStats, MonsterStats, seed)
{
   Player player(PlayerStats);
   Monster monster(MonsterStats);

EncounterEngine.SeedRNG(seed);

   while(1)
   {
     result = EncounterEngine.Attack(player, monster);
     if (result == PLAYER_DEAD)
       return TEST_FAIL;
     if (result == MONSTER_DEAD)
       return TEST_PASS;
     // result == MONSTER_DAMAGED, PLAYER_DAMAGED is expected.
   }
}

```

Eg. If you call this with PlayerStats.Level == 5 and MonsterStats.Level == 3, you'd expect the player to always defeat this monster eventually.

# Answer
> 2 votes
The pitfall here, as far as I can see, is that you're treating programming and game design as the same task, when really they are separate tasks. As you suggest, this isn't a programming or algorithmic problem (you can code the battle system any way you want), it's about what is fun and interesting to the player.

The answer is, look up resources on game design and game balance. There are actually universities that devote an entire four-year program of study to the topics you're raising, so just giving you a quick-and-dirty answer is impossible (the same way that you'd probably be stumped if someone said "yeah, I've got this idea for a game but I don't know how to program it, what should I watch out for?"). There are books, courses, and online writings out there about game design; seek them out.

# Answer
> 1 votes
The biggest pitfall when writing games is to worry about whether or not you're using the right design patterns instead of just writing code you feel good about.

# Answer
> 1 votes
I would recommend Steve Pavlina's articles about time management and self-motivation: http://stevepavlina.narod.ru/

He is programmer, too. His lifestyle experiments have generated some mainstream media interest.

---
Tags: design-patterns, prototyping
---


# Question
Title: Clear reference implementations of MLAA?
Does anyone know of a clearly written reference implementation of morphological antialiasing (MLAA)?

Intel provide a paper and reference implementation at the following address, but I find the code very opaque.

http://visual-computing.intel-research.net/publications/publications.htm

# Answer
> 2 votes
I don't know whether it's clearer than the original paper, but there is another implementation of the technique (or a variation on it) which I spotted in this year's Siggraph material.

http://igm.univ-mlv.fr/~biri/mlaa-gpu/

As to whether or not you'd get a better answer over at the main site, I don't know - I'd say the majority of people interested in this technique are probably game devs...

# Answer
> 1 votes
These guys have been promising to put some code up for a bit. So this doesn't quite answer your question, but it might be something worth tuning into later.

http://www.iryokufx.com/mlaa/

---
Tags: graphics
---


title: OpenGL ES 2.0: Setting up 2D Projection

text:
# Question
Title: OpenGL ES 2.0: Setting up 2D Projection
This article describes in general, how to draw sharp OpenGL 2D graphics, using fixed function pipeline.

Because OpenGL ES 2.0 has some ES 1.x functions not available (such as: glOrtho()), their functionality must be substituted in Fragment/Vertex shaders.

My question is, how to setup the following 2D projection in programmable function pipeline?

```
const XSize = 640, YSize = 480
glMatrixMode (GL_PROJECTION)
glLoadIdentity ();
glOrtho (0, XSize, YSize, 0, 0, 1)
glMatrixMode (GL_MODELVIEW)

```

How Fragment and Vertex shaders must be configured to fully substitute the above mentioned fixed function 2D projection setup?

# Answer
> 12 votes
In my OpenGL ES 2.X engine, i compute the MVP matrix (Model View Projection) on CPU Side and inject it in vertex shader.

The Orthogonal projection is a 4\*4 matrix. When i have the MVP, i inject it in the vertex shader with:

```
 mMvpLoc = getUniformLocation("uMvp");
 glUniformMatrix4fv(mMvpLoc, 1, false, mMvp.pointer());

```

The mMvp is my matrix 4\*4 on CPU side. The getUniformLocation can be done only one time after you have loaded the program shader.

An example of vertex shader:

```
uniform mat4    uMvp;
attribute vec3 aPosition;
varying vec4 vColor;

void main() {
   vec4 position = vec4(aPosition.xyz, 1.);
   gl_Position = uMvp * position;
}

```

The gl\_Position is a special predefined variable. It must contain the position of the vertex.

An example of fragment shader. For each point to draw, the final color "gl\_FragColor" must be computed:

```
#ifdef GL_ES
precision highp float;
#endif

void main(void)
{
   gl_FragColor = vColor;
}

```

This program draw a triangle with a smoothing of colors defined for each vertex.

For a better tutorial, look this wonderful document.

# Answer
> 9 votes
From the glOrtho doc, with values substituted:

```
         2
    ------------       0              0             -1
       XSize
                       2
        0         ------------        0              1
                   - Ysize
        0              0              -2            -1
        0              0              0              1

```

Store this matrix in a uniform, and you can then apply it (ie do the M . v product) to your incoming vertex positions.

---
Tags: game-design, 2d, shaders, graphics-programming, opengl-es
---


# Question
Title: Essential knowledge for making HTML/JavaScript-based games
I was wondering if any experts out there could share the knowledge and resources of what is necessary to start making games with the latest HTML standards and JavaScript (or what some like to call HTML 5). Are there JavaScript libraries that are essential to the process? Aside from the `<canvas>` tag, what other pieces of HTML do we need to be aware of?

# Answer
> 9 votes
You should be aware of the Audio and Video tags. Web Storage is pretty critical if you need to save a lot of data for saved games etc.

There are already a few Javascript html5 game frameworks, Akihabara is rather popular.

As far as other libraries, Jquery and Functional Javascript are 2 of my favorites.

# Answer
> 6 votes
There are a couple of frameworks already: GameQuery and Akihabara, which is a plugin for jQuery to do some game-related activities, like animations, grouping sprites, detect collisions and read player input.

# Answer
> 4 votes
Just to throw more resources out there, check out RaphaelJS. It's a very nice SVG drawing and animation library that has a nice API. Don't forget to check out the demos.

Overall, I'd recommend `<canvas>` tags over straight DOM manipulation (e.g. making each sprite its own `<div>` to make hit-testing amazingly simple). It's easy to get DOM manipulation wrong and badly performant, whereas traditional 2d development strategies work well on an HTML canvas.

# Answer
> 3 votes
In addition to some of the game-making frameworks that are out there, you should be aware of the Burst Engine, which is a JS framework for displaying SVG-based animations in an HTML5 Canvas:

http://burst.bocoup.com/

So far I've seen people mention the and tags, but there are other DOM things that are vital to JS/HTML game development, including stuff like adding EventListener callbacks to the element for things like the 'mousemove' and 'mousedown' events. For example, this takes the first canvas element it can find and sets it up so that when you click on the canvas, it calls a function you've defined called "shootAtClick":

document.getElementsByTagName("CANVAS")\[0\].addEventListener('mousedown', shootAtClick, false);

You can see it in action in this example where I've extended the Akihabara engine to accept basic mouse control. (Press Z to begin, use arrow keys to move, click the mouse to shoot in the direction of the cursor.)

# Answer
> 3 votes
Knowledge of what HTML5 components are supported in what browsers.

Though cross browser compatibility is getting better and more uniform as time goes on some of the newer components are still not supported entirely equally.

Local storage may have some browser specific differences, and for legacy support you'll definitely need a library such as jStorage or YUI Storage Lite.

Web sockets as well may have browser specific differences, but socket.io looks like a promising library that provides a convenient abstraction.

Audio compatibility is a pretty major component that requires different sound files for different browsers: http://html5doctor.com/native-audio-in-the-browser/

Chrome has a couple of significant audio bugs, such as being unable to play short audio files, and playing many simultaneous sounds can crash the entire browser.

The main thing is to understand the browser differences, using libraries to abstract and provide legacy support as needed.

# Answer
> 1 votes
HTML and JavaScript are honestly fairly bad platforms for game development, but that won't matter until you've decided on a kind of game. The answer would be radically different for a first person shooter, an RTS or a puzzle game.

Notice that you're starting to get vague, hand-wavey answers rattling off random technologies that seem neat. That's a warning sign that you haven't asked a question with a particularly legitimate answer.

You might as well ask what C++ stuff you need to write applications. That depends. Tell us more about the project, and you might get a useful answer.

By and on the whole, there's a reason that nearly all web games are still Flash.

---
Tags: web, html5, javascript
---


# Question
Title: Is SVG a viable technology choice for web-based game?
I have started to read up about the web technology available for doing web-based game with only Javascript, but I have no where got feedback about SVG with HTML5. Is is a viable choice ? Does it performs well compared to other technique like Canvas, DOM & CSS Transformation, etc.

# Answer
SVG is supported in HTML5; whether the browser your player is using supports it is a different story.

Depending on your needs you should check out RaphaelJS. Raphael provides SVG-like support for IE by switching to VML when rendering for IE. Raphael provides a lot of functionality including animations and Cufon font support. It's definitely worth a look.

Since SVG is a part of the DOM it is pretty simple to attach DOM events like "click" and "hover" to the created SVG elements. This might make SVG more suitable for HUD-type displays rather than animating sprites, etc.

You probably have a lot of testing ahead of you to determine the relative performance characteristics of SVG versus canvas, however.

Straight DOM manipulation will probably be the worst of the bunch. As you change things in the DOM the browser's layout engine will recalculate the layout of the page to accomodate your changes which will probably kill your game's performance. If you have to go this route, prefer CSS (especially CSS3-specific features like transformations and keyframing).
> 6 votes

# Answer
Take a look at this website to see SVG compatibility. Right now it's dodgy at best and I wouldn't recommend it for anything other than test demos for showcases.

Don't expect people to use the latest and greatest browser.

I think using SVG would be a huge mistake and will shy your users away when they see things broken.
> 5 votes

# Answer
You would be much better off using Canvas. Neither of them are supported in IE, and canvas is known to be a viable web-based game technology; plus it has decent rendering speed, especially in Chrome (and apparently also in IE9, according to the early demos; I haven't tried it recently). If you need to target older versions of IE and/or mobile platforms, stick to plain old DOM, which doesn't have very good performance but it's still acceptable for simple games (e.g. Pacman).
> 5 votes

# Answer
Short answer yes.

Long answer,

I still work in an environment totally dependent on IE6 and have used this wonderful library for charts. (which uses VML for IE6-IE8) I definitely love canvas and prefer it for writing games with js. So if you want to make a game in svg I say do it, other games have been created using it (see Raphael examples). Regardless you will still be using JS to do it, so if you want to transition to canvas, it wont be as painful.
> 2 votes

---
Tags: performance, web, svg
---


title: How to prepare a sprite for a game?

text:
# Question
Title: How to prepare a sprite for a game?
For example, I created my character drawing on Paint.NET using the Pencil tool and now it's a sprite like asset.

If I want him to move do I need to create many different poses for him and render them according a timer? Or do I need to have each pose side by side in a single image, then render the rectangle I need, thus loading the picture only once?

Thanks.

# Answer
> 5 votes
Usually you try to have them in a single file(maybe even fit multiple characters/backgrounds in just 1 image) and then do all the magic **in memory**.

This files with a lot of images are called **Sprite Sheets** and you can find a lot of them online.

There are many tools out there to manage sprites and aprite sheets both language/framework specific or general use.

Some of the things to consider is if you have things of different sizes, perspectives, how do you represent that information about the sprite sheet.

Depending on the platform and type of game it might be more or less important to use optimization in this area, I would suggest to always **Keep It Simple** if possible.

---
Tags: rendering, sprites
---


# Question
Title: How can I compute the shortest path in Euclidean environments with non-convex polygons?
Can someone suggest papers or algorithms about calculating shortest paths in Euclidean spaces with non-convex polygon as obstacles?

# Answer
This may not be the exact answer to your question but I may suggest you an approach on this issue.

Actually your problem is two problems combined.

1. Finding shortest paths
2. Finding collisions

And the second problem is embedded into first. I may recommend understanding blind search first. Here's a very simple presentation about it: Blind Search

If you read the document for building the state space, you will need to generate state points and they must be legal meaning these states can be on your shortest path so they shouldn't collide with any objects in your space. From now on you can continue with Euclidian collision algorithms. After building your state space and search tree restricted with collisions you may chose any of the shortest path algorithms or one of your own or a modified hybrid one.
> 3 votes

# Answer
The simplest approach is to turn the non-convex polygons into multiple convex ones, then do normal convex collision and pathfinding (via A\* or D\* or whatever). The first process is often called triangulation in computational geometry, and there are several common ways to do it.
> 3 votes

---
Tags: path-finding
---


# Question
Title: How can I get OnMouseEnter to trigger on a 3D Text in Unity3D?
I've just started to learn Unity3D.

I want to create a simple 3D menu with just two 3D Text instances. I've created and named them, then dropped this script:

```
function Awake(){
    print("MenuItem "+gameObject.name+" init!");
}
function OnMouseEnter(){
    print("OnMouseEnter " + gameObject.name);
}
function OnMouseDown(){
    print("OnMouseDown " + gameObject.name);
}

```

I only see the init/awake message printed in the console.

What am I missing ?

**EDIT:**

Sorry, I forgot to add the BoxCollider(Physics\>Box Collider) to my object, so no events were triggered.

# Answer
> 4 votes
First make sure that everything else is set up correctly.

In a different script that's running somewhere, put in this bit of code (C#, and from memory so it may not be 100% accurate):

```
RaycastHit hitInfo;
if( Physics.Raycast( Camera.main.ScreenPointToRay( Input.mousePosition ), out hitInfo ) )
{
    Debug.Log( "mouse is over object " + hitInfo.collider.name );
}

```

If that doesn't work then you probably don't have your colliders set up correctly. If it does print out something then you have something else messed up.

---
Tags: unity
---


title: Motion blur is blurring static stuff

text:
# Question
Title: Motion blur is blurring static stuff
I made a motion blur using OpenGL immediate mode, basically it involves saving screen to texture, then rendering blended texture back (let's skip the details) with something like this:

```
glBegin(GL_QUADS);
        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
        glTexCoord2f(0.0f, 1.0f); glVertex2f(0, 0); // Bottom Left Of The Texture and Quad
        glTexCoord2f(1.0f, 1.0f); glVertex2f(800, 0);   // Bottom Right Of The Texture and Quad
        glTexCoord2f(1.0f, 0.0f); glVertex2f(800,  600);    // Top Right Of The Texture and Quad
        glTexCoord2f(0.0f, 0.0f); glVertex2f(0,  600);
    glEnd();

```

My problem is: When I use the motion blur, seemly the blended screen get 1 pixel shifted to the opposite of (0, 0), resulting in everything getting blurry, not only the moving stuff.

The stronger I apply the effect, the stronger everything else blurs (as seemly every frame of blur get 1 more pixel shifted).

How I fix that?

# Answer
> 5 votes
The texel co-ordinates, if you have bilinear filtering, are falling between the texels rather than being centered.

You either need to to add half a texel to the UVs, or turn off filtering.

---
Tags: opengl, special-effects, blur, effects
---


# Question
Title: Programatically loading fonts, textures, and media in XNA
So far, in my rhythm game, I've been using XNA's Content Pipeline for loading static resources in my app (videos, sound effects, etc). However, down the road I'd want to allow users to create their own themes, as well as making custom notecharts for whatever songs they'd like to play. Is there any way to load say, a Texture2D or Video object, from disk without using the Content Pipeline, given a file path to the resource?

**EDIT**: Even thought this is XNA, I'm targeting Windows only (no Zune, WP7, or Xbox 360).

# Answer
> 5 votes
Use the `Texture2D.FromFile` method; for the first parameter, give it your `GraphicsDevice` which is a property of the `Game` class (so from within a method of the Game class, just use `this.GraphicsDevice`).

Unfortunately only `Texture2D` objects can be loaded this way; a `Video` object is not so easy to load.

# Answer
> 3 votes
It's entirely possible to run the content build process at runtime using MSBuild. The following sample shows you basically how to do it: http://creators.xna.com/en-GB/sample/winforms\_series2. This particular example uses windows forms, but there is nothing preventing you from doing the same thing in an actual game.

The big problem is that the content pipeline assembly (which is where all the processors/importers/build tasks necessary for building are) is not included in the XNA Framework redistributable. This means that in order to actually create and/or load custom content your users would need to install whatever version of XNA Game Studio your game was built with. They would never need to actually use any of the software included in it, but they would need to install it. Depending on your game and who you expect to be creating and using custom content this may or may not be acceptable.

# Answer
> 1 votes
Some of the content processors expose classes which do a lot of the heavy lifting, e.g. take in a Stream and produce an intermediate object (like the data necessary to construct a mesh, but not an actual Mesh object). You may be able to do some additional processing to transform the intermediate object into the final object that you want to consume. Some of those classes may actually even spit out the final object for you. It varies by the type of content. I suggest digging through the content processors for the relevant content types and see anything useful is exposed. You may have to rewrite some bits yourself (Reflector is your friend), but it could be worth the effort if you really don't want to use "precompiled" assets.

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