title: 3D primitive rendering library

text:
# Question
Title: 3D primitive rendering library
I am looking for a library which would easily allow me to render shapes (cubes, spheres, lines, circles, etc.) in 3D3 and OpenGL if possible. I want to be able to rapidly design visual debugging tools and I am not proefficient enough in graphics rendering to do it myself (writing the low level stuff that is). The library would have to be for C/C++.

I've already taken a look at the open-source 3d engine, but I feel those are too big for what I really need.

Do any of you know if such library exist? If so, links would be appreciated!

# Answer
**OpenGL** and **freeglut** will do what you're looking for. Freeglut can create the spheres, cubes, cylinder, cone, donuts, teapots, etc.

> GLUT (and hence freeglut) allows the user to create and manage windows containing OpenGL contexts on a wide range of platforms and also read the mouse, keyboard and joystick functions.

**http://freeglut.sourceforge.net/**
> 6 votes

# Answer
You can also use SFML.

There are differences between them. With FreeGLUT you can control OGL context, window properties, single/double buffering, multi-sampling etc.

SFML is more object-oriented. You can set FPS with it, it offers you multi-threading, image loading, etc. It sets window itself (it always uses RGBA, double-buffering, depth buffer etc.) - you cann't change it, but it's all you need (you don't need to change it in most cases).
> 1 votes

---
Tags: c++, opengl, directx, c, directx9
---


# Question
Title: Code Structure / Level Design: Plants vs Zombies game level dissection
I am interested in learning the class structure of Plants vs Zombies, particularly level design; for those who haven't played it - this video contains nice play-through: http://www.youtube.com/watch?v=89DfdOIJ4xw.

How would I go ahead and design the code, mostly structure & classes, which allows for maximum flexibility & clean development? I am familiar with data driven design concepts, and would use events to handle most of dynamic behavior.

Dissection at macro level:

* (Once every Level) Load tilemap, props, etc -- basically build the map
* (Once every Level) Camera Movement - might consider it as short cut-scene
* (Once every Level) Show Enemies you'll face during present level
* (Once every Level) Unit Selection Window/Panel - selection of defensive plants
* (Once every Level) Camera Movement - might consider it as short cut-scene
* (Once every Level) HUD Creation - based on unit selection
* (Level Loop) Enemy creation - based on types of zombies allowed
* (Level Loop) Sun/Resource generation
* (Level Loop) Show messages like 'huge wave of zombies coming', 'final wave'
* (Level Loop) Other unique events - Spawn gifts, money, tombstones, etc
* (Once every Level) Unlock new plant

Potential game scripts:

a) Level definitions: Level\_1\_1.xml, Level\_1\_2.xml, etc.

**Level\_1\_1.xml :: Sample script**

```
<map>
   <tilemap>tilemapFrontLawn</tilemap>
   <SpawnPoints> tiles where particular type of zombies (land vs water) may spawn</spawnPoints>
   <props> position, entity array -- lawnmower, </props>
</map>

<zombies>
   <... list of zombies who gonna attack by ids...>
</zombies>

<plants>
   <... list by plants which are available for defense by ids...>
</plants>

<progression>
   <ZombieWave name='first wave' spawnScript='zombieLightWave.lua' unlock='null'>
      <startMessages time=1.5>Ready</startMessages>
      <endMessages time=1.5>Huge wave of zombies incoming</endMessages>
   </ZombieWave>
</progression>

```

b) Entities definitions: .xmls containing zombies, plants, sun, lawnmower, coins, etc description.

Potential classes:

```
//LevelManager - Based on the level under play, it will load level script. Few of the //               functions it may have:
class LevelManager
{
 public:
   bool load(string levelFileName);
   bool enter();
   bool update(float deltatime);
   bool exit();

 private:
   LevelData* mLevelData;
}

// LevelData - Contains the details of level loaded by LevelManager.
class LevelData
{
   private:
      string file;

      // array of camera,dialog,attackwaves, etc in active level
      LevelCutSceneCamera** mArrayCutSceneCamera;
      LevelCutSceneDialog** mArrayCutSceneDialog;
      LevelAttackWave** mArrayAttackWave;

        ....
      // which camera,dialog,attackwave is active in level
      uint mCursorCutSceneCamera;
      uint mCursorCutSceneDialog;
      uint mCursorAttackWave;

   public:
      // based on cursor, get the next camera,dialog,attackwave,etc in active level
      // return false/true based on failure/success
      bool nextCutSceneCamera(LevelCutSceneCamera**);
      bool nextCutSceneDialog(LevelCutSceneDialog**);
}

// LevelUnderPlay- LevelManager
class LevelUnderPlay
{
   private:
      LevelCutSceneCamera* mCutSceneCamera;
      LevelCutSceneDialog* mCutSceneDialog;
      LevelAttackWave* mAttackWave;
      Entities** mSelectedPlants;
      Entities** mAllowedZombies;

      bool isCutSceneCameraActive;

   public:
      bool enter();
      bool update(float deltatime);
      bool exit();
}

```

I am totally confused.. :(

Does it make sense of using class composition (have flat class hierarchy) for managing levels.

Is it a good idea to just add/remove/update sprites (or any drawable stuff) to current scene from LevelManager or LevelUnderPlay?

If I want to make non-linear level design, how should I go ahead? Perhaps I would need a LevelProgression class, which would decide what to do based on decision tree.

Any suggestions would be appreciated very much.

Thank for your time,

lalan

# Answer
> 2 votes
This is a *very* open-ended question and you'd be better off asking one clear top-level question and then following it up with several more focused detail questions afterwards. But I'll try and sum things up.

> How would I go ahead and design the code, mostly structure & classes, which allows for maximum flexibility & clean development?

There isn't One True Way to write code. People can give you their opinions here but they will differ significantly. If you're not familiar with coding yet, then you need to start with smaller projects than this. If you are familiar with coding in other contexts, then whatever rules for good development you used before will still apply here.

> Potential game scripts:

Note - typically a 'script' in game development refers to code written in a programming language, to perform some sort of logic. What you were describing are actually just data files.

> Does it make sense of using class composition (have flat class hierarchy) for managing levels.

If you like. Or have a hierarchy. It makes no difference to the outcome, only to what you have to go through to make it. Great games have been written using both methods. You shouldn't be considering a component based system unless you know you need components though. The program structure should follow the requirements of the game.

> If I want to make non-linear level design, how should I go ahead?

You have to define what you mean by "non-linear level design" first.

The problem with most of this is not that it's confusing, but that you don't have clear specifications. Once you have clear specifications, it becomes clear what code you need. Once you know what code you need, it's obvious where most of it has to go, especially if you're familiar with good coding practices and typical design patterns.

All your other questions are really just asking for opinions which will vary from person to person and nobody can give you the right answer, especially not without seeing which classes you have and what they all do - but if you had a list of classes, you would probably know what to do in the first place.

For all these decisions - just pick one, and code it. If you find yourself wishing you'd done it the other way, refactor it later.

---
Tags: level-design, component-based, data-structure
---


# Question
Title: How to choose a success and failure sound
I create a math game where the user has to solve an equation. If the user is right, the application plays sound A. If he's wrong, it plays sound B.

What criteria should I use to choose sounds for A and B?

# Answer
Good sounds are generally higher pitched and more crisp than bad sounds.
> 11 votes

# Answer
It depends on the tone of your game.

If it is humoristic, you can probably go with a 'ta-daaaa!' trumpet sound for correct answers, and a 'sad trumpet' (wa-waa-waaa-waaaa) sound for incorrect answers.

If the tone is more 'abstract', then a correct sound should have its pitch "going up" (like the Super Mario Coin sound), while an incorrect sound should have its pitch "going down".

You can also go "the Street fighter way" and have the program say the equivalent of "You Win!" and "You Loose!" in plain English.

Profesor Layton's series, for example, have their main characters tell you "That answer is spot on!" or "Mmm... that doesn't look too right..." (they still have trumpets and whatnot on the background)

Another important thing is duration: sounds derived from clicking a button should be short, specially if the user is supposed to answer lots of questions quickly. Sounds emitted after resolving a 5-minutes problem can be a little longer.
> 11 votes

# Answer
Not that I have a direct answer for you, but you might browse Freesound.org for good sounds. You can tag search for "success" and "failure" (or other suggested keyword around here like "crisp") to find sounds people have associated with those. Listening to a lot of samples should give you a better feel for what you want.
> 6 votes

# Answer
Absence of sound also counts. Rather than having a negatively-toned failure sound you could play no sound if the answer is wrong, and in doing so come off as less harsh on the user who may be struggling with the subject matter.

Reward them with a pleasant noise (not too loud or sharp) and give them empty air when they miss something. Antagonizing a math test taker is not likely to help them improve much. (in my opinion)

Another good place for examples of positive / negative user feedback sounds can be found by auditioning the system sound sets in a typical Windows installation. There are some great examples of the sonic motion alluded to by other answers in this thread. (just don't use them for anything other than reference of course.)

-j
> 1 votes

---
Tags: audio
---


# Question
Title: How to implement behavior in a component-based game architecture?
I am starting to implement player and enemy AI in a game, but I am confused about how to best implement this in a component-based game architecture.

Say I have a following player character that can be stationary, running and swinging a sword. A player can transit to the swing sword state from both the stationary and running state, but then the swing must be completed before the player can resume standing or running around. During the swing, the player cannot walk around.

As I see it, I have two implementation approaches:

* Create a single AI-component containing all player logic (either decoupled from the actual component or embedded as a PlayerAIComponent). I can easily how to enforce the state restrictions without creating coupling between individual components making up the player entity. However, the AI-component cannot be broken up. If I have, for example, an enemy that can only stand and walk around or only walks around and occasionally swing a sword, I have to create new AI-components.
* Break the behavior up in components, each identifying a specific state. I then get a StandComponent, WalkComponent and SwingComponent. To enforce the transition rules, I have to couple each component. SwingComponent must disable StandComponent and WalkComponent for the duration of the swing. When I have an enemy that only stands around, swinging a sword occasionally, I have to make sure SwingComponent only disables WalkComponent if it is present. Although this allows for better mix-and-matching components, it can lead to a maintainability nightmare as each time a dependency is added, the existing components must be updated to play nicely with the new requirements the dependency places on the character.

The ideal situation would be that a designer can build new enemies/players by dragging components into a container, without having to touch a single line of engine or script code. Although I am not sure script coding can be avoided, I want to keep it as simple as possible.

Summing it all up: Should I lob all AI logic into one component or break up each logic state into separate components to create entity variants more easily?

**edit**: I suspect there is some confusion about what I meant with the first and second situation. I have tried to explain it in the diagram below.

Note the relationship between the individual states and the entity. In the first situation, an AI component is pre-built before being put in the entity. A designer can only select from a distinct set of AIComponents made available by the programmer. The second situation has the different states on the same level as other components. A designer can now create an entity with unique AI without interference of a programmer.

The question is, are these the only two options for structuring AI in an component-based entity and, if so, what would give the maximum flexibility?

# Answer
If you do intend to have more possible enemies or players that you can't imagine right now, then you should definitely break it up. What you're describing in your second point is basically the state pattern.

I think I agree with Gregory that you shouldn't have separate stand and walk state components. It's just a movement component with speed 0. On the other hand, if you have objects that can't move, you either have to split it up, or just put some kind of boolean restriction in the movement state that prevents having non zero velocity.

For the player I don't think it needs to be completely separate. It can still use all the other components, with the addition of an input component. This component drives the transitions between states, whereas in the enemy it's controlled by a default AI, or if you want, different AI subclasses that your enemy designers can choose from.

edit: actually, for your stationary enemies, rather than restricting the movement component, just give them a stationary AI component that never chooses to move them.
> 6 votes

# Answer
I'd at least keep Player AI (or what I'd call Player Controller) as its own component. With most games, the player is fundamentally different enough from the NPCs that you can't generalize from one to another except in basics like hit points.

For NPCs, I see StandComponent and WalkComponent as aspects of the same thing. Are you ever going to have a WalkComponent without a StandComponent? I doubt it. Likewise, a RunComponent would just be a WalkComponent with a higher speed and different animations. I can see the value in having an NPCMovementComponent and a separate NPCSwordFighterComponent, but even that feels like overengineering to me.
> 2 votes

# Answer
First I would make a State component and then I would create a state machine to handle the transitions. Make it generic enough that you can use this for your players and your AI. This will make sure the AI plays by the same rules and that you don't have to change your logic when you change how the player states work compared to the AI states.

Finite State Machine C++

The above has a concrete example of a state machine in c++ that can be used by players and AI alike.
> 2 votes

# Answer
What you want is a component handling the movement of characters (player and NPCs). The AI component or a player component will send commands to this movement component and it will check if the action can be initiated. This will encapsulate your movement constraints into one single component. Your AI code and player code do not have to know how swing sword is executed. The AI would have internal states e.g. Idle, Attacking, Fleeing.
> 1 votes

---
Tags: architecture, ai, component-based
---


# Question
Title: Android - Efficient way to draw tiles in OpenGL ES
I am trying to write efficient code to render a tile based map in android. I load for each tile the corresponding bitmap (just one time) and then create the according tiles. I have designed a class to do this:

```
public class VertexQuad {

private float[] mCoordArr;
private float[] mColArr;
private float[] mTexCoordArr;
private int mTextureName;
private static short mCounter = 0;
private short mIndex;

```

As you can see, each tile has it's x,y location, a color array, texture coordinates and a texture name. Now, I want to render all my created tiles.

To reduce the openGL api calls (I read somewhere that the state changes are costly and therefore I want to keep them to a minimum), I first want to hand ALL the coordinate-arrays, color-arrays and texture-coordinates over to OpenGL. After that I run two for loops. The first one iterates over the textures and binds the texture. The second for loop iterates over all Tiles and puts all tiles with the corresponding texture into an IndexBuffer. After the second for loop has finished, I call

```
gl.gl_drawElements()

```

whith the corresponding index buffer, to draw all tiles with the texture associated. For the next texture I do the same again.

Now I run into some problems: Allocating and filling the FloatBuffers at the start of each rendering cycle costs very much time. I just run a test, where i wanted to put 400 coordinates into a FloatBuffer which took me about 200ms.

My questions now are:

* Is there a better way, handling the coordinate and color structures?
* How is this correctly done, this is obviously not the optimal way? ;)

thanks in advance, regards Markus

# Answer
> 2 votes
In OpenGL ES 1.x, you can use several methods:

* glDrawArrays
* glDrawElements: TRIANGLES or TRIANGLES\_STRIP (denormalized triangles)
* VBO
* glDrawTexfOES (you need to verify that you have this extension)

glDrawTexfOES is the faster method to draw efficiently quads but it is not available on old phones. VBO is efficient for static quads. If you use VBO with FloatBuffers, there is a bug on Android 2.2 and 2.1 devices which causes slowness. Use the libgdx.so, to transfert data into VBO for performance. If you use NDK, there is no performance issues.

Your question is not OpenGL ES related but OpenGL Java Wrapping issue.

Ps: in efficient opengl es 1.x engines, you have a tool to batch drawcalls. It is recommanded to limit your drawcalls to 50.

Ps 2: the FloatBuffers is very slow on android devices \< 2.3. The libgdx has rewritten this part to speed its engines. You should look this issue.

# Answer
> 0 votes
You **don't** refill buffers every frame unless it's totally necessary, because this has a great performance penalty (copying data from CPU to GPU is no trivial task).

Create a VBO for each texture type, and fill it once (on map load, or whenever you want) with the data of those tiles. Then, iterate your tile texture array, set the active texture and then draw the corresponding VBO.

Keep in mind that this solution is very inflexible (in case your map changes dinamically), but for static tile maps is the best solution.

---
Tags: android, opengl-es, tiles
---


# Question
Title: Mesh with Alpha Texture doesn't blend properly
I've followed example from various place regarding setting OutputMerger's BlendState to enable alpha/transparent texture on mesh. The setup is as follows:

```
            var transParentOp = new BlendStateDescription {
            SourceBlend = BlendOption.SourceAlpha,
            DestinationBlend = BlendOption.InverseDestinationAlpha,
            BlendOperation = BlendOperation.Add,
            SourceAlphaBlend = BlendOption.Zero,
            DestinationAlphaBlend = BlendOption.Zero,
            AlphaBlendOperation = BlendOperation.Add,
        };

```

I've made up a sample that display 3 mesh A, B and C, where each overlaps one another. They are drawn sequentially, A to C. Distance from camera where A is nearest and C is furthest. So, the expected output is that A see through and saw part of B and C. B will see through and saw part of C.

But what I get was none of them see through in that order, but if I move C closer to the camera, then it will be semi transparent and see through A and B. B if move closer to camera will see A but not C. Sort of reverse.

So it seems that I need to draw them in reverse order where furthest from camera is drawn first then nearest to camera is drawn last.

Is it suppose to be done this way, or I can actually configure the blendstate so it works no matter in which order i draw them?

Thanks

# Answer
> 2 votes
Yes, that's the basics of blending: you must manually sort your objects from farther to closer, so when object B is drawn and occludes A, the alpha function merges the two colors correctly. Also, disable depth writing when drawing transparent object.

---
Tags: directx, directx10, slimdx
---


# Question
Title: Most efficient way to handle coordinate maps in Java
I have a rectangular tile-based layout. It's your typical Cartesian system.

I would like to have a single class that handles two lookup styles

1. Get me the set of players at position X,Y
2. Get me the position of player with key K

My current implementation is this:

```
class CoordinateMap<V> {
    Map<Long,Set<V>> coords2value;
    Map<V,Long> value2coords;

    // convert (int x, int y) to long key - this is tested, works for all values -1bil to +1bil
    // My map will NOT require more than 1 bil tiles from the origin :)
    private Long keyFor(int x, int y) {
        int kx = x + 1000000000;
        int ky = y + 1000000000;
        return (long)kx | (long)ky << 32;
    }

    // extract the x and y from the keys
    private int[] coordsFor(long k) {
        int x = (int)(k & 0xFFFFFFFF) - 1000000000;
        int y = (int)((k >>> 32) & 0xFFFFFFFF) - 1000000000;
        return new int[] { x,y };
    }
}

```

From there, I proceed to have other methods that manipulate or access the two maps accordingly.

My question is... **is there a better way to do this?** Sure, I've tested my class and it works fine. And sure, something inside tells me if I want to reference the data by two different keys, I need two different maps. But I can also bet I'm not the first to run into this scenario.

Thanks!

# Answer
Have you considered using a Hilbert R-Tree? I use it for doing computation on points with CUDA on the GPU, since "flattening" out multidimensional data in this way preserves data locality and results in fewer cache misses.
> 2 votes

---
Tags: java, coordinates, data-structure
---


title: C# Timers for game development

text:
# Question
Title: C# Timers for game development
I want to find out the best way of creating time based events in games. Lets talk for example about Texas Holdem Poker. Server can handle thousands of tables and in every table we have timers: turn timer, hold seat timer and so on.

What is the best way of timers realization for this purpose?

Is System.Timers.Timer class can handle this or it will be more reasonable to create a separate thread with sorted time queue (for example an ascending sorted list with int values which represent time in ms remained)?

Thanks in advance, Valentin

# Answer
> 5 votes
Timer can handle it, your main concern will be memory usage with thousands of requests.

A suggestion is to create an Async timer with a callback to signal the table or player of an action. The function signature is this :

```
Timer( TimerCallback callback, object state, uint dueTime, uint period)

```

so instead of keeping track of the timer queue yourself and having some heavy logic, you can just add a timer with a callback to your logic, and pass th

```
void HandleAction (object state)
      {
         //Do the work here
      }

      static void CreateTimer( )
      {
         Program p = new Program();

         Timer myTimer = new Timer
            (p.HandleAction, //method
               "Parameter to pass to the function.", //parameter
               2000,   // execute this after 2 seconds
               1000);  // Repeat every second
      }

```

# Answer
> 1 votes
This is how I'd do it, in general programming (not just C#)

I'd have a thread to handle my timers, with an ordered queue with datetime values for all future events.

Your timer thread would look like this:

```
while (true)
{
    curr_date = time();
    lock(queue);
    while (queue.top.date < curr_date)
    {
        act(queue.top); // usually very simple stuff, like alerting another thread
        queue.pop();
    }
    unlock(queue);
    thread.sleep(queue.top.date - curr_date);
}

```

In addition, any thread who wants to add a message into your timer list, should call a function like this:

```
lock(queue);
queue.insert_ordered(timer);
unlock(queue);
thread.awake();

```

Would something like this solve your problem?

---
Tags: c#, .net, timer
---


# Question
Title: Switching between Discrete and Integrated GPUs
I have a machine with two discrete GPUs and one integrated GPU. I can currently switch between them using NVIDIA's software, but I would like the ability to do so within my applications for purposes of benchmarking and general convenience. Apparently this requires the "NDA version" of NVIDIA's Driver API, which I know not how to obtain. Would using this API be the only way to accomplish what I seek, and if so, how would I obtain it? A solution using Windows APIs would also be acceptable, though less preferable to one which would leverage a cross-platform API. I have created a similar thread concerning the matter on NVIDIA's forum, which is down at the time of this writing.

Thanks for reading my question; it is much appreciated!

Edit: Here's a link to the original post I made on the NVIDIA forums - no luck on either site yet, though.

# Answer
> 2 votes
As far as I know there is no way to do this from the CUDA APIs, and honestly I doubt that there is a publicly available way to do it at all. Switching the current graphics device is a deeply rooted OS thing, something that likely only the device driver itself can do. I've never heard of the device driver exposing that functionality to other software.

There *might* be something buried deep in the Windows API that could do it, but I don't think a cross-platform solution exists because as far as I know switching graphics devices on the fly isn't supported in Linux at the moment. (I also have a laptop with two devices, an integrated Intel and discrete ATI FireGL, but for Linux I have to set the device specifically in the BIOS.)

I think you're just to have to switch them by hand.

---
Tags: hardware, gpu, gpgpu
---


# Question
Title: How can I convert a mouse click to a ray?
I have a perspective projection. When the user clicks on the screen, I want to compute the ray between the near and far planes that projects from the mouse point, so I can do some ray intersection code with my world.

I am using my own matrix and vector and ray classes and they all work as expected.

However, when I try and convert the ray to world coordinates my far always ends up as 0,0,0 and so my ray goes from the mouse click to the centre of the object space, rather than through it. (The x and y coordinates of near and far are identical, they differ only in the z coordinates where they are negatives of each other)

```
GLint vp[4];
glGetIntegerv(GL_VIEWPORT,vp);
matrix_t mv, p;
glGetFloatv(GL_MODELVIEW_MATRIX,mv.f);
glGetFloatv(GL_PROJECTION_MATRIX,p.f);
const matrix_t inv = (mv*p).inverse();
const float
    unit_x = (2.0f*((float)(x-vp[0])/(vp[2]-vp[0])))-1.0f,
    unit_y = 1.0f-(2.0f*((float)(y-vp[1])/(vp[3]-vp[1])));
const vec_t near(vec_t(unit_x,unit_y,-1)*inv);
const vec_t far(vec_t(unit_x,unit_y,1)*inv);
ray = ray_t(near,far-near);

```

What have I got wrong? (How do you unproject the mouse-point?)

# Answer
I recently had to solve this myself for a WebGL application. I've attached the complete source code, but incase it doesn't work right off the bat for you here are some debugging tips:

1. Don't debug your unproject method in your game. If possible, try to write unit-test style tests to make it easier to isolate what is going wrong.
2. Be sure to print the output rays for both the near and far clipping planes.
3. Remember that matrix math is NOT commutative. A x C != C x A. Double check your math.

Also, to reply to some comments above, you almost never want to use OpenGL's selection APIs. That helps you pick existing items, like if you were creating a menu, however it fails to perform most real-world scenarios like 3D model editing. Where you need to add geometry as a result of the click.

Here is my implementation. There is nothing magic going on here. Just JavaScript and Google's Closure library.

### gluUnProject

```
/**
 * Port of gluUnProject. Unprojects a 2D screen coordinate into the model-view
 * coordinates.
 * @param {Number} winX The window point for the x value.
 * @param {Number} winY The window point for the y value.
 * @param {Number} winZ The window point for the z value. This should range
 *    between 0 and 1. 0 meaning the near clipping plane and 1 for the far.
 * @param {goog.math.Matrix} modelViewMatrix The model-view matrix.
 * @param {goog.math.Matrix} projectMatrix The projection matrix.
 * @param {Array.<Number>} view the viewport coordinate array.
 * @param {Array.<Number>} objPos the model point result.
 * @return {Boolean} Whether or not the unprojection was successful.
 */
octorok.math.Matrix.gluUnProject = function(winX, winY, winZ,
                        modelViewMatrix, projectionMatrix,
                        viewPort, objPos) {
  // Compute the inverse of the perspective x model-view matrix.
  /** @type {goog.math.Matrix} */
  var transformMatrix =
    projectionMatrix.multiply(modelViewMatrix).getInverse();

  // Transformation of normalized coordinates (-1 to 1).
  /** @type {Array.<Number>} */
  var inVector = [
    (winX - viewPort[0]) / viewPort[2] * 2.0 - 1.0,
    (winY - viewPort[1]) / viewPort[3] * 2.0 - 1.0,
    2.0 * winZ - 1.0,
    1.0 ];

  // Now transform that vector into object coordinates.
  /** @type {goog.math.Matrix} */
  // Flip 1x4 to 4x1. (Alternately use different matrix ctor.
  var inMatrix = new goog.math.Matrix([ inVector ]).getTranspose();
  /** @type {goog.math.Matrix} */
  var resultMtx = transformMatrix.multiply(inMatrix);
  /** @type {Array.<Number>} */
  var resultArr = [
    resultMtx.getValueAt(0, 0),
    resultMtx.getValueAt(1, 0),
    resultMtx.getValueAt(2, 0),
    resultMtx.getValueAt(3, 0) ];

  if (resultArr[3] == 0.0) {
    return false;
  }

  // Invert to normalize x, y, and z values.
  resultArr[3] = 1.0 / resultArr[3];

  objPos[0] = resultArr[0] * resultArr[3];
  objPos[1] = resultArr[1] * resultArr[3];
  objPos[2] = resultArr[2] * resultArr[3];

  return true;
};

```

### Usage

```
  this.sys.event_mouseClicked = function(event) {
    // Relative x and y are computed via magic by SystemModule.
    // Should range from 0 .. viewport width/height.
    var winX = event.relativeX;
    var winY = event.relativeY;
    window.console.log('Camera at [' + me.camera.position_ + ']');
    window.console.log('Clicked [' + winX + ', ' + winY + ']');

    // viewportOriginX, viewportOriginY, viewportWidth, viewportHeight
    var viewPort = [0, 0, event.viewPortWidth, event.viewPortHeight];
    var objPos = [];  // out parameter.

    // The camera's model-view matrix is the result of gluLookAt.
    var modelViewMatrix = me.camera.getCameraMatrix();
    // The perspective matrix is the result of gluPerspective.
    var perspectiveMatrix = pMatrix.get();

    // Ray start
    var result1 = octorok.math.Matrix.gluUnProject(
      winX, winY, 0.0,
      modelViewMatrix, perspectiveMatrix,
      viewPort, objPos);
    window.console.log('Seg start: ' + objPos + ' (result:' + result1 + ')');

    // Ray end
    var result2 = octorok.math.Matrix.gluUnProject(
      winX, winY, 1.0,
      modelViewMatrix, perspectiveMatrix,
      viewPort, objPos);
    window.console.log('Seg end: ' + objPos + ' (result:' + result2 + ')');
  };
};

```
> 14 votes

# Answer
I dont see any problems with your code. So i only have some suggestions:

```
unit_x = (2.0f*((float)(x-vp[0])/(vp[2]-vp[0])))-1.0f,
unit_y = (2.0f*((float)(y-vp[1])/(vp[3]-vp[1])))-1.0f;

```

And trying to change matrix multiplacation to `(p*mv).inverse();`. Just because glMatrices are nutaraly transposed in memory. (this is one big maybe, sorry)

**Another raycasting**
Unprojecting is not only way how to get ray from the pixel. This is my code for raycaster:

```
//works for right handed coordinates. So it is opengl friendly.
float mx = (float)((pixel.x - screenResolution.x * 0.5) * (1.0 / screenResolution.x) * camera.fovX * 0.5);
float my = (float)((pixel.y - screenResolution.y * 0.5) * (1.0 / screenResolution.x) * camera.fovX * 0.5);
float4 dx = cameraRight * mx;
float4 dy = cameraUp * my;

float3 dir = normalize(cameraDir + (dx + dy).xyz * 2.0);

```

You can get cameraRight, Up and Direction from view matrix (which is mostly useful in shader) View matrix in opengl

**Color Picking**
Color picking is a technique where you render every clickable object with another (solid) color and then read the value of color at clicked point. It worked as GL\_SELECTION in opengl. But it is deprecated now. But color picking is easy to code as 1 additional render pass.

Use frame buffer and render to texture with same resolution as screen resolution, use simple shader which just return color in fragment shader. After "color pass", read the value from a texture addressing with clickedPoint x and y. Find object with color which you read. Easy and quite fast.
> 4 votes

---
Tags: opengl, camera, geometry
---


# Question
Title: Game engine design: Multiplayer and listen servers
My game engine right now consists of a working singleplayer part. I'm now starting to think about how to do the multiplayer part.

I have found out that many games actually don't have a real singleplayer mode, but when playing alone you are actually hosting a local server as well, and almost everything runs as if you were in multiplayer (except that the data packets can be passed over an alternate route for better performance)

My engine would need major refactoring to adapt to this model. There would be three possible modes: Dedicated client, Dedicated server and Client-Server (listen mode)

* How often is the listen-server model used in the gaming industry?
* What are the (dis)advantages of it?
* What other options do I have?

# Answer
> 11 votes
I'll see if I can answer this the best I can:

> How often is the listen-server model used in the gaming industry?

When it comes to most online games, you'll find that a large majority of games use a client-server architecture, though not always in the way you think. Take any Source game, for instance. Most will use a standard client-server with a master server architecture (to list games available), in that one person will host a dedicated server and anyone with a client can join it.

However, you have some games and services, take for instance Left 4 Dead, League of Legends, and some XBox Live games, that take a slightly different approach. These all use a client-server architecture with a controlling server. The main idea here is that someone creates a dedicated server that isn't "running" any game. The controlling server will create a "lobby" of sorts, and when the game is started, the controlling server will add them to a queue, and when it is that lobby's turn, it will select a matching dedicated server (in terms of location/speed, availability, numerous factors), and assign the players to that server. Only then will the server actually "run" the game. It's the same idea, but a little simplified, as the client doesn't need to "pick" a server, only join a game and let the controlling server do the work.

Of course, the biggest client-server model is the MMO model, where one or many servers runs a persistent world that handles almost all data and logic. Some of the more famous games using this model are World of Warcraft, Everquest, anything like that.

So where does a listen server fit in here? To be honest, not really that well, however, you will still find many games using it. For instance, most Source games allow listen servers to be created, and many XBox Live games do (it's been a while, but I believe Counter Strike did, as well as Quake 4, and many others). In general though, they seem to be frowned upon due to the advantages of the client-server model, which brings us to our next point.

> What are the (dis)advantages of it?

First and foremost: **performance**. In a client-server model, the client will handle local changes (such as input, graphics, sounds, etc) on each cycle of the game. At the end of the cycle, it will package up relevant data (such as, did the player move? If so, where to? Where is s/he looking now? Velocity? Did they shoot? If so, information on the bullet. Etc) and send that to the server for processing. The server will take this data and determine if every thing is valid such as, is the user moving in a way that indicates hacking (more on that later), is the move valid (anything in the way?), did the bullet from player 1 hit player 2?, and more. Then the server packages this up, and sends it to the clients, which then update whatever necessary, such as adjusting health if the player was shot, kicking the player if it is determined that they are hacking, etc.

A listen server, however, must deal with all of this at the same time. Since I assume you are familiar with programming, you probably realize how much power a game can rob from a computer, especially a poorly designed one. Adding on network processing, security processing, and more *as well as* the client's game, you can see where performance would take a serious hit, at least as far as just standard processing goes. Furthermore, most servers run on fast networks, and are servers designed to withstand network traffic. If a listen server's network is slow, the entire game will suffer.

Second **security**, as stated earlier, one of the main things a server will do is determine if a player is exploiting the game. You may have seen these as Punkbuster, VAC, etc. There are a very complicated set of rules that run these programs, for instance, determining the difference between a hacker, and just a very good player. It would be very bad for your game if you weren't able to catch hackers, but even worse if you executed action against a falsely accused one.

A listen server will generally not be able to handle the client's game, the server processing, and the hack detection, and in most cases, detectors like Punkbuster are very hard to, if not impossible to get to run on a listen server, because it's hard for it to function correctly without the necessary processing power, as generally the game logic is prioritized over security, and if the detector is not allowed to process for one frame it may lose the data it needed to convict someone.

Lastly, **gameplay**. The biggest thing about servers is that they are persistent, meaning that even if everyone leaves, the server will continue to run. This is useful if you have a popular server that doesn't have much activity in the night time, people can still join when they are ready to play and not have to wait for it to be brought back online.

In a listen server, the main disadvantage is that as soon as the client hosting the listen server leaves, the game must either be transferred to another player (creating a lul in the game that can last minutes in some cases), or must end completely. This is not preferable on a big server, as the host must either stay online (wasting a slot in the server, and his/her computer power, which could also slow the game), or end the game for everyone.

However, despite these problems, listen servers do have a few advantages.

**Easy to set up**: Most listen servers are nothing more than hitting "New game" and letting people join. This is easy for people who just want to play with their friends, and don't wish to have to try to find an empty dedicated server, or play with other people.

**Good for testing**: If one owns a dedicated server and wishes to change it's configuration, it is generally a better idea to *test* the configuration first. The user would either have to create a backup of the dedicated server and go blindly into the changes, with the only option being to roll back if something goes wrong, create a new dedicated server to test them, of just create a simple listen server to test them. And in with point 1, these are generally easier to start up and configure. This is especially true, as most dedicated servers are not within the administrators immediate access (most dedicated servers are rented from a remote location). It takes much longer to push configuration changes, as well as commands for restarting, etc, to a remote location than a machine that the administrator is currently on.

**Less resources**: In most dedicated servers, a user with the same IP cannot connect to the dedicated server (meaning, the client must either host the server, or play, they cannot do both). If the client wishes to play on his/her own server, they will usually need a second machine to host the server, or *buy or rent* a dedicated server so that they can actually play on it. A listen server requires only one machine, which may be the only thing the client can use.

In either case, both have advantages and disadvantages, and you need to weigh them with what you're willing to design and implement. From my experience, I believe that if you were to implement a listen server it would get used, if for nothing else than for a few users wishing to play around with friends, or test settings.

Lastly:

> What other options do I have?

This is an industrial can of worms. In reality, any type of network architecture can be applied to video games. However, from what I've seen, like most internet communication, most boil down to some form of client-server model.

Please let me know if I didn't answer your question, or if you need something expanded, and I'll see what I can do.

---
Tags: multiplayer, server
---


title: Browser-based MMOs (WebGL, WebSocket)

text:
# Question
Title: Browser-based MMOs (WebGL, WebSocket)
Do you think it is technically possible to write a fully-fledged 3D MMO client with Browser JavaScript - WebGL for graphics, and WebSocket for Networking?

* Do you think future MMOs (and games generally) will be written with WebGL?
* Does today's JavaScript performance allow this?
* Let's say your development team was you as a developer, and another model creator (artist). Would you use a library like SceneJS for the game, or write straight WebGL? If you would use a library, but not SceneJS, please specify which.

**UPDATE (September 2012):** RuneScape, which is a very popular 3D browser-based MMORPG that used Java Applets so far has announced that it will use HTML5 for their client (source).

Java (left) and HTML5 (right)

**UPDATE (June 2013):** I have wrriten a prototype of a WebGL/WebSocket based MMO: https://github.com/alongubkin/xylose

# Answer
> Do you think it is technically possible to write a fully-fledged 3D MMO client with Browser JavaScript - WebGL for graphics, and WebSocket for Networking?

Yes, absolutely. There is no reason WebGL or WebSocket technology would prevent you from making a 3D MMOG client, or any game client for that matter.

> Do you think future MMOs (and games generally) will wrriten with WebGL?

Yes. I believe within the next five years, most 3D browser games will be written using WebGL. The reason is simple - WebGL is the only standardized 3D technology that will have implementations available in every major web browser (Chrome 9, Firefox 4, Safari 6, and Internet Explorer via Chrome Frame).

> Does today's JavaScript performance allow this?

Yes. JavaScript performance in modern browsers has increased to the point where 3D game development is feasible. For example, see the Three.js project.

> Let's say your development team was you as a developer, and another model creator (artist). Would you use a library like SceneJS for the game, or write straight WebGL? If you would use a library, but not SceneJS, please specify which. Thanks!

Use a library to save time. There is no reason to write your own WebGL graphics code unless an existing library is missing features that you need. Even in that case, it would probably be more time efficient to extend the existing library.

For my project, I am using GLGE as it supports many different graphics effects and is constantly being updated with new ones.
> 7 votes

# Answer
There are already several Browser based MMOs out there. They usually don't use 3D graphics though.

I'm a bit sceptic when it comes to WebGL. The current crop of browsers don't support WebGL in their normal release builds. You'll have to get special builds or mess with config files, which is more complicated to the average user than downloading a plugin.

Speaking of plugins: Several people mentioned Unity, but don't forget Flash. An upcoming release of the Flash player (code-name molehill) will have GPU-accelerated 3D. My guess is, that flash will provide hardware accelerated 3D graphics in the browser before WebGL takes off.
> 5 votes

# Answer
Technically possible? Yes. But why bother when web solutions like Unity are available?

Future MMOs written in WebGL? No. Ok maybe but there are web based plugins like Unity that do fine right now.

Today's JavaScript performance allow this? No. Ok yes if you keep your game simple.

Would you use a library like SceneJS \[...\] or write straight WebGL? Neither. I would use a third party application such as Unity.
> 3 votes

# Answer
This is not feasable right now (early 2011). You can not create a real-time, 3D MMO in native, browser technologies (meaning no plugins).

I won't speculate about the future. This is how it looks right now. Assuming you target only modern browsers (IE9, FF4, etc). If you plan to support IE7 then you are crazy. That will never work.

Things missing:

* full control over keyboard and mouse (ability to set mouse position, key interception)
* fullscreen
* 3D

Areas / solutions with serious problems:

* WebSockets now deactivated in the few browsers that supported it
    + without it: now low latency, bi-directional client-server communication
* audio problems
    + codec mess, you need ogg and mp3
    + common frequences not supported
    + concurrancy
    + delay
* canvas performance (in some cases doing divs & css transformations is faster)
> 2 votes

# Answer
Yes, but with major caveats.

You won't have full keyboard control, and for many control freaks, this could be a deal-breaker. The F-keys for example will likely remain out of reach for quite some time.

You're not going to be able to hit most browsers, either. WebGL isn't really well-supported yet, and websocket support is hit-and-miss these days, with some browser vendors enabling it for one version, then disabling it for the next.

But you can put together something simple, sure. Throw in some compelling gameplay and it won't matter that the graphics are a little low-key. Runescape started off pretty simple, and grew into a complex, fun, incredibly popular MMO, back when everyone said that an MMO created in a browser plug-in was a pipe dream.

An MMO built withing the current limits for browsers that adapts as things change would certainly have a leg-up by the time that browsers are far enough to support a "AAA" MMO.
> 1 votes

# Answer
Absolutely, yes.

WebGL is included in nightly builds of both WebKit (Chrome/Safari) and Gecko (Firefox). WebSockets is currently disabled due to security issues, but there is no reason why it shouldn't be re-enabled once the issues are resolved. In the meantime there is always HTTP.

Will all games be written this way? No, but a significant number will be. Once WebGL is in final versions of Chrome and Firefox the penetration will already be higher than that of native plug-ins like Unity.

JavaScript performance is absolutely up to writing games. You probably won't see a Crysis level of graphics for a while, but remember with WebGL, the number-crunching is offloaded to the GPU.

For a small 2-man team you will need to be prepared to do a lot coding which ever engine you use. There currently aren't any WebGL/JavaScript engines that actually cover much of the game code. SceneJS, three.js and similar are wrappers over the graphics layer, but provide nothing for collision, physics, audio, resource-loading, network or tools which make up the bulk of a product like Unreal Engine, or Unity.

It's early days at the moment, I'd expect to see more middleware emerging over the next year.
> 1 votes

# Answer
I don't think many future MMOs will be written with any client-side browser technology since most MMO developers will want to use the same language across the client and the server, and most game developers are fluent in non-web languages like C++. There's far too much client-code involved to make it very practical in Javascript anyway, except for quite trivial simulations. There are also other limitations imposed by running in the browser which are unsavoury for a typical game developer.

I'm sure there will be *some* games like this, however. They're just not going to take over from WoW or similar games for quite a while. They will probably be made more by web developers getting into games rather than games developers getting into the web.
> 0 votes

# Answer
The question you should ask yourself is why will game developpers want to depend on web technology they do not master and have no control over, current langages allows you even in a web browser to make awesome games ?
> 0 votes

# Answer
Yes, but the technology still needs to stabilize and there will likely remain performance trade-offs vs native applications.
> 0 votes

# Answer
Unity is good. See also Shiva and the Prime Engine.
> -3 votes

---
Tags: mmo, webgl, websocket
---


# Question
Title: OpenGL - Stack overflow if I do, Stack underflow if I don't!
I'm in a multimedia class in college, and we're "learning" OpenGL as part of the class. I'm trying to figure out how the OpenGL camera vs. modelview works, and so I found this example. I'm trying to port the example to Python using the OpenGL bindings - it starts up OpenGL much faster, so for testing purposes it's a lot nicer - but I keep running into a stack overflow error with the glPushMatrix in this code:

```
  def cube():
      for x in xrange(10):
          glPushMatrix()
          glTranslated(-positionx[x + 1] * 10, 0, -positionz[x + 1] * 10); #translate the cube
          glutSolidCube(2); #draw the cube
          glPopMatrix();

```

According to this reference, that happens when the matrix stack is full.

So I thought, "well, if it's full, let me just pop the matrix off the top of the stack, and there will be room". I modified the code to:

```
  def cube():
      glPopMatrix()
      for x in xrange(10):
          glPushMatrix()
          glTranslated(-positionx[x + 1] * 10, 0, -positionz[x + 1] * 10); #translate the cube
          glutSolidCube(2); #draw the cube
          glPopMatrix();

```

And now I get a buffer underflow error - which apparently happens when the stack has only one matrix.

So am I just waaay off base in my understanding? Or is there some way to increase the matrix stack size?

Also, if anyone has some good (online) references (examples, etc.) for understanding how the camera/model matrices work together, I would sincerely appreciate them!

Thanks!

EDIT:

Here is the pastebin of the full code: http://pastebin.com/QXxNisuA

# Answer
*Edited to add: this isn't important for now as it will still work just fine and makes learning OpenGL easier but do note that the whole matrix stack system is deprecated in OpenGL 3.x and beyond. One possible replacement is GLM.*

The code in your pastebin fails to even run for me.

In particular, your list indices in the display function are out of range (your list has 10 elements : python lists start at 0; you index from 0+1 to 10+1).

I think you also had some globals missing in the mouse handling function but that could be from me moving code around in an attempt to at least make it look like python ;)

Anyway, with these fixes, the code shown below DOES work for me, with no signs of GL matrix stack under/overflow !

```
import sys
from math import sin, cos
from random import randint
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
#angle of rotation
xpos= ypos= zpos= xrot= yrot= angle= lastx= lasty = 0

#positions of the cubes
positionz = []
positionx = []

def init():
    global positionz, positionx
    glEnable(GL_DEPTH_TEST) #enable the depth testing
    glEnable(GL_LIGHTING) #enable the lighting
    glEnable(GL_LIGHT0) #enable LIGHT0, our Diffuse Light
    glShadeModel(GL_SMOOTH) #set the shader to smooth shader

    positionx = [randint(0, 10) for x in xrange(10)]
    positionz = [randint(0, 10) for x in xrange(10)]

def camera():
    global xrot, yrot, xpos, ypos, zpos
    glRotatef(xrot,1.0,0.0,0.0)  #rotate our camera on teh x-axis (left and right)
    glRotatef(yrot,0.0,1.0,0.0)  #rotate our camera on the y-axis (up and down)
    glTranslated(-xpos,-ypos,-zpos) #translate the screen to the position of our camera

def display():
    global angle
    glClearColor(0.0,0.0,0.0,1.0) #clear the screen to black
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #clear the color buffer and the depth buffer
    glLoadIdentity()
    camera()
    for x in xrange(10):
        glPushMatrix()
        glTranslated(-positionx[x] * 10, 0, -positionz[x] * 10) #translate the cube
        glutSolidCube(2) #draw the cube
        glPopMatrix()
    glutSwapBuffers() #swap the buffers
    angle += angle #increase the angle

def reshape(w, h):
    glViewport(0, 0, w, h); #set the viewport to the current window specifications
    glMatrixMode(GL_PROJECTION); #set the matrix to projection

    glLoadIdentity();
    gluPerspective(60, w / h, 1.0, 1000.0)
    #set the perspective (angle of sight, width, height, , depth)
    glMatrixMode(GL_MODELVIEW); #set the matrix back to model

def keyboard (key, x, y):
    global xrot, xpos, ypos, zpos, xrot, yrot, angle, lastx, lasty, positionz, positionx
    if (key=='q'):
        xrot += 1
        if (xrot >360):
            xrot -= 360
    if (key=='z'):
        xrot -= 1;
        if (xrot < -360): xrot += 360
    if (key=='w'):
        yrotrad = (yrot / 180 * 3.141592654)
        xrotrad = (xrot / 180 * 3.141592654)
        xpos += float(sin(yrotrad))
        zpos -= float(cos(yrotrad))
        ypos -= float(sin(xrotrad))
    if (key=='s'):
        yrotrad = (yrot / 180 * 3.141592654)
        xrotrad = (xrot / 180 * 3.141592654)
        xpos -= float(sin(yrotrad))
        zpos += float(cos(yrotrad))
        ypos += float(sin(xrotrad))
    if (key=='d'):
        yrotrad = (yrot / 180 * 3.141592654)
        xpos += float(cos(yrotrad)) * 0.2
        zpos += float(sin(yrotrad)) * 0.2
    if (key=='a'):
        yrotrad = (yrot / 180 * 3.141592654)
        xpos -= float(cos(yrotrad)) * 0.2
        zpos -= float(sin(yrotrad)) * 0.2
    if (key==27):
        sys.exit(0)

def mouseMovement(x, y):
    global lastx, lasty, xrot, yrot
    diffx=x-lastx #check the difference between the current x and the last x position
    diffy=y-lasty #check the difference between the current y and the last y position
    lastx=x #set lastx to the current x position
    lasty=y #set lasty to the current y position
    xrot += float(diffy) #set the xrot to xrot with the addition of the difference in the y position
    yrot += float(diffx) #set the xrot to yrot with the addition of the difference in the x position

glutInit()
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(500, 500)
glutInitWindowPosition (100, 100)
glutCreateWindow("A basic OpenGL Window")
init()
glutDisplayFunc(display)
glutIdleFunc(display)
glutReshapeFunc(reshape)
glutPassiveMotionFunc(mouseMovement)
#check for mouse movement
glutKeyboardFunc (keyboard)
glutMainLoop()

```
> 9 votes

# Answer
OpenGL can store and restore matrices on a stack using `glPushMatrix` and `glPopMatrix`. It is very important that each push has a corresponding pop - if you push more than you pop, you get told when all the drawing is over that you are overflowing the stack. If you pop more than you push, you get told immediately that you are underflowing the stack. This is how OpenGL lets you localise programming errors.

So ensure that all pushes everywhere have a corresponding pop.

Everywhere you push, ensure there is a corresponding pop in the exit of that code block.

If your code is throwing an exception (i.e. your iterating out of bounds in your array?), it may be that you need to place the pop in a finally block, e.g.:

```
def cube():
    for x in xrange(10):
        try:
            glPushMatrix()
            # draw something
        finally:
            glPopMatrix()
            # I'm trusting some code further out will catch and display your actual error now

```
> 1 votes

---
Tags: opengl, python
---


# Question
Title: First Person Shooter game agent development
I would like to apply (program) the Artificial intelligence methods to create game bots for first person shooter games. Do you have any knowledge from where can I start to develop as a Linux user? Do you have a suggestion for an easy-to-start game for which I can develop bots easily, caring more about the result of my algorithms rather than spending a lot of time dealing with the game code? I've read some publications about the applied methods to Quake 3 (c) and Open Arena. But I couldn't find the source codes and manuals describing how to start coding( for compiling, developing ai and etc.).

I appreciate your help.

# Answer
Looking at the Quake 3 source code probably isn't going to help you at this stage, if you're new to AI development. There is a lot of code and it can be quite easy to get overwhelmed at the sheer size of it.

First of all, if you want to create an AI bot for an existing game, then that's a little bit of a legal grey area and it's a lot more difficult since you probably won't have much access to the game's API.

On the other hand if you are creating a bot for a game that you currently are developing for, then this is relatively easier.

First of all, sort out exactly what you want your bot to do. Get a list of requirements of what you want your bot to eventually do. Then start right at the bottom.

I would probably split it up into separate tasks such as:

* Movement
* Targeting
* Sensory system - what the bot can see and hear
* World representation - how the bot observes and manipulates the world
* An FSM to govern behaviour at first to keep it simple - Hunt state, Attack state, Flee state, etc
* An algorithm to select the best weapon for the job - this can probably be simplified to always use the most powerful weapon in the bot's arsenal.

In Programming Game AI by Example, Buckland shows a 2D representation of a Quake-like game that contains goal-based behaviours, which is probably a lot more relevant to this kind of simulation. I'd definitely recommend getting the book as it deals with building AI from the bottom up.

Just bear in mind that a good AI bot is no simple task. There is a lot of research out there currently going on trying to get the most human-like behaviour. But as long as you design it well and break the entire thing into small tasks and components, you should make good progress on it.

Good luck! :)
> 4 votes

# Answer
The book "Programming Game AI by Example" (by Mat Buckland) is a great way to start. and as the title says, example code/game is included.
> 2 votes

# Answer
If you're looking to code a FPS bot without wanting to get into the engine itself, Pogamut allows you to code just the AI bot portion for Unreal Tournament 2004. It's more limiting than say diving into the Quake 3 or Enemy Territory code base, but it also lets you focus in on just AI.

**Pogamut 3 GameBots2004**

Extension of the original GameBots work done by USC which supports UT2004/ UDK/ and Defcon. Allows an external program to control bots in game in a **Client/Server** fashion as if they were a human player.

> External control mechanisms can be connected to many of these games using the scripting languages, thereby providing a tool to control the in-game characters from the outside. Pogamut utilizes UnrealScript (UT2004 scripting language) in this way and also NetBeans Java platform to provide an out-of-the box development environment for AI of virtual characters inhabiting **UT2004**, **Unreal Development Kit (UDK)** and **DEFCON** worlds.

*-- Copied and Pasted from my CW Game Dev post*
> 2 votes

---
Tags: game-design, ai, linux
---


# Question
Title: Modelling photo-realistic grass in realtime
I see a number of tutorials on how to create good looking grasses when creating 3D renders but can't think how to model it for realtime/use in a game's scenery.

Sure simple models with alpha cutouts can be used to create plants and trees in really awesome scenery but what about a lawn?

Are there any good tricks to achieve this effect? I tried with a simple 4 sided box and a small texture and the number of objects needed for a decent appearance made Max crawl to a halt.

(I am thinking it may be possible with a shader but that is a whole other area so thought I would just ask about anyones experience with modelling it here)

Thanks!

# Answer
> 4 votes
I'm not sure what is considered the best approach, but one option would be to use instanced geometry - you provide the GPU with a 3d model and a list of places/orientations where you'd like it drawn (preferable in the form of a concatenated matrix), and the GPU will handle the rest via a custom vertex shader.

Basically, you create two vertex buffers: one containing your 3D model (a blade of grass or patch of sod, for instance), and one containing a list of transformation matrices, each matrix containing the scale+rotation+translation where you'd like to render an instance of your model. (You'll need a custom vertex structure to hold the matrix - it's a vertex buffer in name only, and is just used to pass matrices to the GPU.)

Then, you'll need a custom shader. The vertex shader will get called for each vertex in each stream, so for each call you'll get two input parameters: one vertex from your blade model, and one of the transformation matrices. The shader then transforms the model vertex with the matrix, and returns the updated position.

If you want effects like wind, etc, you can adjust the matrix for each instance and update the matrix stream.

Using a model for a patch of grass rather than individual blades is makes it easier to cull. If you're using an octree or BSP for collision and visibility determination, you can reduce the depth of your tree by dealing with larger "blocks" of grass instead of smaller blades. Also, it's easy to provide a less complex/less-detailed model for a patch of grass if you detect a performance issue.

There's also something called a "Geometry Shader" that may apply here, but I don't know anything about it other than it's relatively new and apparently (?) not supported on the xbox.

Here's a link to an XNA instancing sample.

**Update**

Alternate methods: Though rendering lots of grass via instancing is significantly faster than other geometry-based methods, it can still be very expensive. GPU Gems contains an interesting alternative using intersecting billboard clusters.

And, of course, there's shell rendering, which consists of rendering a stack of textured polys, each with a map of "dots" on a transparent background. Each texture has an image of a cross section of a patch of grass - think dots on a transparent background. When you render them in close proximity, the solid parts of the texture appear to be extruded and connected between the layers. Not sure how well this performs.

**Update 2**

I hadn't noticed that the XNA billboard sample is a grass simulation.

# Answer
> 6 votes
The probably best reference to rendering grass: Boulanger.

Also, since geometry shader was mentioned: this techdemo has slightly inferior quality compared to K. Boulanger's technique, but it is stunning in another way since it draws crazy amounts of grass blades and does the culling via the geometry shader and transform feedback, which is a pretty cool idea.

# Answer
> 1 votes
i would LOVE to suggest pure geometry shader based solution, but you dont know even basic vertex-fragment shaders. So no, let's stay on the ground:). I will only guide to this site:

Loopix project

It is great place where to grab simple vegetation models. They are very lowpoly and always only one textured, with very smart texture repeating.

Use instanced rendering for sure.

---
Tags: 3d, 3d-meshes, levels, level-of-detail
---


title: How to improve batching performance

text:
# Question
Title: How to improve batching performance
I am developing a sprite based 2D game for mobile platform(s) and I'm using OpenGL (well, actually Irrlicht) to render graphics. First I implemented sprite rendering in a simple way: every game object is rendered as a quad with its own GPU draw call, meaning that if I had 200 game objects, I made 200 draw calls per frame. Of course this was a bad choice and my game was completely CPU bound because there is a little CPU overhead assosiacted in every GPU draw call. GPU stayed idle most of the time.

Now, I thought I could improve performance by collecting objects into large batches and rendering these batches with only a few draw calls. I implemented batching (so that every game object sharing the same texture is rendered in same batch) and thought that my problems are gone... only to find out that my frame rate was even lower than before.

Why? Well, I have 200 (or more) game objects, and they are updated 60 times per second. Every frame I have to recalculate new position (translation and rotation) for vertices in CPU (GPU on mobile platforms does not support instancing so I can't do it there), and doing this calculation 48000 per second (200\*60\*4 since every sprite has 4 vertices) simply seems to be too slow.

What I could do to improve performance? All game objects are moving/rotating (almost) every frame so I really have to recalculate vertex positions. Only optimization that I could think of is a look-up table for rotations so that I wouldn't have to calculate them. Would point sprites help? Any nasty hacks? Anything else?

Thanks.

# Answer
Did you use my port of irrlicht for android ? For 2d sprites on Android and iphone, i use the same tricks as you: batching. I try many solutions in OpenGL ES 1.x and 2.x:

* sort by z (parallax) and by texture, do the transformations on the CPU and call glDrawArrays or glDrawElements (fastest way). Use one big texture if you can.
* same trick with VBO, not faster because for each frame you refresh all informations. It can be useful for statics sprites.
* use OpenGL ES 2.x and use Vertex shader to compute positions (slower)
* use PointSprites (no solution if it is not a square and too many transparent pixels kill fillrate)
* use gldrawtexoes extension...
* use a drawcall for each sprite (slowest method)

So as you, all transformations are done by the CPU for OGLES 1.x or OGLES 2.x. If you have neon instructions, you can use them to speed your computations.

Ps: on iphone or android devices, i'm not CPU limited but fill rate limited. So it is very important to limit overdraw.
> 6 votes

# Answer
I would recommend having a VBO, with each vertex containing the position/rotation of each rendered object and batching based on texture like you're doing. I'm not very familiar with ogl ES, so i'm not sure which version of glsl it supports, but you might even be able to batch based on a set of textures, and store which of the 4 or so textures you are passing in you'd be using inside of the vertex. Point sprites would definitely improve you're performance because it would cut down the amount of data you are sending over drastically, and batching should never decrease performance if you are doing it correctly. Also, you could improve performance a bit by computing rotation on the shader and only passing in an int/float value into the params or inside the vertex itself. (params would be faster, just create an array for each batch and have an index into that array stored inside the vertex itself)
> 1 votes

# Answer
You mention mobile platforms which do not have instancing. But, you still do have vertex shaders, don't you?

In that case, you can still do pseudo instancing, which is very fast too. Make a VBO (GL\_STATIC\_DRAW) with the corner points (relative to the center point of the sprite, e.g. -1/-1, 1/-1, 1/1, -1/1) and any texture coordinates you need, in it.
Then set one of the generic vertex attributes for every draw call to the centerpoint of the sprite, and draw the two triangles with the buffer bound. Inside the vertex shader, read the generic vertex attribute and add the vertex's coordinates.

That will save you blocking on a data transfer for every sprite and should be much faster. The actual number of draw calls is not so terribly important, the blocking/stalling in between is.
> 1 votes

# Answer
The problem resides in the amount of data you are sending to the GPU each frame. Just create a VBO for each batch and populate it once, then apply the corresponding transformation matrices (via glMultMatrix, or a shader if you are using ES 2.0) when drawing the batches.
> 0 votes

---
Tags: opengl, sprites, performance
---


# Question
Title: How to implement mouselook in the browser?
I am currently creating a 3D first-person shooter game in the browser using WebGL. How would I implement mouselook/free look for such a game?

# Answer
Mouselook is now supported in Chrome and Firefox via the W3C Pointer Lock specification. Essentially:

```
document.onmousemove = function (e) {
  document.body.innerHTML = "<div>dx: " +
    (e.movementX || e.mozMovementX || e.webkitMovementX || 0);
}

document.body.onclick = document.body.requestPointerLock ||
                        document.body.mozRequestPointerLock ||
                        document.body.webkitRequestPointerLock;

```

A good tutorial article is Pointer Lock and First Person Shooter Controls on HTML5Rocks.
> 10 votes

# Answer
Capture `mousemove` Events and use the `screenX` and `screenY` properties of the event object to update camera position (use the delta to the last `screenX` and `screenY` position to get the amount of movement).

If you have some sort of scenegraph, you could build a node-setup like the following:

```
CameraNode (Scene Node)
 |
 +- YawNode (Scene Node)
     |
     +- PitchNode (Scene Node)
         |
         +- Camera (actual Camera Object)

```

Movement in the X-Axis rotates the YawNode and movement in the Y-Axis rotates the PitchNode. The CameraNode will be moved when the player moves.
> 1 votes

# Answer
It's quite simple, and just takes two things.

1. An event handler for the mouse move event.
2. A camera object representing your basic model-view transformation

### Sample event code

Here's some sample source code for doing the event handling. The system module (which handles all game \<--\> browser interaction) keeps track of two variables: `lastMousePosition` and `lastMouseDelta`.

To track the camera with the mouse, you just need `lastMouseDelta` which is how you will know how many degrees to rotate frame-to-frame.

```
  var canvas = /* WebGL rendering context */
  canvas.onmousedown = function (event) { me.handleMouseDown(event); };
  canvas.onmouseup   = function (event) { me.handleMouseUp(event);   };
  canvas.onmousemove = function (event) { me.handleMouseMove(event); };

  // snip

  engine.SystemModule.prototype.handleMouseMove = function(event) {
    this.lastMouseDelta = [event.clientX - this.lastMousePosition[0],
                           event.clientY - this.lastMousePosition[1]];
    this.lastMousePosition = [event.clientX, event.clientY];
  };

```

### Same camera movement code

Here's some sample code for handling the camera rotation. Given the number of pixels the mouse has moved in the X or Y direction, rotate the camera by that many degrees.

```
 /**
   * degrees/pixel
   * @const
   */
  var cameraMouseRotation = 0.5;

  // Mouse movement for camera angle.
  if (sys.isMouseDown()) {
    var positionChange = sys.getLastMousePositionDelta();
    camera.rotateYDegs(cameraMouseRotation * positionChange[0]);
    camera.rotateXDegs(-cameraMouseRotation * positionChange[1]);
  }

```

Later, when you actually go on to render your world, simply generate a model-view matrix from your camera. (Converting the camera's position, yaw, pitch, and roll into vectors you can pass to gluLookAt.) And you should be good to go.
> 1 votes

---
Tags: 3d, javascript, webgl, first-person-shooter, browser-based-games
---


title: Comparison between Cocos2d and Corona

text:
# Question
Title: Comparison between Cocos2d and Corona
I'm having a really hard time deciding which way to go on this. I'm about to start developing a game and I haven't been able to find many good comparisons between these approaches. I don't have many requirements for the game yet, but here is what I do know.

* needs to work on iPhone
* I don't have much money ($400 for Unity for iPhone is probably too much. I can probably afford $99 for Corona.)
* Graphics will be 2D
* Physics support is not needed
* Ability to use particles would be nice
* Game Center support would be nice (Corona is planning to support it soon)
* It would be nice to be able to support Android as well if it isn't much effort.

I have done my own research, so I know basic things about them. I know Corona uses Lua and Cocos2D uses Objective C. I know that Corona allows deployment to iPhone and Android, but how easy is it?

Cocos2D is free, but so many people talk about how easy it is to use Corona, but I don't like being restricted to features Corona supports or the price tag. I feel so torn here.

# Answer
I have never used Corona, but it looks nice. Especially the easy deployment to different platforms makes it interesting if you plan to release for Android and iOS.

The problem with an engine like Corona or Unity is, that you're mostly limited to what they include in their API. Apparently corona doesn't come with a particle engine (you'll need a license for an addon).

The big plus of Cocos2D is, that it's native code and you can mix and match it with other libraries. If you find some good C++ library that would be useful for your game you can add that rather easily (as long as it compiles for iOS). On the other hand you're stuck with iOS then. Porting to Android would most likely require a rewrite of your code in Java.

Programming in Objective-C is most likely to be more difficult than using a scripting language, unless you have some previous experience with C or C++.

I'm sorry that I probably didn't solve your problem, maybe I made it even worse. My advice to you is to make a checklist of your most important features and add a *weight* (or preference) to each point. Then add up the weights to choose which engine to use.
> 4 votes

# Answer
I haven't used Corona.It needs a license if you need to publish.Cocos2d on the other hand is really flexible and stable 'graphics' engine right now.

I would suggest Cocos2d-x (C++ version) as objective-c version has some performance issues when your update cycle is Overloaded.This performance issues is ONLY because of the message passing System in Objective-C.

As others said,You need to depend on the support of 'third party Engine' if any thing NEW comes up!But cocos2d is flexible at that moment!

If you are targeting multiple platforms,Cocos2d-X is ready for that as well! Check this link - http://www.cocos2d-x.org/wiki/cocos2d-x/Chapter\_1\_-\_Create\_a\_New\_cocos2d-x\_project\_with\_multi-platforms
> 1 votes

# Answer
I have only had a quick once over look at Corona and it does seem nice. Mobile platforms are quite restrictive in and of them selves so trying to knock out a game that will work in multiple platforms can be a daunting task especially if its your first.

I have been in the same place as you. I was torn between different engines but finally setled on Cocos2d. Here are my core reasons:

* versatility 1: it allowed me to mix native iphone views and features this includes things like gestures
* versatility 2: you can use natice c or c++ libraries if found any suitable onces
* Control: i had direct access to the code base so if i wanted to change anything in the engine i could also if i fixed anything i could submit it(not that i had)
* Support: there is a big and active community behind Cocos2D
* Complete: i can build the game and the menu all using the Cocos2D Api
* Extras: out of the box i got other other extras like a physic engine(not that i use it but its supposed to be pretty good)

2 Reasons i would stay with it:

* has 3d now :)
* if a 16 year old can make a iPad game of the week then surely i can ;)

As for your check list as far as cocos2d is concerned

* needs to work on iPhone(check)
* I don't have much money ($400 for Unity for iPhone is probably too much. I can probably afford $99 for Corona.)(free)
* Graphics will be 2D(check)
* Physics support is not needed(well it has it if you change your mind)
* Ability to use particles would be nice(half check decent effects engine)
* Game Center support would be nice (Corona is planning to support it soon)(either way pretty easy to implement in its own right)
* It would be nice to be able to support Android as well if it isn't much effort. (there is a cocos2D for android but it is nothin like the iPhone one which is a good thing cause it means its tailored to the platform) hope that helped :)
> 0 votes

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


# Question
Title: Significance of Bresenhams Line of Sight algorithm
What is the significance of Bresenhams Line of Sight algorithm in chasing and evading in games?

As far as i know and implemented this algorithm calulates the straight line between two given points. However while implementing it in game development i stored the points calculated using this algorithm in an array.Then im traversing this array for chasing and evading purpose. This looks to be working good with some angles only.In an pixel based environment/tile based.

What if there are some obstacles added in the paths of the two points? then this algorithm will not work right?

How well can we use the Bresenhams Line algorithm in game development?

# Answer
Bresenhams line algorithm was very useful in history (history of computer graphics), where was need of drawing lines without using floating point operations, because integer operations are faster (was faster). This is not today problem. In cpu is integrated math co-procesor (till intel 486), there is SSE unit and also GPU computes floatng points. There are not many useful usages of Bresenham today. But still. It is very interesting historicaly and it is beatiful algorithm to study.
> 4 votes

---
Tags: algorithm
---


# Question
Title: How can state changes be batched while adhering to opaque-front-to-back/alpha-blended-back-to-front?
This is a question I've never been able to find the answer to. Batching objects with similar states is a major performance gain when rendering many objects. However, I've been learned various rules when drawing objects in the game world.

1. Draw all opaque objects, front-to-back.
2. Draw all alpha-blended objects, back-to-front.

Some of the major parameters to batch by, as I understand it, are textures, vertex buffers, and index buffers. It seems that, as long as you are adhering to the above two rules, there's little to be done in regards to batching.

I see one possibility to batch, while still adhering to the above two rules. Opaque objects can still be drawn out of depth-order, because drawing them front-to-back is merely a fillrate optimization, meanwhile state changes may very well be far more expensive than the overdraw of drawing out of depth-order. However, non-opaque objects, those that require alpha-blending at least, *must* be drawn back-to-front in order to avoid rendering artifacts.

Is the loss of the fillrate optimization for opaques worth the state batching optimization?

# Answer
> 5 votes
You might want to read Christer Ericson's excellent blog post on draw call bucketing: http://realtimecollisiondetection.net/blog/?p=86

Alpha blended objects will have to be draw back to front to avoid artifacts.

State batching will not help with reducing the amount of alpha blended objects being rendered.

If you're looking for a way to discard objects that do not visually contribute to the scene, then what you're looking for is culling.

What state batching will help with is to *ensure* that your alpha blended objects are *actually* drawn last and in reverse depth-order.

It will also ensure that within both your alpha and non-alpha buckets all objects are sorted so as to keep expensive state changes to a minimum (primitive, shader, texture, shader constant, etc.).

As for rendering opaque objects front-to-back (with depth testing enabled): If your pixels are expensive to compute (read: complex pixel shaders), then not having to compute the same pixel multiple times can be an enourmous gain - which gives rise to the idea of an early depth-only rendering pass (Z-Pre-Pass).

# Answer
> 3 votes
If you can render your opaque pass front to back then you are probably fine, but for a lot of scenes this might not be worth the processing time. What people usually to is render a Z-only pass to fill the Z-buffer, and then render opaque with optimized state changes to only render visible pixels. Transparent can then be rendered back to front.

It's all up to the scene and render layout. Check performance counters before trying to optimize.

# Answer
> 2 votes
http://developer.nvidia.com/docs/IO/8230/BatchBatchBatch.ppt is a great presentation by NVIDIA on batching costs.

On the first slides it says that the wisdom that state changes are expensive is wrong. Its about how many batches you have.

Its not the state that goes with each batch, its the batch itself that costs. So how might you put lots of objects into a single batch? (slide 30 onwards...)

---
Tags: rendering, state
---


# Question
Title: Need help in determing what, if any, tools can be used to create a free Flash game
Yes I proudly -and sadly- declare that I am a complete nincompoop when it comes to Flash, and I have been fishing around the big wide web for information. The reason for this is that I have been contracted to create a game(s) for a website -the usual flash-based games caveat. Please I do not mean things like by those gaming generator websites, I mean small yet professional games- but the caveat, as always, is that impossible dream: it needs to be done all for free. The budget...well imagine it as not there.

Annoyingly is that I am a game designer yes, but with a ridiculously tight deadline I haven't got much time to re-learn (ah the heady days of programming at uni) everything by the end of March, so I'd like to ask some people who know their stuff rather than keep looking at a gazillion different things.

This is my understanding: with the flash sdk you can create a game, albeit you need to be pretty programming savvy. FlashDevelop helps there -yet I am not entirely sure how. Yet even FD says to use Flash for the animation/graphics.

Yes its undeniably powerful but as I said there is the unattainable demand of no money. The million dollar question: what, if any, tools can I use to create a free flash game?

# Answer
> 3 votes
This question pretty much covers the software part.

Then I suggest you use a framework like Flixel or Flashpunk for your game as it will allow you to:

1. Build a game rather quickly and...
2. Doesn't require Flash IDE to create graphics, since these engines are Bitmap based (so you could use GIMP or other image editing software to create your sprites).

# Answer
> 1 votes
i have been there. we knocked out a simple flash platform ages ago as2 back in the day. i would recommend the same engine but they never updated to as3 :( but it did save a lot of time.

so in short find a few game engines i listed to below take a quick look at the tutorials of each and then glance their api's. once you have found one you like batter down the hatch get the coffee brewing and go for it.

http://pushbuttonengine.com/

flixel(dot)org (i am only allowed to post two links cause i am noob)

both those engines are free.

next comes creative. I would hope they at least sources you the assets are got you a designer if. Maybe you can do it your self. if not you can get assts from the link bellow double check the licence for each though its always tricky when making a commercially funded game :) prroz the internet you can get some cheap game assts too that are quite nice and with a few little amends they can become quite uniques if you dont mind a little pixel pushing :)

http://funplosion.com/free-assets.html

as for for the development environment using the flash IDE will make bundling up the assets easier but it is not essential. the engine would normally handel most of the animations and you can bundel the assets using the free flex compiler it would just take a little more time.

personally if i had any money at all after buying assets i would spend it on flash then if there was any money left after that FLash Builder and if by some miracle i had any money left i would get the FLash Builder plugin Source Mate. If you are unsure about any of these applications you could try them you can normally get 30day free trials to give them a whirl before you buy

well good luck :)

---
Tags: flash, tools, actionscript
---


# Question
Title: Looking for JMonkeyEngine tutorials and documentation
I'm looking for tutorials and documentation for JMonkeyEngine, beside the material on the official website. Any clue?

# Answer
Although mostly from the official site, I thought it was important to mention them as they have a lot of good tutorials.
> 8 votes

# Answer
I found this:

http://www.theprogrammersweblog.com/2008/12/3d-game-programming-in-java-using.html

Pretty interesting, even if incomplete for the moment.
> 1 votes

# Answer
Try the wiki:

http://jmonkeyengine.org/wiki/doku.php
> 1 votes

# Answer
Although not exactly the same technology you might want to check out the lightweight java game library at http://lwjgl.org/ as there seems to be a fair amount of tutorials on it.
> 0 votes

---
Tags: java, jmonkeyengine
---


# Question
Title: Which university shall I choose in UK? ( game programming )
I'm starting my undergraduate studies soon, but as I'm not from UK, I completly don't have idea what university should I choose.

Do you know any good game programming universities?

---

Is it good idea to make computer science as undergraduate studies and game-programming as postgraduate one? I'm thankfull for all your replies, as they help me alot.

# Answer
When I think of people I've interviewed that have done games courses, the one that sticks in my mind is Abertay (in Scotland).

That said, I have to agree with U62. Doing a games course doesn't mean you'll come out the other side and fall into a job in games. I've interviewed people (and the odd lecturer) who's been on games courses from various institutions and the quality seems to vary wildly. I would expect good games "people" to be good no matter what course they do. I don't think many people I've interviewed and then been offered a job have come from games courses, the majority have done other courses and have a strong love of playing and writing games, with them being able to demonstrate this love via some sort of game related demo.
> 5 votes

# Answer
A game development degree might be more fun for you to take, but if you talk to anyone in the industry that hires programmers they will all tell you that they'd rather hire a programmer with a good Computer Science, Maths or Physics degree than someone who did a game development degree. There are plenty of online resources that will help you find out which UK universities have good CS departments.
> 5 votes

# Answer
If you're really focused on game development then a course specific to that may be right up you street. There are a lot of skills you'll learn that are specific to games development that you'll be unlikely to learn anywhere else: directx, opengl, etc. You'll also gain an understanding that there can be a lot of people involved: story writers; level designers, programmers, testers, etc. and possibly be given the chance to focus on a specific area that interests you.

However it may be worth considering a more general computer science route. Although you'll miss out on the specific skills of game development, you'll arguably get a better grounding in core development and gain more general skills that you can apply to a wider range of problems.

Only you can decide what you want to study. Studying either course will not limit you to working in or out of a specific industry, but it may make it more difficult to change course.

With that piece of advice out of the way, onto answering your specific question:

There is a broad opinion that the University of Abertay is one of the foremost institutions for studying game development in the UK. Abertay had the foresight to build and develop a top level course specializing in game development before others and it's continued to build on it.

Dundee (where the university is based) has a thriving game development industry that has sprung up partly because of the courses. Games like GTA4 (amongst many others) were developed in the area. That should give you an indication of the community that's built up.
> 1 votes

# Answer
I'm looking at the moment to start next year and the two best choices I've seen are Abertay in Scotland and Derby in the midlands. I haven't been to see Abertay yet but as far as I've heard it has been given a LOT of money by the government to help supply the course with development kits and engines and the like, but it does not do a placement year, which I see as being worth much more than just having slightly better computers as then you get to work with other people and see how the professionals do it.

Derby, however, though it has less money it still has decent facilities (about 20 PSP development kits, large dual screen monitors on each computer, up to date specs and the like) and it also aims to get all of it's students into a relevant placement after their second year for a year.

Hope that helps you make a decision :)
> 0 votes

# Answer
If I were looking at UK universities for game programming courses, I'd probably look at Essex. After all, they have Richard Bartle there.
> 0 votes

---
Tags: education
---


title: Best way to do large XNA animations?

text:
# Question
Title: Best way to do large XNA animations?
What's the best way to have large animations in XNA 4.0? I have created a spritesheet with the sprite being 250x400 (more of an image than a sprite but hey ho) and there are approximately 45 frames in the animation. This causes problems for XNA as it says that the maximum filesize for Reach is 2048.

I'd rather not change to hidef as I heard that means that your game is less compatible with some computers and systems so does anyone have any idea what the best thing I could do is? The only thing I could come up with is to have a list of textures to flick through but that's not ideal.

# Answer
Since you wont answer my comment above I will give you a few options.

1 . Use a tilesheet that spans multiple Textures.

2 . Use a

```
List<Texture2D>

```

You can make this easier by making a png sequence with BigImage0001,BigImage0001,BigImage0001....

Import all of those.

Make a method that takes a name, Trailing numbers, and total frames. Have it return the built list of textures.

..

..

Use 1 if you have a lot of instances of the animation, that are playing at different frames, as it will reduce the amount of SpriteBatch calls XNA has to process.

Use 2 if you have a small amount of instances, it will reduce video memory consumption, but each instance more will increase the SpriteBatch calls.
> 5 votes

# Answer
Basically if you are targeting towards Direct9 then you can't use HiDef. You could always create a smaller animation and just set the scale to a higher amount(allowing it to zoom in on the image), if its a vectors image it won't skew the image.
> 4 votes

---
Tags: xna, animation, sprites, spritesheet
---


# Question
Title: Associate a texture to an object (from a data-model, not graphical point of view)
I'm writing a roguelike where objects and floor can be made of different materials. For instance, let's say we can have a wooden chair, an iron chair, a golden chair, and so on.

I've got an Object class (I know, the name is terrible), which is more or less using a composite pattern, and a Material class. Material have different important properties (noise, color...). For the time being, there are 5 different instances of materials, created at the initialization of the game.

How would connect an instance of Object with one of the 5 instances of materials ? I see three simple solutions :

* Using a pointer. Simple and brutal.
* Using an integer material-id, then get the materials out of a table when engine manipulates the object for various purposes (display, attack analysis, etc.). Not very beautiful, I think, and not very flexible.
* Using an integer material-id, then get the materials out of a std::map. A bit more flexible, but still not perfect.

Do you see other possibilities ? If not, what would you choose (and why) ? Thanks in advance !

# Answer
It seems you want new types of Materials to be able to be created at runtime. Then I don't see the problem with having a pointer to the Material of the object; it's how I would do it. Perhaps elsewhere in the program (e.g. in the factory class which creates these Object instances) you would have an array of all the Materials, to keep track of them and allow for choosing between them. Also you would need to either never delete a Material once it's created, or keep track of the references to a material so that if you want to delete the material then you reassign new materials onto all the objects which were previously using that material. You certainly don't want to `delete` a Material in memory, only to have Objects still pointing to that memory location which is now invalid!

The problem with the integer ID which is a position of an array, for example, is if that array is manipulated, for example if a material is deleted, then you need to either put a 'null' in that position and never use it again, or you need to loop among the objects and change their material ID when you change the array. So for example if you have three materials, and an object points to material 1, then if you delete material 1 you need to either put a null in that place, or change the object id to e.g. -1 before you allocate a new material in position 1 (or else the object is magically given a new material!).

Also an std::map seems like unnecessary overhead in this case. It seems to me that you don't really need the map when you could use a pointer and reference counting as mentioned above. You could certainly use it though, keeping in mind similar downfalls such as mentioned in the previous paragraph; e.g. you still need to make sure the IDs are unique among all materials deleted or not, or else you could get objects whose materials get reassigned just because the material gets deleted and a new one gets put in with the same ID as the old one.

If however Materials can't change at runtime, you could of course make an enum with the material type, and the object would have an element of that enum (or a pointer to that element; my c++ is rusty).
> 2 votes

# Answer
Use the pointer. You haven't identified any requirements of the system beyond that you should be able to go from Object to Material, and the pointer is the simplest and most direct approach by some way.
> 3 votes

# Answer
From my point of view, array indices and pointers are two flavors of the same thing -- and both are simple and direct, which is good for a game.

You could introduce an abstraction layer, and make this more complicated, but you have not identified any requirements to help design such a layer.

In fact, as near as I can tell, you only have 5 materials, and they will not change.

Anyways, I see nothing wrong with using a pointer, and I see nothing wrong with using an array index. If you do see something wrong with either of those, I think that that means you have requirements which you have not expressed here.
> 1 votes

# Answer
The OO way to do it is to create each new object with a material and colour as *properties* by instance passing. For example in Python:

```
class Chair(Object):
    def __init__(self, colour, material, position):
        self.colour = colour
        self.material = material
        self.position = position
    ...

```

You would then create the object with those properties:

```
chairmaterial = Material("wood")
mychair = Chair(COLOUR_GREEN, chairmaterial, (0,0))

```

Rendering could then just be dependent on the Chair class for shape, and the material and colour for colour and texture.
> 1 votes

---
Tags: c++, data-structure
---


# Question
Title: Are there any good blogs or articles on the business of indie games?
Interested in both successes and failures (and semi-successes).

Maybe this might be better at OnStartups but I think the game market is quite a bit different than the business market that's prevalent there (i.e. selling something that's fun instead of selling something that's useful)

# Answer
Cliffski's Blog is really great, he goes into all aspects of indie developement. Check it out.
> 3 votes

# Answer
I really like Struct.ca (Matt Rix). He was really successful with his Trainyard game and shared lots of interesting sales and marketing related facts on his blog.
> 1 votes

# Answer
http://gamesfromwithin.com/ Noel Llopis' blog on iPhone and indie gamedev is top notch in every aspect.

http://gbgames.com/blog/ Reflects a lot on the technical and financial issues associated with someone's first indie title.

I can highly recommend the both of them.
> 1 votes

# Answer

> 1 votes

# Answer
Not a blog, but a subreddit: Marveloper
> 1 votes

---
Tags: business
---