title: How to handle netcode?

text:
# Question
Title: How to handle netcode?
I'm interested in evaluating the different ways that the netcode can "hook into" a game engine. I am designing a multiplayer game now, and so far I have determined that I need to (at the very least) have a separate thread to handle the network sockets, distinct from the rest of the engine which handles the graphics loop and scripting.

I did have one potential way to make a networked game entirely single-threaded, which is to have it check the network after rendering each frame, using non-blocking sockets. However this is clearly not optimal because the time it takes to render a frame is added to the network lag: Messages arriving over the network must wait until the current frame render (and game logic) completes. But, at least this way the gameplay would still remain smooth, more or less.

Having a separate thread for networking allows the game to be completely responsive to the network, for instance it can send back an ACK packet instantly upon receipt of a state update from the server. But I'm a little confused about the best way to communicate between the game code and the network code. The networking thread will push the received packet to a queue, and the game thread will read from the queue at the appropriate time during its loop, so we haven't gotten rid of this up-to-one-frame delay.

Also, it seems like I would want the thread which handles the sending of packets to be separate from the one that is checking for packets coming down the pipe, because it wouldn't be able to send one off while it is in the middle of checking if there are incoming messages. I am thinking about the functionality of `select` or similar.

I guess my question is, what's the best way to design the game for the best network responsiveness? Clearly the client should send user input as soon as possible to the server, so I could have net-send code come immediately after the event processing loop, both inside of the game loop. Does this make any sense?

# Answer
Ignore responsiveness. On a LAN, ping is insignificant. On the internet, 60-100ms round-trip is a blessing. Pray to the lag gods that you don't get spikes of \> 3K. Your software would have to run at very low number of updates/sec for this to be a problem. If you shoot for 25 updates/sec, then you've got 40ms max time between when you receive a packet and act on it. And that is the single-threaded case...

Design your system for flexibility and correctness. Here is my idea on how to hook a network subsystem into game code: Messaging. The solution to a lot of problems can be "messaging". I think messaging cured cancer in lab rats once. Messaging saves me $200 or more on my car insurance. But seriously, messaging is probably the best way to attach any subsystem to game code while still maintaining two independent subsystems.

Use messaging for any communication between the network subsystem and game engine, and for that matter between any two subsystems. Inter-subsystem messaging can be a simple as a blob of data passed by pointer using std::list.

Simply have an outgoing messages queue and a reference to the game engine in the network subsystem. The game can dump messages it wants sent into the outgoing queue and have them automagically sent, or perhaps when some function like "flushMessages()" is called. If the game engine had one large, shared message queue, then all subsystems that needed to send messages (logic, AI, physics, network, etc.) can all dump messages into it where the main game loop can then read all of the messages and then act accordingly.

I would say that running the sockets on another thread is fine, though not required. The only problem with this design is that it is generally asynchronous (you don't know precisely when the packets are being sent) and that can make it hard to debug and making timing related issues appear/disappear randomly. Still, if done properly, neither of these should be a problem.

From a higher level, I'd say separate networking from the game engine itself. The game engine doesn't care about sockets or buffers, it cares about events. Events are things such as "Player X fired a shot" "An explosion at game T happened". These can be interpreted by the game engine directly. Where they are generated from (a script, a client's action, an AI player, etc) doesn't matter.

If you treat your network subsystem as a means of sending/receiving events, then you get a number of advantages over just calling recv() on a socket.

You could optimize bandwidth, for example, by taking 50 small messages (1-32 bytes in length) and have the network subsystem package them into one large packet and send it. Maybe it could compress them before sending if that was a big deal. On the other end, the code could uncompress/unpackage the large packet into 50 discrete events again for the game engine to read. This can all happen transparently.

Other cool things include single player game mode that reuses your network code by having a pure client + a pure server running on the same machine communicating via messaging in shared memory space. Then, if your single player game operates properly, a remote client (i.e. true multiplayer) would operate as well. Additionally, it forces you to consider ahead of time what data is needed by the client since your single player game would either look right or be totally wrong. Mix and match, run a server AND be a client in a multiplayer game -- it all works just as easily.
> 14 votes

# Answer
> I need to (at the very least) have a separate thread to handle the network sockets

No you don't.

> I did have one potential way to make a networked game entirely single-threaded, which is to have it check the network after rendering each frame, using non-blocking sockets. However this is clearly not optimal because the time it takes to render a frame is added to the network lag:

Doesn't necessarily matter. When does your logic update? There's little point getting data off the network if you can't do anything with it yet. Similarly there's little point responding if you have nothing to say yet.

> for instance it can send back an ACK packet instantly upon receipt of a state update from the server.

If your game is so fast-paced that waiting for the next frame to be rendered is a significant delay, then it's going to be sending enough data that you don't need to send separate ACK packets - just include ACK values inside your normal data payloads, if you need them at all.

For most networked games, it's perfectly possible to have a game loop like this:

```
while 1:
    read_network_messages()
    read_local_input()
    update_world()
    send_network_updates()
    render_world()

```

You can decouple updates from rendering, which is highly recommended, but everything else can pretty much stay that simple unless you have a specific need. Exactly what kind of game are you making?
> 4 votes

# Answer
> However this is clearly not optimal because the time it takes to render a frame is added to the network lag: Messages arriving over the network must wait until the current frame render (and game logic) completes.

That's not true at all. The message goes over the network *while* the receiver renders the current frame. The network lag is clamped to a whole number of frames on the client side; yes- but if the client has so few FPS that this is a big deal, then they have bigger problems.
> 2 votes

# Answer
Network communications should be batched. You should strive for a single packet sent each game tick (which is often when a frame is rendered but really should be independent).

Your game entities talk with the network subsystem (NSS). The NSS batches up messages, ACKs, etc and sends a few (hopefully one) optimally sized UDP packets (~1500 bytes usually). The NSS emulates packets, channels, priorities, resend, etc while only sending single UDP packets.

Read through the gaffer on games' tutorial or just use ENet which implements many of Glenn Fiedler's ideas.

*Or* you can just use TCP if your game doesn't need twitch reactions. Then all the batching, resends, and ACK problems go away. You'd still want an NSS to manage bandwidth and channels, however.
> 0 votes

# Answer
Don't completely "ignore responsiveness". There is little to gain from adding another 40ms latency to already delayed packets. If you're adding a couple of frames (at 60fps) then you're delaying the processing of a position update another couple of frames. It is better to accept packets quickly and process them quickly so you're improving the accuracy of the simulation.

I've had great success optimising bandwidth by thinking about the minimum state information needed to represent what is visible on the screen. Then looking at each bit of data and choosing a model for it. Position information can be expressed as delta values over time. You can either use your own statistical models for this and spend ages debugging them, or you can use a library to help you out. I prefer to use this library's floating point model DataBlock\_Predict\_Float It makes it really easy to optimise the bandwidth used for the game scene graph.
> 0 votes

---
Tags: c++, architecture, networking
---


# Question
Title: HLSL: Using instance float input to select texture index, possible?
I'm writing a game for the xbox360 using XNA. I would like to draw several models with a single DrawInstancedPrimitives call. Each model will use a different texture.

To do this, I would like to create a sampler array, and select which sampler to use in the array from a value passed into the shader from the instance vertex buffer.

So the shader code might look like:

```
void InstancingVertexShader(..., in float4x4 data : TEXCOORD0)
{
    output.TextureIndex = data._m00
}

void InstancingPixelShader(...)
{
    color = tex2Dlod(samplers[input.TextureIndex]);
}

```

Before I start trying to implement that, my question is:

Is it possible to do that, or will the HLSL complain?

Are there any cons to this method that I should know about?

# Answer
> 6 votes
Practical answer: **No** (in SM 3.0; apparently you can in SM 4.0, but I haven't checked.)

Technically the answer is yes, as it is legal HLSL. But if the sampler index cannot be determined at *compile* time, then compilation will fail because there is no way to express this as a GPU instruction.

So, **you can only select a sampler by index if that index is constant at compile time**.

Of course you can achieve a similar effect to indexing by using dynamic branching or simply doing multiple reads and selecting one. But this is only a good idea if you have *lots* of texture bandwidth to spare.

The best solution is probably a texture atlas. You can create your own mipmaps, if that is a concern.

(Here is a thread on GameDev.net that is the same as your question.)

# Answer
> 4 votes
With 3D textures you could use the 'w' component of the 3D texture co-ordinates to select a different texture to sample from.

What are you trying to achieve? Are you making big savings by rendering all 3 with a single call? You could also use a texture page/atlas to have all 3 textures in one larger texture (maybe with a little wastage) and then have the 3 set's of UV's pick the correct texture out of the right part of the image.

# Answer
> 2 votes
This is posted as an answer because I don't have enough reputation to write a comment.

You mention that you cannot use texture atlas because then you can't use mipmapping. This is not true. Just generate the mipmap chain for texture atlas yourself (for example by generating mipmaps for individual textures first and then combining them into one big texture dynamically; this is relatively easy because Texture2D generated mipmaps automatically). In shader you can use tex2Dlod, tex2Dgrad, ddx and ddy functions to calculate preferred mipmap level.

Also, you could take a look about hardware instancing which is obviously available also on Xbox (http://dotnetkicks.com/csharp/Hardware\_Instancing\_in\_XNA\_on\_the\_XBOX\_360)

# Answer
> 1 votes
I didn't have the time to actually read the entire thing, but judging by the synopsis, this might be for you:

There's a sample in the nVidia Direct3D SDK 10.5 that is described as follows:

> This sample is a simple example using Texture Arrays in DX10. It uses a texture array as a palette of terrain textures to render a terrain mesh with many textures in a single draw call. A similar effect in previous APIs would require a texture atlas or multiple draw calls.

nVidia D3D SDK 10.5 samples page (it's at the bottom of the page)

nVidia White Paper on Texture Arrays and Terrain Rendering

nVidia Demo Project Download

I'm aware this is a) not directly regarding XNA and b) possibly not quite what you want but maybe you can gain get a hold of further leads there.

---
Tags: xna, xbox360, hlsl
---


title: Starting off with coordinate systems

text:
# Question
Title: Starting off with coordinate systems
Where is a good place to start with learning how to program custom coordinate systems in a 3d environment?

Are there any good books on he topic of gaming coordinate systems? I would like to build a real life data structure based on techniques used for game programming.

# Answer
> 3 votes
Books about Game Engine development usually have chapters/sections on coordinate systems:

Game Coding Complete (Chapter 13)
Game Engine Architecture (Chapter 4)
3D Game Engine Design (Chapter 2)

# Answer
> 1 votes
Also see http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/ . It's about the math used in coordinate systems for games. Has explanations for creating user coordinate systems and matrix transformations.

It should be helpful

# Answer
> 0 votes
I can greatly recommend this book. It covers 3D coordinate systems in great detail (and is not a pain to read).

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


# Question
Title: (real) 3d map rendering in wpf without an engine - how to handle the map data?
I'm just doing some research before embarking on rendering a 3D map inside a wpf app. I've never delved into 3D before, and hence the question..

I have map data (in several formats, and many files) which I need to render - probably in a wpf `viewport3D`. All the map data is in 2D, but I can add a height-map and convert to 3D. This data can be altered (updated) by the user without my knowledge, but a bit of data-crunching can be done before application start, so it doesn't need to be **entirely** realtime.

I've googled around but can't find a framework for how to represent my world. Do I write a terrain-tile stream server to handle requests from the viewport about which area to display? Do I create a collossal map, and hope it fits into memory?

Are there tutorials about how to deliver large terrains for rendering? Most of them seem to be about building a world inside an editor..

My world could be about 1000km * 1000km, with roads, parks, forests, power lines, street addresses (etc) - it's going to be a fair bit of data..

The machines that this software has to run on are ruggedized laptops - so not terribly fast (Core 2 duo?) and probably without DX10, but we can insist on heaps of RAM and HDD (SSD?).

Thanks - I'm looking forward to getting into this project..

# Answer
It sounds like there are several problems you need to solve so I would try to approach each problem at a time and slowly make my way to a working solution.

You said you don't have experience with 3D. There is this great tutorial that shows you how to render 3D shapes in WPF.
This will get you started with 3D and WPF, and it even shows you how to display a small terrain so you'll get a good idea of the type of data structure you need to store your terrain data.
Once you have the basic data structure you should be able to extrapolate how much memory your large terrains are likely to take up.

As for handling streaming terrain data you might want to pick up a good book on Game Engine development that addresses this topic.
For example Game Engine Architecture has a section (14.4) about this.
> 1 votes

---
Tags: algorithm, directx, terrain-rendering, data-structure, wpf
---


# Question
Title: How to create a perspective field of view matrix?
Hey, hello. I am learning a little of WebGL (OpenGL ES 2.0) through the http://learningwebgl.com tutorials, but it uses a third party library to create the View, Projection and transformation matrices (glutils.js). Well, I don't really like the idea of depending on a non standard library, so I am trying to learn how to create these matrices by myself.

I've already managed to understand most of it, and although I can't really tell why these matrices work if someone asks me, at least I know how to build them when I need to. Now I have my own lib to work with 4x4 matrices. I can create translation, scale, rotation and the lookAt matrix, but, I am having a hard time finding out how to create the perspective matrix. Anyone could help me out?

Here is my lib: http://pastebin.com/csMi9GuC

# Answer
> 3 votes
Very well. That is fine approach. Sadly lots of game programmers do not understand their matrices, so don't worry about it now. Personally i use directx documentation as my personal reference if i'm not sure.

There is perspective matrix.

---
Tags: opengl, mathematics, opengl-es, matrix, webgl
---


# Question
Title: Technique to have screen independent grid based puzzle with sprite animation
let's say I have a fixed size grid puzzle game (8 x 10). I will be using sprites animation, when the "pieces" in the puzzle is moving from one grid to another grid.

I was wondering, what is the technique to have this game being implemented as screen resolution independent. Here is what I plan to do.

1) The data structure coordinate will be represented using `double`, with 1.0 as max value.

---

```
// Puzzle grid of 8 x 10
Environment {
    double width = 0.8;
    double height = 1.0;
}

// Location of Sprite at coordinate (1, 1)
Sprite {
    double posX = 0.1;
    double posY = 0.1;
    double width = 0.1;
    double height = 0.1;
}

// scale = PYSICAL_SCREEN_SIZE
drawBitmap (
    sprite_image,
    sprite_image_rect,
    new Rect(sprite.posX * Scale, sprite.posY * Scale, (sprite.posX + sprite.width) * Scale, (sprite.posY + sprite.Height) * Scale),
    paint
);

```

---

2) A large size sprite image will be used (128x128). As sprite image shall look fine if we scale from large size down to small size, but not vice versa.

Besides the above mentioned technique, is there any other consideration I had missed out?

# Answer
Personally I wouldn't use *double* to store sprite coordinates. Since you have a fixed grid, why not simply use grid coordinates? *Double* would probably work, but is more complicated and you'll suddenly end up with rounding errors or equality check problems.

Using grid coordinates, your sprite would be located at: `posX = 1` and `posY = 1`. You can then calculate the actual screen coordinates by multiplying with the grid-cell size. Animation is a special case, but I guess you'll move the sprites from one grid-position to another one, so you can calculate the initial position in pixels (screen space) and the target position (also in screen space) and animate from one position to the other.

128x128 is probably a bit large for a sprite.. I guess 64x64 is still sufficient. But it really depends on how big you want to scale these sprites. 64x64 will result in a 640x512 grid.
> 2 votes

# Answer
How many different sprites are we talking about? Is it possible to draw the sprites with vector graphics? If you search some you can probably find a way to draw svg (scalable vector graphics) with a canvas directly.

Or, if you are ambitios, you can draw them yourself. Even if it is lots of work, it have its advantages. For instance, it is easy to change various colors of the drawing to account for selected/disabled/locked/etc status.
> 1 votes

# Answer
To solve this problem in a game I'm working on I adopted the Model View ViewModel design. I had the following architecture:

```
class BoardModel {
    int Columns = 4;
    int Rows = 4;
    SquareModel[] squares;
}

class SquareModel {
    int Column;
    int Row;
}

class SquareViewModel {
    float X;
    float Y;
    float Width;
    float Height;
    SquareModel model;
}

class SquareView {
    Texture texture;
    Draw(SquareViewModel square);
}

```

Notice that the `SquareModel` isn't aware of its position on the screen or its dimensions. When switching resolutions or platforms it is sufficient to change the dimensions in the `SquareViewModel` and the texture used by the `SquareView`.
> 0 votes

---
Tags: android
---


title: Outsourcing iPhone Game Development

text:
# Question
Title: Outsourcing iPhone Game Development
I'm looking for good sources to outsource virtually every aspect of an iPhone game:

Writing Graphics Programming

I have a good amount of programming experience so putting everything together should not be a problem.

What are some reputable sources for outsourcing this kind of development? Is it feasible to approach game development from this angle?

# Answer
The way you have phrased your question implies to me that you intend to break up each subcomponent of the game and farm that out to an individual outsourcing entity (somebody gets the graphics, somebody gets the physics, somebody else gets the audio, et cetera). That seems fraught with peril -- you will need to spend an inordinate amount of time making extremely clear, detailed requirement and design specifications to give to each outsourcing entity in order to have a prayer of integrating everything without doing significant reworking on your own -- thus wasting money and probably defeating the purpose of outsourcing anyhow.

It's more feasible to essentially pay a single somebody to develop the entire game. **You can find outsourcing companies via Google, unfortunately I don't know of a reputable directory of such companies.** You *might* have some luck at the Help Wanted forum on GDNet, although I wouldn't hold my breath.

You may be able to handle outsourcing every component individually if you do them one at a time, and you write the core game yourself (basically providing a design and hooks for a rendering API, and having somebody else fill it out, et cetera).

I feel like you're vastly underestimating the amount of iteration and clean up that is going to go into outsourcing code development, and when you add that to the cost (because you'll get what you pay for) **I'd be willing to bet that outsourcing that much of the game's development is not financially viable** for indie game development. If you were a large studio, perhaps the overhead would be amortized a bit.
> 6 votes

# Answer
It may be some stupid to say this, but anyway: aren't you looking for a scriptable game engine?

This way all internal aspects of the application will be handled by the engine itself and you can just join the parts (art, AI, levels) that you can generate on your own or, if it seems more convenient for you, contract with someone else.

If all the outsourced parts work on the same toolbox and you establish a robust set of specifications I think this could be, if not easy, at least not impossible.

Also if, as you mentioned, you have programming experience it should be quite easy for you to work over an engine.

As an example I would point you to the omnipresent UDK.

Hope this can help you.
> 1 votes

---
Tags: outsourcing
---


# Question
Title: Different number of lights => different shader
I have a shader that computes lighting for each light.

```
PointLight PointLights[10];

uniform const float NumPointLights;

for(int i = 0; i < NumPointLights; i++)
{
lightVec = PointLights[i].Position - pos;
lightDist = length(lightVec);
    // Do other stuff with light here, etc.
}

```

If I set NumPointLights to 2, the loop still iterates 10 times, and discards the result of the last 8 iterations.

Should I set a compiler flag that will permit the loop to actually loop only 8 times, or should I make 10 shaders, a shader for each number of lights that can be rendered?

On some small pieces of geometry I occaisionally need 10 lights. 90% of the time I only need 1-2 lights. How do I proceed?

# Answer
Your dilemma hints at a larger problem that's well-known to the graphics programming community, commonly referred to as "combinatorial shader explosion." As the name implies, it's usually considered in the context of very large numbers of shader permutations, but the basic principle is the same. Solutions geared toward solving the overarching problem are **industrial-strength**, and as far as I'm aware, can be categorized into two main approaches:

1. So-called "Ubershaders"
2. Code generators

# Ubershaders

The term ubershader refers to a shader which has conditional code to handle an extremely large number of permutations with regard to feature support. Likely candidates include variations on light counts/types, animation (number of bones? Dual quaternion skinning?), vertex formats, shadow map sampling and more. Because dynamic branching in shaders both pushes shader limits, and is not particularly performant, these variations are usually controlled by preprocessor directives, varying the values of preprocessor definitions (e.g. #define USE\_PCF\_SHADOW\_FILTERING 1, #define NUM\_PCF\_SAMPLES 16, etc).

# Code generators

Code generators, on the other hand, actually assemble the body of the shader from the ground up. An example of such an approach would be Shawn Hargreaves' shader fragment system.

As Shawn mentions in his article:

> If you have five, ten, or even fifty shaders, this system is probably not for you. If you have thousands, however, automation is your friend.

I would say this advice applies to ubershaders as well.

As I mentioned above, these solutions are industrial-strength. Both have their pros and cons, and both are very complex to manage. Importantly, you need to know ahead of time which shader combinations your engine is going to potentially require, or you'll end up compiling them on-the-fly; this is obviously undesirable, because if you don't have the shader handy, compilation takes a considerable amount of time.

---

# Bonus: Deferred rendering

You should also be aware that, in the case of light and shadow complexity specifically, deferred rendering approaches also help cut down on shader permutations.

Imagine the following simple approach (expressed in pseudo-code):

```
for ( each mesh )
{
  draw mesh with ambient lighting only;
  for ( each light )
  {
    additively blend single light's diffuse + specular contributions \
      for this mesh into frame buffer;
  }
}

```

Now your shader only needs to handle one light, and you invoke it as many times as necessary. Unfortunately, this naive approach does not scale very well in terms of performance — with deferred shading, you draw each mesh only once, and then draw each light only once.

An in-depth explanation of deferred shading is beyond the scope of this answer, but you can start looking here for more info.

It's similarly possible to calculate shadows in a "deferred" manner, which is much simpler, and plays nicely with traditional ("forward") rendering — you don't need deferred shading to implement deferred shadows.
> 15 votes

# Answer
Ah performance optimisation! The first question is, of course, what are you limited by? Are you pixel-shader limited?

If you are, then obviously you should spend some time on this. If you are not, then simply calculate 10 lights and be done with it.

What I would probably do is implement just two shaders. One that calculates 3 lights (which is fairly traditional), and one that can do an arbitrary number of lights. That way you can work on optimising 90% of your scene, without losing the ability to do fancy lighting in special cases.

Also, you might find my answer here about HLSL conditionals interesting. How are you determining that it is iterating 10 times?

Also, here are three more resources that are somewhat related.
> 5 votes

---
Tags: xna, shaders, xbox360, hlsl, directx9
---


# Question
Title: How should i have the key/mouse input in an advanced java game?
I am a self taught programmer, so I do not know the proper ways to do things. I have made simple games like asteroids and snake, but in those games, you can easily modify the variables within the keyevent functions. Here is how I did it in my simple Asteroids game:

```
/*
* key listener events
*/
public void keyReleased(KeyEvent k){
    int keyCode = k.getKeyCode();

    switch(keyCode){

        case KeyEvent.VK_LEFT:
            turnLeft = false;
            break;

        case KeyEvent.VK_RIGHT:
            turnRight = false;
            break;

        case KeyEvent.VK_UP:
            accel = false;
            break;

        case KeyEvent.VK_1:
            cls = true;
            break;
        case KeyEvent.VK_ENTER:
            break;
        case KeyEvent.VK_SPACE:
            fire = false;
    }
}
public void keyTyped(KeyEvent K){}
public void keyPressed(KeyEvent k){
    int keyCode = k.getKeyCode();

    switch(keyCode){

        case KeyEvent.VK_LEFT:
            turnLeft = true;
            break;

        case KeyEvent.VK_RIGHT:
            turnRight = true;
            break;

        case KeyEvent.VK_UP:
            accel = true;
            break;

        case KeyEvent.VK_1:
            cls = false;
            break;
        case KeyEvent.VK_ENTER:
            clearAllBullets();
            break;
        case KeyEvent.VK_SPACE:
            fire = true;
    }
}

```

If I were to make a more advanced game (with a main menu, options, main game, etc.), how should I do the key/mouse input?

Also, if I were to go into the single-player, should i put all of the gameplay code into one class? Is there a way to put the single player code into a separate class and somehow have the key input still modify the variables and such?

# Answer
I am no expert, and I nevertheless suggest separating both the controls and the business/game/menu (name it) logic.

I have already answered a similar question in regards to giving directions to a Snake in a game designed with classes. Java being an object-oriented language, I guess you are able to write adequate classes and stuff. Then, when you have written your object class, if it is so that your object needs to react to some keys and mouse clicks, I would go with a Controller class that knows what is currently displayed on screen, then tell this object what it should do depending on the key that has been pressed or the region that has been clicked.

Here's the link to the question I told you about which I answered about separating the controls from the object logic. It also includes a code sample which illustrates my thought.

Moving my sprite in XNA using classes

> (*Unfortunately, none of the answer was yet accepted by the OP, so we don't know for sure whether it solved his concerns. Besides, I'm always designing this way and found no trouble by doing so so far.*)

Now I know, it's tagged XNA. The idea or design is a higher architecture level than the technology that is used, so this design could be simply adapted to Java syntax. The general idea remains the same. =)

I do hope this helps! I'll be glad to help further when I can, just ask! =)
> 3 votes

# Answer
Will's answer shows you what is probably the most flexible and straightforward, and I'd recommend it if what you need is straight-ahead input polling.

But, if you need an easy way to check for different combinations of button presses while avoiding massive amounts of switch and if statements, you can use bit flag enums.

I dunno what you know about bit vectors, so here's an overview: Basically, you have an enum class that represents all possible keys. Each enum should have a value that corresponds to a bit in an integer. (ie: 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0011, 0x0012, 0x0014, etc). (Link for doing this in Java).

Now, since you can pass around information about up to 32 (or 64 if you use longs) keys, you can have a hash table that associates bit vectors (int or long) with objects falling some sort of KeyComboCallback interface, which just contains a single method call, Do(), that gets called when the associated combination of keys are pressed.

Now when you instantiate/initialize your player object or your menu object, you can make a call to some sort of input manager and pass it all the key combination bit vectors you want and associate them with anonymous inner classes.

```
// ... in your init code for Player

InputManager.map(
    KeyMap.A.val() | KeyMap.B.val() | KeyMap.C.val(),
    new KeyComboCallback(KeyMap keys) {
        public void Do() {
           this.DoCrazyAwesomeComboAttack();
        }
    });

// ...  continue init

```

This is really quick & convenient in C++ and C#, but Java enums are special, so you may find it more convenient to create a KeyCombination class or something that will store all of this information without worrying about enums. But the idea is still the same. I'm using this in an XNA game, and I like the facility a lot. You can also use it to separate input regions, which is useful for comparing different parts of the keyboard or gamepad independently (might be useful for two players on one keyboard).
> 5 votes

---
Tags: java, input
---


title: Daz3D for creating game assets

text:
# Question
Title: Daz3D for creating game assets
Are the Daz products viable for 2D/3D game asset creation or are they geared more towards creating art? I am thinking of the products: Daz Studio 3D, Bryce and Carrara.

If you have used any of these products for 2D or 3D asset creation please provide input on any export issues you have encountered.

# Answer
I know this was asked a while back but i've spent some time on this for my own project so in case anyone else wants to know here are the results of my experiments (assuming you are thinking of skinned characters):

**On Licensing**
Daz is venturing (tentatively) into the 3d assest market and as such their new EULA does permit use of their models (& derived) in computer games with a couple of restrictions:

> SUMMARY:
>
> Summary of section 5 – INCORPORATION OF 3D MODEL(S) INTO OTHER WORKS
>
> You may use the 3D content/models or derivatives thereof when embedded in a single game or other project if you have purchased the “single-use” license. By purchasing the “multiple-use” license, you may use the content/models or derivatives thereof when embedded in the number of games or projects authorized by the multiple-use license.
>
> You may publish, market, distribute, transfer or sell any games or projects that contain DAZ content/models as long as the DAZ content/models are not accessible to end users in their native formats and are protected by asset protection technology, encryption or whatever means necessary to protect them from theft or copyright infringement.

(https://helpdaz.zendesk.com/entries/123880-what-is-daz-3d-s-real-time-game-content-end-user-license-agreement-eula)

In regards to open source projects I am not sure (I emailed and haven't had a response yet). Bear in mind however that most of the content sold in Daz's store and in other marketplaces like Renderosity have their own licenses.

*\[See update 1\]*

**File Formats**
Daz Studio is free and can import/export OBJ and COLLADA files as standard. Plugins can be purchased to export to CR2 (Poser Characters) and FBX.

In my experience OBJ transports fine between 3DS Max & Daz Studio but the associated MTL material files do not; I am not sure whether this is due to Daz or Max (probably a bit of both). The problems can be resolved easily with a text editor - but it is still another stage in your pipeline no matter how small.

An important point to consider is rigging. As opposed to vertex weighting, Daz models consist of many distinct poly groups which correspond to bones. These groups deform with respect to a single bone based on spherical falloff zones defined for each axis of rotation. (I think this is used to maintain compatibility with Poser; certainly i've seen posts on their forums of people saying vertex weighting would be easier when creating clothing)

The OBJ format does not support vertex weights, or skeletons (though I suppose you may be able to pack one in with something like empty poly groups, I doubt it would be pretty).

Daz can convert these falloff zones to vertex weights when exporting to FBX and the results are pretty good - I'm sure a modeller could do better if they were working with vertex weighting natively but its unlikely you'll notice unless the limbs are at extremes.

Poser CR2 files support the poly group rigging but are horrifically complex. Check out Kuroyume's CR2 spec (http://www.kuroyumes-developmentzone.com/poser/poserfilespec/products\_poser\_cr2.html) to see what I mean.
CR2 files make liberal use of external references so you will need to process OBJs in full to support CR2s. Further that spec is for an older format. The latest version (8 I believe) had about 5 new sections when I tried to import it using the CR2 importer I've been working on.

I haven't seen any open source CR2 importers you could modify easily for your project - it looks as if usually people start on one then give up halfway through and writing one myself I can see why!

**Performance**
Daz models are very high poly but I dont think this is as much of an issue as people make out. Daz has 'Decimator', a plugin which can reduce the poly count, though I don't even use it on the Daz models I use in my XNA project as they render perfectly fast; the count is about ~130,000 polys for V4 (base female human model).

Whats more of a concern is the textures.

1. They are very large (esp. third party products), so you will need to resize them in the pipeline depending on your engine/api.
2. They are numerous. (I'm talking 3 different textures for the EYE!)
3. Most importantly the materials have all sorts of 'odd' configurations - things like bump and transparency maps with no diffuse map. Its not that they are hard to support, its that there are so many different combinations you either need a very comprehensive importer or very comprehensive shader set and model class.
My importer combines the trans and diffuse maps (creating if necessary), and adds vertex colour and normal data if missing - as a result I pack alot of 'white' structures into the resultant file but I only need 4 shaders.

**Alpha Sorting**
Daz models (like probably most organic models) makes liberal use of transparency maps; further the nature of the models prohibits depth sorting before drawing.

Let me pose a question: When you model an eye, do you surround the completed model eye with an extraneous sphere that has a solid diffuse colour (no map) but a transparency map that turns it invisible? So when the unsuspecting prospective game developer loads up the model the eyes appear black from the outside while from the inside are textured fine? Daz does. (Its to create the glossy wet sheen effect - turn the opacity setting of the material 7\_EyeSurface down to 0 on the default V4 to see what I mean)

I use 2-pass alpha sorting which is best for the 'cutout' transparency maps (which is what Daz models use it for mostly). This is built right into my model base class and engine from the start.

**Customizing the character**
Clothes don't have to have a loose fit to deform properly once exported with bone weights, but beware that those ~90,000+ polys they are obscuring will still be there.

**Animation**
FBX supports animation (in theory). Daz does have a keyframe animation editor but its a little 'light' and not easy to use. Daz also has plugins such as AniMate Lite which allow you to drag and drop animation segments into a timeline and then bake the keyframes into an animation to be exported.

I've found extracting animations from FBX to be a little hit and miss, especically when baked from AniMate. For example, the walking animation 'block' will acctually move the model in model space so you couldn't simply pop that into the timeline, bake, export and then move your character around in time with it in an FPS.

Further I've found that sometimes the exported animation causes the mesh, or a prop, to deform incorrectly; and since FBX files are accessed with an Autodesk SDK as opposed to with a custom importer like most formats its not trivial to look inside and see where the problem lies. (On the plus side I've worked out where the Dead Space developers got the ideas for all their monsters.)

**To Summarise**

1. If you want to use Daz models you will need the FBX exporter because OBJ is not comprehensive enough and CR2s are too complex to import, and even if you did your shader would need to support a new type of rigging\*.
2. Do not be concerned with poly counts or texture sizes until you need to be. Textures can be resized (and also combined into one texture for the whole character using Daz's Texture Atlas) and Daz has plugins for reducing poly counts IF you need them.
3. Do be aware that the models will have quirks that a game artist would never dream of putting in - 3x texture for 1x eye and 'specular surface sphere' for example.

I think Daz models are a super resource, esp. for hobbyist developers, but to be used seriously they would be best utilized *as* a resource as opposed to a complete asset - design your characters, clothe them, *then* cull unseen polys, bake and animate in the modeller of your choice. Also, while Studio itself is free, to create and equip characters to a resonable standard, and export them in useful formats, you will need ~£70-100 worth of content and plugins minimum.

\*Not saying that would be prohibitively hard though - maybe have say a single 'vertex distance' plugged in by the importer as opposed to four vertex weights, and set the falloff zones & transform shader wide for each poly group (geometry segment).

**Update 1:** When purchasing Daz models for use in realtime rendering environments, it needs to be done via Daz's Developer Store at http://developer.daz3d.com; this site has the option to buy a Single or Multiple Use license. The V4 Base in the developer store starts at ~$60 so it may be worth prototyping with the free V4 Base from the regular store first.

According to the Daz Developer Store FAQ models may not be given away for free, i.e. distributed as a part of any free project such as an open source game or mod.
> 4 votes

# Answer
Hey there, there's no problem with exporting to common model formats, however if you have any content from Daz3D website they are very much geared towards art use so are generally very high poly and wont be good for real time use.
> 1 votes

# Answer
read this FAQ: What 3D Object File Formats can Bryce Export?

you can export a various file formats for multiple uses (programming: dxf,3ds, x...)
> 0 votes

---
Tags: assets, asset-creation
---


# Question
Title: Is C# viable for a real-time game server?
Most of the question is in the title.

Basically, I'm starting to develop a 2D multiplayer action game. The client is (probably) going to be in XNA, and I thought I'd ask here about whether it's a good idea to use C# for server side development as well.

I guess the fact that the language is managed is not something problematic as Java is being used in even MMO game servers (correct me if I'm wrong), so are there any reasons to avoid C# for this purpose? I need it to be fast and responsive, to communicate over TCP, to chat with an SQL server. And if there is no reason to avoid C#, how would I deploy such a web server, would it be a .NET EXE running on the server machine?

# Answer
> 26 votes
Not only viable, but really good, in my experience. I've developed several MMO servers using C#, and I must say I never regretted the choice of language and platform.

There are lots of great libraries and tools for C# and .NET in general - network, logging, O/R mapping, etc. And, compared to Java C# is more expressive and less verbose (some people might argue about this, though..)

The GC "overhead" that scares some people is not really an issue, unless you happen to abuse it with billions of allocations per second. As an example, our current server allocates up to 50 mb/second under heavy load, and GC does not introduce any noticeable lag. We did have to use object pooling in strategic places, though - most importantly, objects representing network packets are pooled and not garbage-collected. Still, even with pooling turned off, GC is not the biggest problem.

As an example of how cool C# is, this is what we recently implemented. Our server runs several WCF services, that the game client uses for non-time-critical tasks, and we also use them for server administration. It turns out, it's very easy to make a WCF service to simply return our game objects to the caller. So we did just that, then made a little plugin to LINQPad that connects to our server - and now we can run queries like

```
from character in Service.GetOnlineCharacters()
where character.LocationManager.LocationId==5 && character.Attributes.Level<10
select new { character.Id, character.Nick }

```

On a live server, no less! I don't think you can do this with any other platform. Not in couple day's work, at least.

# Answer
> 27 votes
Sure, you can use C#.

One of the bigger issues to be aware of in terms of performance in C# or other .NET ecosystems is the GC -- the .NET framework provides several flavors of GC, including a "server" GC, that are worth learning about. Intelligently managing memory (for example, by pooling) is still a good technique even in a managed environment.

There are several robust APIs for interacting with SQL, communicating via TCP, et cetera in C#, either as part of the base framework or via third-parties, so you should have no trouble there.

You can utilize ASP.NET or similar if you really want your server to be web-based; if you just want to run a process and listen for TCP connections you can just deploy an .exe and the appropriate dependencies to the server machine, open up the appropriate ports, and run the .exe.

# Answer
> 5 votes
I think it's a great idea. The language is certainly capable of it, and especially if it's what you know, don't spend a bunch of time learning a new language just because it's "faster". The real bottleneck of your server will be network latency; an extra millisecond or two because you used C# instead of C++ won't make a difference.

# Answer
> 3 votes
If it's okay for you to deploy on Windows, I'd strongly recommend it, especially since your client is C#.

Don't underestimate game server development though. Even making a simple chat-only concurrent server is no trivial task, and you'll soon have lots of questions regarding concurrency, locking, performance, etc.

Just as a starting point, I'd like you to take a look at this page that broadly explains how to do concurrent socket programming in several platforms:

Link

If you're really serious about it, I'd recommend you thoroughly study Stevens' Unix Network Programming. It's focused on C sockets on Unix, but the principles are the same for every other platform, including .net.

Edit: This is another great resource, focused on scalability and performance for concurrent servers in .net. It's no longer available, but our friends at the wayback machine have a copy of it.

http://replay.waybackmachine.org/20080405220143/http://www.coversant.net/dotnetnuke/Coversant/Blogs/tabid/88/EntryID/10/Default.aspx

# Answer
> 1 votes
UPDATE (2020): The following paragraph is no longer true due to dotnet core/dotnet 5.

One 'disadvantage' would be that with C# if you want to use it on multiple platforms you have to be very careful to make sure that your code will work with mono. If all you care about is running it on a single platform and windows is that platform, then you should have no problems as others have mentioned.

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


title: "Time Control" in a 2d Platformer

text:
# Question
Title: "Time Control" in a 2d Platformer
I am making a 2d platformer where the player can press a button, and restart the level, only their previous character will also run the level at the same time, like they are traveling back in time.

I know other games have done this before, and the way I have thought of doing it is to make the game character have a set of actions (Idle, Jumping, Walking Left etc.) and then detect changes in those actions and log them into a list along with the game time. So then when I need the character to run the level again on its own, I can just go through the list changing its actions at the right time.

Is this the best way to do it? Does anyone have any experience in this?

Thanks.

# Answer
## EDIT:

Please see @Bluescrn's answer to this question; he elaborates on weaknesses in replaying controls rather than movement vectors or position.

--

You're on the right track. Here's the approach I'd use:

## Controllers

Create a Controller class which receives keyboard input and passes it on to your character. However, also have a Controller record exactly when the significant keys (e.g. arrows, jump, etc) were pressed and when they were released. It would store up this sort of information:

```
actions[0].milliseconds = 400     actions[0].action = right pressed
actions[1].milliseconds = 1000    actions[1].action = jump pressed
actions[2].milliseconds = 1300    actions[2].action = jump released
actions[3].milliseconds = 2500    actions[3].action = jump pressed
actions[4].milliseconds = 3000    actions[4].action = jump released
actions[5].milliseconds = 5330    actions[5].action = right released

```

A Controller has two modes:

1. Record: Receives keyboard input. Records input in the list. Hands the character input based on keyboard state.
2. Replay: Ignores keyboard input. Advances through the list according to milliseconds elapsed since the level began. Hands the character input based on the recorded keyboard state at the current moment.

## Characters

When your Character object is constructed, it creates a fresh Controller for itself. The Character can be in one of two modes at any time:

1. Active: There is only ever one active Character and it is the one you control. When the Character is in Active mode, its Controller is in Record mode. **By default** when a Character is constructed it is in Active mode.
2. Ghost: This is the one that replays your past actions. When a Character enters Ghost mode, it changes its appearance and sets its Controller to Replay mode.

## Levels

### A freshly started level

When you start the level, create a single Character. Now the level begins and the player does his thing.

### When time resets

When the level resets, do three things:

1. Tell the current Active Character to enter Ghost mode.
2. Create a new Character.
3. Call all Characters to Reset themselves. This will place them back at the starting position with no movement, etc. They will in turn tell their Controllers to reset to millisecond 0 with no keys pressed.

Then the level begins and the player does his thing.
> 8 votes

# Answer
If you are replaying recorded inputs, consider the implications of any moving/destructible/interactive objects in the world, which may have moved or changed state when the actions are replayed

Also, replaying inputs will not work precisely if your game uses a variable timestep. You may want to consider a fixed-timestep game update (with interpolation for variable framerate rendering)?
> 8 votes

# Answer
There are a lot of topics that cover game recording/replay systems/etc which should probably be the keystone of your past runthroughs.

Here's one: How to design a replay system
> 4 votes

# Answer
Recording the keyboard input might not be that useful in your case. You can however generate a spline with a timeline. You can even rewind time if your tricky with the forces that you need to apply
> 0 votes

---
Tags: 2d, architecture, time-travel
---


# Question
Title: Are any 3D design skills required for game development?
I am no graphics designer, but I'm a good developer with lots of experience. So, my question is the following:

Are any 3D design skills required for game development? If not, how does one write a game with 3D characters without having to design them?

# Answer
> 9 votes
Like with just about any skill, like math, the answer is no, it's not required, but it helps.

So how do you cope with it? You find someone who has the skills required to help you. Or design something that does not require said skills, like in this case, a 2d game.

# Answer
> 1 votes
You don't have to design your own characters as some characters already exists, you just have to find them, you can even substitute a character with boxes when your prototyping the gameplay until you find a partner.

However Level Design is a different beast altogether even if they are just boxes it can make or break the gameplay and are intrinsically linked to the game design.

---
Tags: career
---


title: How to monetize a free XNA game?

text:
# Question
Title: How to monetize a free XNA game?
I have written a windows based game in XNA. I wish to release it for free but I would also like to monetize it in some way. What are my options?

## Possible ways:

* Ads - what current libraries/services are available?
* Donations - PayPal, what else?
* MicroTransactions - what current libraries/services are available?

# Answer
* Paid for extensions/add ons.

I wouldn't necessarily buy these, but having these *might* be an option. It would depend on the game. You wouldn't want someone whose paid for an add on having a competitive advantage in an online game.

* Licensing for other developers to write extensions/add ons.

This would be a risky strategy though as if they didn't have a mechanism to recoup their outlay why would they develop anything for your game.
> 1 votes

# Answer
On WP7 a lot of developers are having the best results by using ads in their games, just show an add on loading screens (that's not too intrusive).
> 5 votes

---
Tags: xna, monetization
---


title: Using Tilemaps in C

text:
# Question
Title: Using Tilemaps in C
I have used tilemaps .TMX files using cocos2d and objective c.

How are tilemaps used in C? Are there libraries available or where is a good place to start for using tilemaps in C?

I would like to create a tilemap using a tool. if this is supported by a library in C and then read each tiles layer.

How is this done in C?

# Answer
> 2 votes
I've used "Tiled Map Editor" http://www.mapeditor.org/ for a iPhone game with good results. Our engine was made in house, but Tiled has his own format file that you can parse easily or you can append a custom format.

Tile supports layer, metaobjects to place the positions of objects in the game or anything else. It's multiplatform and free.

You provide an image with all tiles. Each tile is represented by a number. When you draw the map in the editor, the output is a matrix with the numbers that represents the tiles, with this identifiers you can put the tiles in your game in the correct order.

---
Tags: tiles, maps, c
---


# Question
Title: Theoretic question about rendering in sfml and in general
I have read whole tutorial section on sfml-dev.org and have some question.

What are exactly views and how to use them ?

Should I render things in views or in renderwindow ?

# Answer
Views in SFML, like it says in the docs, are like 2D cameras. Essentially it represents what you would see through a camera and allows you to zoom in or out and to scroll in any direction easily. Doing this with a RenderWindow would mean that in order to zoom in, you would need move/scale every sprite. Same thing for scrolling, you would need to move every sprite on screen depending on the scroll direction.

On the other hand I have used sfml once, to make a multiplayer 2D shooter. I didn't use views at all when doing all the rendering. Everything was drawn directly to the RenderWindow and I had no performance problems or anything else.
> 3 votes

---
Tags: c++, game-mechanics, sfml
---


# Question
Title: MMO techniques, algorithms and resources for keeping bandwidth low?
Are there any resources and documentation on how current MMOs handle the action and movement data from the compression to the handling on the client? Any resources for movement prediction algorithms?

I'm especially interested in those that have wsad movement and focus on keeping latency low Also what is the packet rate and size for different types of MMOs(network wise)?

Is there a way to scale the packet rate or outright disable some packets if the player can't reach or in the later case see them?

# Answer
> 9 votes
Well, there's this book -- which is a bit old now, and I've never really read it, but it's from a reputable publisher. I also found this one, which is newer, but I've never heard of before. Both claim to cover MMO (or at least online) game development issues; that said, client-side prediction is more or less the same regardless of the scale of your concurrent player base, and Google has plenty of information about it.

It's important to realize that from a practical perspective it's rather hard for an indie/hobby developer to put together a game that will be popular enough to even garner enough players to achieve a theoretical peak concurrency high enough to be considered "massive." But the techniques can still be educational to research.

There are two major classifications of things you can do:

* Be aggressive about sending only the minimal amount of data to the minimal set of clients that need it.
* Design a game that doesn't give players incentive to clump up too much, helping you keep the "set of clients that need" things small in general.

The second one is really a game design and social manipulation problem -- it's especially tricky because multiplayer games are naturally social, that's part of their appeal, so you don't want to discourage clusters of players too much. On the other hand, a game where everybody in the world is spawn-camping the one guy who drops the best loot in the game is going to be hard to scale.

For the first option you could consider doing tiered messaging -- there are some things about other players that are always important to know, such as positions. But other things, such as health, may not be as important for objects that the current player cannot see yet, so you gate what you send to that player based on the relative distance of all other entities in his vicinity -- this is essentially throttling the data you send, as you mentioned in the last bit of your question, as well as filtering it.

Very large scale multiplayer architectures will also buffer reports that don't need to have immediate action taken on them. Character save messages sent to the server can be done in deltas, with full updates only at critical points, and these updates can be buffered up on a throttling server so that they are send to the server that actually holds the character data in a steady, periodic fashion -- as your player base scales, you have to worry about optimizing disk IO as well as network traffic. You don't want to cause your character database to thrash.

The packet rate and size differs widely from game to game, just as it would for non-MMO games. It's really a very requirements-specific thing and there aren't generalized standards.

# Answer
> 5 votes
In addition to the above answer, read up on TCP\_NODELAY and how window scaling operates. Understanding the details of TCP (and yes, you want to use TCP not UDP unless the prospect of handling differential updates arriving out of order sounds fun to you) and retransmission is critical for latency control.

---
Tags: mmo, networking, scalability
---


title: Custom effects on Model in XNA

text:
# Question
Title: Custom effects on Model in XNA
If I have a Model that is drawn with a different effect occasionally, what is the typical approach to this?

Models have effects stored in each of their meshes, and you seem to be forced to use those.

Typically this is done:

```
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (Effect effect in mesh.Effects)
    {
        effect.Parameters["World"].SetValue(world);
        // Other stuff related to this specific effect is done here.
    }
    mesh.Draw();
}

```

I want to be able to do this:

```
foreach (ModelMesh mesh in model.Meshes)
{
    myEffect.CurrentTechnique.Passes[0].Apply();
    mesh.Draw(); // Mesh will be drawn with "myEffect".
}

```

What are our options?

# Answer
> 2 votes
Shawn Hargreaves outlines the two options for changing which effect is used when rendering a model on his blog here.

The first option is purely a run-time option: iterate over all of the model.MeshParts and directly modify the ModelMeshPart.Effect property to the new effect. I haven't tried this but I would expect it to work.

The second, and more flexible option, is to use your own custom ModelProcessor to modify the effect that is compiled into each model. If you take this approach you can write your own Effect which has several techniques, each with different shaders, Switching shaders at run-time is then just a matter of changing which technique each effect in the model will use.

```
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (Effect effect in mesh.Effects)
    {
        effect.CurrentTechnique = effect.Techniques["CreateShadowMap"];
        // Other stuff related to this specific effect is done here.
    }
    mesh.Draw();
}
...
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (Effect effect in mesh.Effects)
    {
        effect.CurrentTechnique = effect.Techniques["DrawWithShadowMap"];
        // Other stuff related to this specific effect is done here.
    }
    mesh.Draw();
}

```

---
Tags: xna, c#, xna-4.0, models, effects
---


# Question
Title: Loop through a loaded .x file's vertices
I need to compute the "gravity center" of a mesh, some kind of barycenter, and then find the farest vertices to compute a bounding sphere.

Here is what I have for the moment:

```
D3DXVECTOR3 result(0,0,0);
int num = mesh -> GetNumVertices();
LPDIRECT3DVERTEXBUFFER9 vertexBuffer;
mesh -> GetVertexBuffer((*vertexBuffer));
void* rawData;
vertexBuffer -> Lock(0, mesh->GetNumBytesPerVertex() * mesh->GetNumVertices(), &rawData, D3DLOCK_READONLY);
D3DVERTEXELEMENT9 decl;//[MAXD3DDECLLENGTH];
UINT numElements;
mesh -> GetDeclaration();
mesh -> GetFVF();

```

Apparently I need to cast the rawdata pointer, but I don't know what to do next...

# Answer
> 1 votes
*Are you asking how to compute the "center" or how to get the points with which to do so? I'll assume -- and answer for -- the latter:*

Once you have the buffer pointer itself, and information about the format of the vertices within and the number of vertices (it appears from your code snippet that you have all of this already), you use the format information to determine where the positional data is for each vertex.

In general this involves iterating the elements of the vertex declaration, updating a byte offset until you reach the element representing the position. However in practice, the position is almost always at offset 0 from the start of a vertex so you may not need to be so pedantic.

Once you have that offset, initialize a cursor pointer to (start of buffer + that offset) and read the next few bytes of data, which will be either XYZ or XYZW floating point values, depending on the format of your buffer. Then increment the cursor pointer by the number of bytes in each vertex (including stride, if it exists) to get to the positional data for the *next* vertex. Repeat until you've read all the positional data.

You can save off all this positional data into a container (like a `std::vector`) and process it after the fact, or you can run your algorithm as you do the extraction, if appropriate.

---
Tags: directx
---


title: Associating materials and primitive

text:
# Question
Title: Associating materials and primitive
I'm trying to find a way of setting any kind of material class on any kind of primitive class (all the material classes have a base material class, same goes for the primitive classes).

What I mean by that, is, I'm looking for a way to do something like this:

```
Cube a = Cube( ColorMaterial( COLOR_RED ) );
Cube b = Cube( TexturedMaterial( ambienTex, diffuseTex, specularTex ) );

```

Ok, so that looks pretty easy, but I've got a few problems. First of all, inside my Cube class I've got a function in which I build the cube's geometry, as such:

```
VertexPositionColor vertices[36] =  { VertexPositionColor( pos, color ), ... }

```

Because of this, I can't just pass any type of material to my primitive class, because that would mean that the function that builds the geometry would need to be able to change the type of vertex it uses. I can't use templates either, because, even though it would solve the type issue, different vertex types are not constructed the same way.

So, is there any way of associating a material to a primitive?

# Answer
The first problem I see here is that you have a "cube" class. You really shouldn't -- within the domain of a rendering system, what about a cube is different from a sphere, in terms of type or interface? Since rendering interfaces should not be responsible for non-rendering task (such as collision, et cetera) then the answer is really that there's *nothing* different.

On the whole, the only difference between a cube and a sphere is the data (the actual vertex elements), which can be abstracted. Instead of `Cube`, you should have a `Geometry` class. This class would contains two important pieces of data:

* A list (more accurately, an array or vector) of vertices.
* Information describing the format of an individual vertex.

The vertex format can be as simple or complex as you need -- you can simply decide to pre-define a set of vertex formats your game will use ({position, color}; {position, color, normal, texture coordinates}; et cetera) and represent the format as enumerated type. At the other end of the spectrum you can implement a free-form `VertexFormat` object that allows specification of arbitrary vertex element semantics at arbitrary byte offsets within a vertex.

The actual vertex data should be represented as an `unsigned char*` and you can cast to an appropriate vertex format structure if needed, based on the vertex format enumeration. This allows you to store any shape/mesh in any vertex format without having to create subclasses -- having to create those subclasses is actually a design and maintainability problem.

Once you have this in place, it should be pretty straightforward to then add a `Material*` to the `Geometry` class. If you give the `Material` class a vertex format as well, you can even enforce correct bindings between materials and geometry: you can raise errors when you try to assign a material whose shader requires {position, color, normal} to a geometry object that only has {position, color} for example.

This also allows you to externalize data definitions and thus make your APIs more data-driven. You can now construct `Geometry` objects with arbitrary collections of vertices. In terms of that API you can then implement another interface (it should be separate from `Geometry`) that loads vertex lists from a data file format of your choice, or an interface that generates a list of vertices that form a cube, or sphere, or whatever other procedural primitive you'd like, with whatever vertex properties you desire.

EDIT: A clarification on some ways you can handle vertex formats: The `Geometry` object should accept and store only raw, untyped bytes of vertex data. You can work directly with these raw bytes, although I do understand the appeal of having a 'vertex structure' type that represents an individual vertex for ease of manipulation. In order to be useful that type must perforce be a POD (or you couldn't send arrays of them to the GPU anyhow), and so it is sane to be casting between the raw bytes and the vertex structure, provided the data in the bytes does actually match up to the structure's schema. You could thus provide an interface to the vertex data in the geometry object like:

```
template< typename VERTEX_STRUCTURE >
VERTEX_STRUCTURE* GetVertexData() {
  // Assume 'vertices' is an unsigned char* instance member.
  return reinterpret_cast<VERTEX_STRUCTURE*>(vertices);
}

```

You still need to know the appropriate format at compile time when you call this method, but that's usually not a problem because you are going to be directly manipulating the individual properties of the vertices when you call this (usually) so you'll know anyhow.

But if that's still a problem you can even manipulate the raw bytes directly according to the vertex format at runtime. Assuming you have a series of memory IO routines that allow you to write arbitrary primitive types (ints, floats, et cetera) into arbitrary byte buffers, and you have something that can query a vertex format object for information about whether or not that format contains normals or colors or whatever, you could write to an arbitrary format buffer like this:

```
unsigned char* buffer = /* get raw buffer from Geometry object */
VertexFormat format = /* get format description from Geometry object */

// WriteToBuffer() writes the provided value, advances the buffer pointer
// by an appropriate size and returns that updated pointer, allowing for us
// to do sequential writes. It's a relatively easy thing to implement.
buffer = WriteToBuffer(buffer, x);
buffer = WriteToBuffer(buffer, y);
buffer = WriteToBuffer(buffer, z);

if(format.HasNormals()) {
  buffer = WriteToBuffer(buffer, normal.x);
  buffer = WriteToBuffer(buffer, normal.y);
  buffer = WriteToBuffer(buffer, normal.z);
}

if(format.HasColor()) {
  buffer = WriteToBuffer(buffer, color);
}

// Et cetera.

```

This latter technique would be useful in code that generated a vertex buffer for a sphere procedurally, for example: you could pass that code information about what types of vertex properties you wanted your generated sphere to include, and generate them at runtime.
> 3 votes

---
Tags: architecture, graphics-programming
---


# Question
Title: Required Security Precautions for Flash / AS3 Multiplayer Game
I have created a couple of games in Flash/AS3 and am playing with programming a flash-based multiplayer (possibly mmo?) game where the application will communicate with a server over a socket connection.

Obviously I need some form of authentication (username and password) but what other security precautions do I need to explore to prevent cheating?

# Answer
a big one for flash dev is to never compile any secret into the source, because a decompiler can pull it out pretty easily. so any authentication that you need to do should be session based, and not hard coded into the game.

other than that it's pretty much the same as web site security, use a session, only send a passphrase over https, etc.
> 3 votes

# Answer
Your main priority should be assuming the client talking to your server isn't your flash code, but a program written specifically to try and break the server. Fuzzing is a common technique to try and find this sort of issue.

There's also the possibility of a client that instead of trying to break the server it will try to let a real player cheat or automate gameplay completely. This is significantly more complicated to detect and prevent.
> 2 votes

# Answer
Verify all user input on the server and make sure that it is legal. There are a lot of similar questions if you just search on here for cheating.
> 0 votes

---
Tags: flash, actionscript-3, multiplayer, security, websocket
---


# Question
Title: Is it possible to program the entire logic and flow of a game without ever touching a graphic's engine?
I'm not interested in rendering engines or level design, but I'm very interested in programming the AI that drives all of the characteristics of game play. I'm thinking of how the d20 system drives the rules behind D&D games. Is there a person that programs that logic, and is it possible to program almost all of an API without ever touching a graphic's engine? I'm a software engineer by trade (Java with some C# experience), so I'm looking to use those programming skills.

# Answer
> 8 votes
## Yes

It is possible to program games without touching a graphics or rendering engine. But it will limit you to text based games. Some good examples of these games would be nethack, dwarf fortress, and online MUDS(multi-user-dungeons).

If you want to make a game with graphics, I suggest you join a team where you can program logic and AI without having to know to much about graphics.

# Answer
> 3 votes
Yes,

a game engine is made of lots subsystems. Graphics Engine, AI Engine, the input system, the sound system, a game editor and many more.

A game is composed by a game engine ( and for small games it's not a need ) and much content: textures, levels, 3d models, sounds, and GAME LOGIC, yes, the game logic is a content.

You can made a game without a engine, or with a engine with only two or three subsystems. A game without graphics, only on text mode. On a great company, small groups are dedicated only a part of the game. ( AI scripting, lighting, network, etc..)

# Answer
> 3 votes
Are you interested in creating a **new** game, or just trying to implement various AI techniques? In the second case, there are many video games that offer APIs to interact with the game. For example, you could create a bot for StarCraft using BWAPI.

# Answer
> 3 votes
> Is there a person that programs that logic, and is it possible to program almost all of an API without ever touching a graphic's engine? I'm a software engineer by trade (Java with some C# experience), so I'm looking to use those programming skills.

Definitely. Gameplay programmers often never touch actual rendering code. We're a few layers separated (dealing with actors and controllers and such). That being said, as a gameplay programmer on triple-A FPS's, I found myself frequently working with animation code.

And, you still have to know your math and, depending on the platform, understand what's happening under the covers with the decisions you make.

Your mileage will vary depending on the technology and company; but, generally, you're talking about gameplay or AI programming.

# Answer
> 1 votes
Yes, I think you can. Although you should know that usually the AI system communicates with the animation system to manage character movement and actions.

It really depends on the game you're going to implement.

# Answer
> 0 votes
It is possible.

Microsoft recently released Kodu.

You should watch the series of videos made on Kodu.

# Answer
> 0 votes
IF you have a good game engine available you don't have to focus on the graphics part and let the engine handle it.

# Answer
> 0 votes
I think the great thing about this approach, which I have done myself, is that you are free to reuse your "rules engine" after you complete it.

This gave me a chance to apply it to many different engines/renderers. I just layer the UI on top and can easily create (almost) completely different games. I could make one a 2d sidescroller using sprites, another a 3d dungeon, another a isometric rotating map.

---
Tags: software-engineering, ai
---


title: Cocos2d+pybox2d vs Cocos2d-Iphone

text:
# Question
Title: Cocos2d+pybox2d vs Cocos2d-Iphone
Myself and two colleagues are working on making our first indie game for PC and, we decided to use Cocos2D + PyBox2D. We decided this based on what we've seen of Cocos2D-iPhone games, but I'm not sure if Cocos2D-iPhone is just a port of the Python version with a few more features, or if it's far more advanced than the Python version.

I just want to be sure that I'm on the right track. (We also want to port our game to Android and iPhone if it is successful on the PC.)

Note: For the maps we will use Tiled , which is compatible with Cocos2D (both iPhone and Python versions, I think.)

# Answer
> 2 votes
Hey there, I think that Cocos2d-iPhone is far more advanced and full-featured than Cocos2D-Python. Some design decisions are the same, like using a SceneGraph, and they share some class names, but I would bet that Cocos2d-iPhone has far more work behind it than Cocos2D-Python. I would perhaps recommend that you use cocos2d-x. It is a C++ port of Cocos2D, which has cross-platform support as its main feature.

---
Tags: cocos2d-iphone, box2d, python, cocos2d, tiles
---


title: Creating a checker board in C# winform

text:
# Question
Title: Creating a checker board in C# winform
I am using the PictureBox class to create a checkerboard, and it not really working all that well. I've created the loop:

```
PictureBox[,] squares = new PictureBox[10,10];
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                squares[i, j] = new PictureBox();
                squares[i,j].Image = Chess.Properties.Resources.square;
                squares[i, j].BackColor = Color.Transparent;
            }
        }

        for (int i = 0; i < 10; i++)
        {
            for(int j = 0; j < 10; j++)
            {
                squares[i, j].Location = new Point(i * 30, j * 30);
                this.Controls.Add(squares[i, j]);
            }
        }

```

It's supposed to create a 10x10 grid, and I added the image into the application resources. Each square is 20x20 pixels, and I loop by column. I thought it would work, but all I get is 6 images and the size just gets smaller.

Am I missing something? Or any good alternatives in creating a checkerboard without using PictureBox? Any thing with a MouseLeave, MouseHover, MouseClick, events I can use.

# Answer
If you're just doing basic drawing, you can create a single control (perhaps a UserControl subclass) and override the `OnPaint()` method. See http://www.geekpedia.com/tutorial50\_Drawing-with-Csharp.html for a sample tutorial. You'll also be able to override the various methods pertinent for mouse-handling.
> 1 votes

---
Tags: c#, gui
---


# Question
Title: Importing python DirectX into c++ DirectX program
I'm not asking for code or anything, just some advice on what to google, because I have no idea what to call this process.

I made a video player (with full controls) with python and DirectX and would like to just simply import the rendering of the display into a c++ DirectX fullscreen app. That way, it can be customizable to the user. Any advice is greatly appreciated.

# Answer
You need some kind of Python-C++ bindings.

There's a few options:
> 1 votes

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


# Question
Title: Quad trees/grid based collision - putting logic into action
First of all, I've only been writing my own game logic for a short while, so I apologize if this might seem straight forward.

I've been reading a lot about quad trees and grid based collision detection. I understand the logic - basically don't check for collision unless objects are near basically. But it never is mentioned how the actually execute this.

I have a couple of possibile methods in my head but am not sure which is best

**General collision test - no optimisation**

```
for(var i:int = 0; i < objects.length; i++){
        //find object A
        var objectA = objects[i];

        for(var j:int = i + 1; j < objects.length; j++){
            //find object B
            var objectB = objects[j];

            if(objectA.collidesWith(objectB){

               //handle collision logic
              }
        }

```

**store neighbours (method 1)** But what if we want to optimise the collisions to only check objects that are near. Do we still run through all the objects, or do we create an array with near objects to check through?

```
var objects:Array = new Array();
    var neighbours:Array = new Array();

    for(var i:int = 0; i < objects.length; i++){
        //find object A
        var objectA = objects[i];

        for(var j:int = i + 1; j < objects.length; j++){
            //find object B
            var objectB = objects[j];

            if(objectA.isNear(objectB){

               neighbours.push(objectA, objectB);
              }
        }

    }

    //somewhere else
    for(i:int = 0; i < neighbours.length; i++){
        //only check neighbours

        for(j:int = i + 1; j < neighbours.length; j++){

            if(objectA.collidesWith(objectB){

               //handle collision logic
              }
        }
    }

```

**loop all objects but only check neighbours for collision (method 3)** The other possibillity is that we still loop through everything but check if the objects are near before testing the collision.

```
for(var i:int = 0; i < objects.length; i++){
        //find object A
        var objectA = objects[i];

        for(var j:int = i + 1; j < objects.length; j++){
            //find object B
            var objectB = objects[j];

            if(objectA.isNear(objectB){
               //they are near - check collision!
               if(objectA.collidesWith(objectB){

               //handle collision logic
              }
            }
        }

    }

```

**Store objects in tile data (method 3)** Using a tile based sytem allow for another option; Store the objects that are on a specific tile in the tile data itself. Check to see on which tile the object is the surrounding tiles contain any objects it could collide with:

```
var ObjectA;

for(var i:int = 0; i < 4; i ++){
//check 4 surrounding tiles from object A

   if(Object.currentTile + surroundingTile[i] CONTAINS collidable object){
   //check collision!
    if(objectA.collidesWith(surroundingTile.object){

    //handle collision logic
     }

}
}

```

I always try to look at the real world as an example. If I wanted to compare items with the same colour it would seem illogical to check every entire item even if they don't match colour (Method 2, check each item). I would probably collect the items with the same colour (objects that are near each other) and check those (method 1), instead of checking everything.

This isn't an appropiate comparison since the items in collision checking are constantly moving so the order gets mixed up. That whats confusing me.

***Would it be more efficient to check each item, thus removing the strain of keep generating an array of neighbours.***

***Or is it more efficient to find neighbours thus not having to loop through so many objects to check the collision?***

***Keep changing the data on each tile seems very intensive aswell, so i'm not sure if that a good idea..***

I've been thinking of a tower defense game where the tower needs to detect objects if objects are in range before it shoots at it. And it just seems silly to check all items while at some times there won't be any objects near at all.

I apologize for the long post, always having trouble explaining myself!

# Answer
You need to reduce the count of actual collision checks. Yeah obvious I know. So lets elaborate on this:

Your first collision check algorithm without any optimization: how many checks will it do in one run? If n is the count of objects, this will be around n\*(n-1) checks. For a lot of objects (\>100) this will be horribly slow.

Your neighbor checking method will not be much faster. If your objects aren't static and move around a lot, you will need to build these neighbors list for each object everytime in your game loop. This is actually worse than the first algorithm since you're doing n\*(n-1) to build the neighbour list and then check for each object if it collides with one of its neighbours.

You need to partition your game space. Lets say your game space is 400x400 pixels wide. Your can partition this into 4 sub-space each 200x200 in size and check for each object into which of the sub-spaces it belongs (one object can be inside more than one sub-space). Then you will only need to check if the objects in each subspace collides with other object in the same sub-space.

So the runtime cost will be: n for building the 4 sub-space list + (n/4)\*((n-1)/4) which is a lot better than the previous runtime cost. This can be cut down further by making the sub-spaces smaller (e.g. 50x50).

So our algorithm now looks something like this:

```
for each (object in objects)
  check into which subspace the object belongs

for each (subspace in subspaces)
  for each (object in subspace)
    check object for collision with other objects in same subspace

```

This is somewhat similar to your tile data idea. But the subspaces do not need to be the same size as the tiles.

We can do one last step to optimize this further using a quadtree. Let k be the count of subspaces. To build the spaces object lists we are doing k\*n checks, leading to a lot of checks if your game world gets large.

To cut this cost down we use a quadtree. A quadtree is another way to partition our game space. Instead of dividing our 400x400 space into 64 50x50 subspaces and checking for each object in which of the 64 subspaces it currently is, the game space is divide into 4 subspaces half the size of the game space (200x200), which in turn are divide into smaller subspaces (100x100), which in turn are divided again into 50x50 subspaces. This is our quadtree.

Now if we want to know into which 50x50 subspace an object belongs we check into which of the 200x200 subspaces it belongs. Then we go one level deeper in our quadtree and check against the 4 100x100 subspaces which are inside the 200x200 subspace we just found. This is repeated until we know into which 50x50 subspace the object belongs. So how many checks were now necessary? 4 for each level of the the quadtree (Remember an object can be on the edge of two subspaces). So we need 4\*3 checks to assign an object to the correct 50x50 subspace. A lot better than 64 checks.

So our quadtree algorithm needs 4\*3\*n checks to build the subspace lists and then something like k\*(n/k) checks to check the collisions of each object.
> 8 votes

---
Tags: collision-detection, efficiency, quadtree
---


# Question
Title: How do I create a sky box with OpenGL ES 2.0?
Can you give me hint to any good sky box example in OpenGL ES 2.0? I have found only OpenGL and does not work for me. I am doing it this way: Initialization:

```
glUseProgram(m_programSkyBox.Program);
glGenBuffers(1, &skyBoxVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, skyBoxVertexBuffer);

float vertices[24] = {
    -1.0, -1.0,  1.0,
    1.0, -1.0,  1.0,
    -1.0,  1.0,  1.0,
    1.0,  1.0,  1.0,
    -1.0, -1.0, -1.0,
    1.0, -1.0, -1.0,
    -1.0,  1.0, -1.0,
    1.0,  1.0, -1.0,
};

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glGenBuffers(1, &skyBoxIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyBoxIndexBuffer);

GLubyte indices[14] = {0, 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1};
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

```

Drawing the skybox:

```
glClearColor(0.5f, 0.5f, 0.5f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(m_programSkyBox.Program);

glDisable(GL_DEPTH_TEST);   // skybox should be drawn behind anything else
glBindTexture(GL_TEXTURE_CUBE_MAP, m_textures.Cubemap);

glBindBuffer(GL_ARRAY_BUFFER, skyBoxVertexBuffer);
glVertexAttribPointer(m_programSkyBox.Attributes.Position, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(m_programSkyBox.Attributes.Position);
glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyBoxIndexBuffer);
glDrawElements(GL_TRIANGLE_STRIP, 14, GL_UNSIGNED_BYTE, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnable(GL_DEPTH_TEST);

```

Texture loading is working. Shader is correctly compiled and looks like this: Vertex shader:

```
attribute vec4 position;
varying mediump vec3 texCoord;
void main() {
   texCoord.xyz = position.xyz;
}

```

Fragment shader:

```
uniform samplerCube Sampler;

varying mediump vec3 texCoord;

 void main() {
     mediump vec3 cube = vec3(textureCube(Sampler, texCoord.xyz));
     gl_FragColor = vec4(cube, 1.0);
 }

```

But I can't get the cube visible. Am I doing anything wrong?

# Answer
> 0 votes
My fault, I have found the problem. I have not "create" vertex in vertex shader. It should looks this way:

```
uniform mat4 projectionMatrix;
attribute vec4 position;
varying mediump vec4 texCoord;
void main() {
   texCoord = projectionMatrix * position;
    gl_Position = texCoord;
}

```

I have added line:

```
gl_Position = texCoord;

```

# Answer
> 4 votes
You propably want to send View matrix (which defines camera position), because why to have skybox if you can't look around? And propably also world matrix to add some scale. Personally i like using vertex position as texture coordinate if you know what you are doing. This is how it should look:

```
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
attribute vec4 position;
varying mediump vec4 texCoord;
void main() {
   texCoord = position;
   gl_Position = modelViewMatrix * projectionMatrix * position;
}

```

`gl_Position` should contain 3D position converted to the 2D screen space. Thats what modelViewProjection does. And `texCoord` should be texture position on a vertex, which usualy does not changes with vertex's position on a screen, so no multiplication with any matrices. (Maybe there are some cases when it has sense to multiply texture coord with projection matrix, but sky box is definitevely not one of them).

---
Tags: iphone, opengl-es, textures, shaders, cubemap
---


# Question
Title: Optimising the modelview transformation in GLSL for 2D
So, the standard way to transform vertices and then pass to the fragment shader in GLSL is something like this:

```
uniform mat4 u_modelview;
attribute vec4 a_position;

void main() {
    gl_Position = u_modelview * a_position;
}

```

However, I am working in 2D so there is redundancy in the 4x4 matrix. Would it be more efficient for me to do this?

```
uniform mat3 u_modelview;
attribute vec3 a_position;

void main() {
    gl_Position = vec4(u_modelview * a_position, 1.0);
}

```

gl\_Position requires a 4 component vector so an extra operation is required at output. However the matrix multiplication is for 9 elements instead of 16. Can I do any better?

# Answer
> 6 votes
This is correct way how to save few bits. As it is correct it is also little bit useless. GPU is highly optimized for 3D algebra and can do matrix-vector multiplication pretty fast. Same fast in 2D or 3D. This would be slightly faster on CPU, but not on GPU.

But it is ok and smart also. Just try to keep your eye on real problems like correct memory usage (textures, vertex buffers) and algorithms. Not on "micro optimizations".

And no, you can't make it better.

# Answer
> 6 votes
The GPU in an Xbox 360 is 240 billion flops, and it's a joke compared to modern desktop GPUs. You're not going to make any significant difference at all by spending 7 less flops in a shader. This is especially true if the GPU implements SIMD for 4 floats, which it almost certainly will because 4x4 matrices are by far and away the most common, which would make it nothing. This is not the right place to be spending time looking for optimizations.

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


# Question
Title: Cross-browser cross-platform web support for immersive/non-casual games
I have heard of many plugins/browser technologies that are useful for games, but I didn't dive into any of them yet because I've assumed that omni-support wasn't quite there. By omni-support, I mean all browsers and all OSs.

Since we've recently had many new game-specific plugins pop up (e.g. Unity), new web standards pop up (e.g. WebGL), and existing standards gain better support in IE (e.g. SVG), I'm wondering if this has changed.

There are three fundamental requirements I see to making immersive games:

* Solid mid-to-low level video/audio support (2D and 3D are both interesting)
* Mouse capture
* Full screen

Are there technologies out there that support all three of these, that are cross-platform and cross-browser (including all the big browsers)?

Standardized solutions are preferrable, but plugin-based solutions are okay, as long as they support free or very cheap development.

**Edit**

I realize I posed my question as "are there any such technologies". I'm actually interested in all such technologies. If there is only one, it may still be useful to list other technologies, what they lack, and when they might get there.

# Answer
> 2 votes
Unity is still your best bet. It works in Chrome/IE/Firefox/Safari and on Mac and PC. They're playing around with a linux port, but I wouldn't expect to see that be live for quite some time.

Unfortunately the so-called open standards just aren't there yet in terms of implementation.

Pretty soon Adobe Molehill will be a lot more pervasive if you're looking for 3D rendering in a browser. If you're just looking for sheer install base, this will be the most applicable. Then again, Unity is working on exporting to that platform as well.

Unity does a pretty good job of supporting all sorts of old video cards (even pre-DX7 hardware), it has 3D audio, and of course it can go fullscreen. I don't know what specifically you mean by "mouse capture" but you can do FPS style controls with it.

---
Tags: browser-based-games, hardware-acceleration
---


# Question
Title: Is there a simple C++/.NET game with scripting?
I would like to play around with games that use scripting to see how much easier it makes development. What --simple-- C++ or .NET game may i download and play with using a scripting language. I dont really care which scripting language it is.

# Answer
> 1 votes
Lots of games use scripting which allows for not only modding but the creation of completely different games.

Your welcome to purchase Puzzle Quest 2 (or any Infinite Interactive game) and see just how easy it is to script with Lua. Pretty much everything you can do is already in there in the existing scripts.

# Answer
> 1 votes
Even though it's not directly what you were asking for, there already is a question regarding games that utilize scripting. Some of them might be options for you as well, notably LÖVE (Engine)

Game engine with good Lua entity creation/management

---
Tags: scripting
---