# Question
Title: My frustum culling is culling from the wrong point
I'm having problems with my frustum being in the wrong origin. It follows the rotation of my camera but not the position.

In my camera class I'm generating a view-matrix:

```
void Camera::Update()
{
    UpdateViewMatrix();

    glMatrixMode(GL_MODELVIEW);
    //glLoadIdentity();
    glLoadMatrixf(GetViewMatrix().m);
}

```

Then extracting the planes using the projection matrix and modelview matrix:

```
void UpdateFrustum()
{
    Matrix4x4 projection, model, clip;

    glGetFloatv(GL_PROJECTION_MATRIX, projection.m);
    glGetFloatv(GL_MODELVIEW_MATRIX, model.m);

    clip = model * projection;

    m_Planes[RIGHT][0] = clip.m[ 3] - clip.m[ 0];
    m_Planes[RIGHT][1] = clip.m[ 7] - clip.m[ 4];
    m_Planes[RIGHT][2] = clip.m[11] - clip.m[ 8];
    m_Planes[RIGHT][3] = clip.m[15] - clip.m[12];
    NormalizePlane(RIGHT);

    m_Planes[LEFT][0] = clip.m[ 3] + clip.m[ 0];
    m_Planes[LEFT][1] = clip.m[ 7] + clip.m[ 4];
    m_Planes[LEFT][2] = clip.m[11] + clip.m[ 8];
    m_Planes[LEFT][3] = clip.m[15] + clip.m[12];
    NormalizePlane(LEFT);

    m_Planes[BOTTOM][0] = clip.m[ 3] + clip.m[ 1];
    m_Planes[BOTTOM][1] = clip.m[ 7] + clip.m[ 5];
    m_Planes[BOTTOM][2] = clip.m[11] + clip.m[ 9];
    m_Planes[BOTTOM][3] = clip.m[15] + clip.m[13];
    NormalizePlane(BOTTOM);

    m_Planes[TOP][0] = clip.m[ 3] - clip.m[ 1];
    m_Planes[TOP][1] = clip.m[ 7] - clip.m[ 5];
    m_Planes[TOP][2] = clip.m[11] - clip.m[ 9];
    m_Planes[TOP][3] = clip.m[15] - clip.m[13];
    NormalizePlane(TOP);

    m_Planes[NEAR][0] = clip.m[ 3] + clip.m[ 2];
    m_Planes[NEAR][1] = clip.m[ 7] + clip.m[ 6];
    m_Planes[NEAR][2] = clip.m[11] + clip.m[10];
    m_Planes[NEAR][3] = clip.m[15] + clip.m[14];
    NormalizePlane(NEAR);

    m_Planes[FAR][0] = clip.m[ 3] - clip.m[ 2];
    m_Planes[FAR][1] = clip.m[ 7] - clip.m[ 6];
    m_Planes[FAR][2] = clip.m[11] - clip.m[10];
    m_Planes[FAR][3] = clip.m[15] - clip.m[14];
    NormalizePlane(FAR);
}

void NormalizePlane(int side)
{
    float length =  1.0/(float)sqrt(m_Planes[side][0] * m_Planes[side][0] +
                                m_Planes[side][1] * m_Planes[side][1] +
                                m_Planes[side][2] * m_Planes[side][2]);

    m_Planes[side][0] *= length;
    m_Planes[side][1] *= length;
    m_Planes[side][2] *= length;
    m_Planes[side][3] *= length;
}

```

And check against it with:

```
bool PointInFrustum(float x, float y, float z)
{
    for(int i = 0; i < 6; i++)
    {
        if( m_Planes[i][0] * x + m_Planes[i][1] * y + m_Planes[i][2] * z + m_Planes[i][3] <= 0 )
        return false;
    }
    return true;
}

```

Then i render using:

```
camera->Update();
UpdateFrustum();

int numCulled = 0;

for(int i = 0; i < (int)meshes.size(); i++)
{
    if(!PointInFrustum(meshCenter.x, meshCenter.y, meshCenter.z))
    {
        meshes[i]->SetDraw(false);
        numCulled++;
    }
    else
        meshes[i]->SetDraw(true);
}

```

Matrices look like (Camera is at (5, 0, 0)):

```
ModelView
[0,0,0.99,0] [0,1,0,0] [-0.99,0,0,0] [0,0,-5,1]

Projection
[0.814,0,0,0] [0,1.303,0,0] [0,0,-1,0] [0,0,-0.02,0]

Clip
[0,0,-1,-0.999] [0,1.30,0,0] [-0.814,0,0,0] [0,0,4.98,4.99]

```

What am I doing wrong?

# Answer
It appeared that the points i were testing against had not been scaled, while the render code had. So it was working all along, but the change was too small to see!
> 2 votes

# Answer
```
  makePlane(m[3]+m[0],m[7]+m[4],m[11]+m[8],m[15]+m[12]); // left plane

  function makePlane(a,b,c,d) {
      s=1.0/Math.sqrt(a*a+b*b+c*c);
      return [a*s,b*s,c*s,d*s]
      // NOT return [a/s,b/s,c/s,d/s]  ...
  }

```

BTW, if you are only clipping single points, then a more efficient method is to calculate \[x,y,z,1\] * clip\_matrix -\> \[X,Y,Z,W\] and to check that |X|\<|W|, |Y|\<|W|,|Z|\<|W|.

I'm justifying using 'makePlane' approach because I cull axis aligned bounding boxes and have something more in the makePlane routine that makes the frustumCulling function to choose a single corner of the boundingbox per clipping plane.
> 0 votes

---
Tags: culling, frustum
---


# Question
Title: how to render small texture on another texture?
can anybody help me to render small texture on another texture. i.e I have one background image, when user touches on the screen it should draw small(circle or any object) on it.

can anybody suggest me good tutorial to starts with it?

# Answer
It's called off-screen rendering. In OpenGL you perform normal rendering, but into another render target where you have bound texture which you want render to.

There's wiki documenting it very well, especially this section. It has example for both OpenGL ES1, ES2.
> 3 votes

# Answer
You can bind the background as a render target, and then render the circle onto it. And the next time you want to render a circle onto it, you bind it, but don't clear the colorbuffer, just draw the circle again.
> 0 votes

---
Tags: android, opengl-es, opengl-es2
---


# Question
Title: How do you deal with transitions in animating walking?
I'm pretty new to this whole animating models thing. Just learning the ropes. I got a nice walking animation going, which I can loop while a character is walking, but what about when they stop walking?

I mean, they could be at any point in the animation at the time the player stops walking. How do I get them to smoothly return to a standing still position without having them snap into that position? The same goes for starting walking from a standing still position. Do you need a separate animation? How is this dealt with?

# Answer
You can have different levels of complexity depending on the degree of realism you want.

1. Simply blend (= interpolate) from the walk to the stand animation when the character stops walking, and vice versa when the character starts.
2. Let the walk animation rate depend on the character speed, this way the walk animation will slow down prior blending to the stand animation.
3. Use transition animations: stand-to-walk is an easy one, just play it before your walk animation starts.
4. Getting a walk-to-stand transition to work is a bit trickier, you'll have to know where your character is is his walk cycle, and wait for him to reach the transition point. And/or have several walk-to-stand animation that start at a different walk cycle point and trigger the right one when motion stops, probably with a bit of blending as well.

This goes on and on, you can consider using IK to snap feet to the floor, use human body physics for an even more realistic-looking motion, etc. This is really a question of artistic direction, and of how much time you can spend on this.

One thing for sure: if you want to experiment on all this easily, implement first a good data-driven animation system.
> 9 votes

# Answer
Just like you interpolate between the key frames of the walk animation, you could interpolate between standing pose and the frame when walking stopped. You can also let the walk animation play into the frame that is closest to the standing pose, though you probably need to let the character still move a bit then.
> 1 votes

---
Tags: animation
---


title: HTML5 game programming style

text:
# Question
Title: HTML5 game programming style
I am currently trying learn javascript in form of HTML5 games. Stuff that I've done so far isn't too fancy since I'm still a beginner. My biggest concern so far has been that I don't really know what is the best way to code since I don't know the pros and cons of different methods, nor I've found any good explanations about them. So far I've been using the worst (and propably easiest) method of all (I think) since I'm just starting out, for example like this:

```
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 640;
var height = 480;
var player = new Player("pic.png", 100, 100, ...);
also some other global vars...

function Player(imgSrc, x, y, ...) {
   this.sprite = new Image();
   this.sprite.src = imgSrc;
   this.x = x;
   this.y = y;
   ...
}
Player.prototype.update = function() {
    // blah blah...
}
Player.prototype.draw = function() {
    // yada yada...
}

function GameLoop() {
   player.update();
   player.draw();
   setTimeout(GameLoop, 1000/60);
}

```

However, I've seen a few examples on the internet that look interesting, but I don't know how to properly code in these styles, nor do I know if there are names for them. These might not be the best examples but hopefully you'll get the point:

1:

```
Game = {
   variables: {
      width: 640,
      height: 480,
      stuff: value
      },
   init: function(args) {
      // some stuff here
      },
   update: function(args) {
      // some stuff here
      },
   draw: function(args) {
      // some stuff here
      },
};
// from http://codeincomplete.com/posts/2011/5/14/javascript_pong/

```

2:

```
function Game() {
    this.Initialize = function () {

    }
    this.LoadContent = function () {
        this.GameLoop = setInterval(this.RunGameLoop, this.DrawInterval);
    }

    this.RunGameLoop = function (game) {
        this.Update();
        this.Draw();
    }

    this.Update = function () {
        // update
    }

    this.Draw = function () {
        // draw game frame
    }
}
    // from http://www.felinesoft.com/blog/index.php/2010/09/accelerated-game-programming-with-html5-and-canvas/

```

3:

```
var engine = {};
engine.canvas = document.getElementById('canvas');
engine.ctx = engine.canvas.getContext('2d');

engine.map = {};
engine.map.draw = function() {
    // draw map
}

engine.player = {};
engine.player.draw = function() {
    // draw player
}
// from http://that-guy.net/articles/

```

So I guess my questions are:

* Which is most CPU efficient, is there any difference between these styles at runtime?
* Which one allows for easy expandability?
* Which one is the most safe, or at least harder to hack?
* Are there any good websites where stuff like this is explained?

or...

* Does it all come to just personal preferance? :)

# Answer
> 5 votes
In JavaScript, functions can imitate classes. In my opinion, they're more logical than classes too.

To have a function imitate a class (be a constructor function), you need to use the `this` and `new` keywords. `this` refers to the object being created by the function, so if you write `this.a = 5` inside the function, your newly created object will have a property `a` with the value of 5. `this` in JavaScript is analogous to `this` in C++ or `self` in Python or Java.

The `new` keyword is used when instantiating objects. `var obj = new Class()` instantiates a new object of type `Class`, and assigns a reference to it in the `obj` variable.

However, there is one important thing you should know. If you assign functions to objects inside the constructor (`this.f = function(){...}`), this will create a new instance of this function for each object, something that isn't very efficient. This is where prototypes come into play.

To demonstrate:

```
var Class = function(a)
{
    this.a = a
    this.b = 34
}

Class.prototype.f = function(a)
{
    return this.a + a //this.a != a!!!
}

var obj = new Class(5)

obj.a //5
obj.b //34
obj.f(4) //9

```

Now, each time you create an instance of Class, and try to call its `f` function, JavaScript will traverse the prototype chain and get to the prototype of `Class`, which does have the `f` function. That's another feature of the `new` keyword, it sets the newly created object's prototype to its class' prototype.

Also, you might want to check out closures, they are much slower than prototyping (did the research myself), but provide a sort of access modification.

Now, to answer your concrete questions...

* Which is most CPU efficient, is there any difference between these styles at runtime?

Depends on the implementation, but you want to go with the prototypes (as you are doing).

* Which one allows for easy extensibillity?

Well, you can add anything you want to any object, really, but I suggest that you don't go with the singleton pattern. It's generally not a very good thing to have objects in global scope in JavaScript, and even the pattern itself has some issues.

* Which one is the most safe, or at least harder to hack?

As I said in the comment, you shouldn't care about this. Anyone can fire up a console and mess with your game. JavaScript wasn't built for safety, heck, clients are inherently unsafe, so you'll need to implement such stuff on the server.

* Are there any good websites where stuff like this is explained?

Sure:

codeproject.com/Articles/247241/Javascript-Module-Pattern
developer.mozilla.org/en-US/docs/Canvas\_tutorial
stackoverflow.com/questions/4650513/why-is-javascript-prototyping
codethinked.com/preparing-yourself-for-modern-javascript-development
addyosmani.com/resources/essentialjsdesignpatterns/book/ (You simply must read this.)
javascriptpatterns.org/
nodejs.org/ (For JavaScript servers.)
socket.io/ (For multiplayer.)

# Answer
> 2 votes
Their are indeed differences between these at runtime.

1. In OOP terms, this is directly an instantiated object, or if you prefer this is a singleton. If you want more instances of those you'll have to clone that object but this isn't native in JavaScript.
2. This is probably the most common way to define a class. This allows creating as many instances as necessary using `var game = new Game();`. The drawback is that your class methods are duplicated each time you create a new instance, this can become a concern if you need a lot of them. A workaround is to add methods to the class prototype, as you're doing yourself for your `Player` class.
3. This is virtually the same thing as option 1., except the object is defined bit by bit instead of all at once.

You could check this blog entry for details.

So for a game, the best is probably to use what you've used for your `Player` class, and maybe use option 1. or 3. for singletons. Another option might be to use a proper OOP language and compile it to JavaScript.

# Answer
> 2 votes
there is no fit-all answer. Search the web for "javascript patterns" and you will find great resources. Invest the time in this before you get too far into things.

On suggestion that I can make - we used the "Self-Executing Anonymous Function" in this article http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ to hide private members and that worked out well for us. we have, of course, spent significant amount of time researching and experimenting and arrived at this as the best option after 2 months of development, so do your homework as well

If you want to mimic OOP, i suggest you look into higher level languages like typescript or others or you will be doing a lot of boiler plate/pluming code that makes the code hard to read and error prone

Here is an example of our code. these are not classes/objects in OOP sense, they are more like namespaces, or singletons

```
(function (ROE) {
} (window.ROE = window.ROE || {}));

(function (obj) {

    var CONST = { popupName: "Building" },
        CACHE = {};

    CONST.Enum = {};

    CONST.Enum.CanUpgrade = {
        Yes: 0,
        No_LackFood: 1,
        No_LackSilver: 2,
    };

    var _load = function () {
    }

    var _showBuildingPagePopup = function (buildingID) {
    }

    //public function definition
    obj.showBuildingPagePopup = _showBuildingPagePopup;

} (window.ROE.Building = window.ROE.Building || {}));

```

---
Tags: software-engineering, javascript, html5, html-canvas
---


# Question
Title: In a Tower defense game, how to do buffs/debuffs
The question is at the very bottom. If you understand Buffs/Debuffs in tower defense games then you should skip the bulk of this question and go to the bottom (seperated with the long line)

I plan on making an IPhone TD game. The fact that its an iPhone game isn't relevant but I am coding in Objective-c with Cocos2D.

I am relatively inexperienced in the field of game design so I'm looking for some advice from someone experienced in this field.

In tower defense, there are two things that are relevant to my question: towers/enemies (both have their own classes/children). They each have stats like hp, damage, speed, etc.

I want to add buffs/defuffs, for instance: Towers A,B and C each have 15 base damage. Tower D would be a buff tower with no damage, a tower with an AOE(area of effect) aura that gives 10% damage to all towers in range. Tower E might slow enemies in its AOE, a debuff. Stuff like that.

The same could go for enemies. Enemy A is a boss that has a slow aura that affects towers and slows their base attack speed or something along those lines.

---

So the question is, what would be the most effective way to implement this? If it was just towers then I would just mess around with the tower classes, but since tower classes and enemy classes are both affected, should I make a buff class?

TD games can consume quite a bit of memory with large amounts of creeps and towers, and buffs I feel like would also consume quit a bit... So I'm trying to be as effective as possible.

# Answer
> 5 votes
I would represent Buff/Debuff effects with a single class like this:

```
public class Buff
{
    public BuffType BuffType;
    public float Value;  //The bonus percentage, for example: -12.5 or 25
}

enum BuffType
{
   Speed, FireDamage, ColdDamage, Range //etc.
}

```

Each and every Tower and Creature instance has a property `public List<Buff> CurrentBuffs;` . If a buff tower affects a creature / other tower, it adds (or updates) an item in the `CurrentBuffs` list.

In each update, you calculate which buff towers affect which creatures / towers. This way, you fill the `CurrentBuffs` list of every such entity. Then you use the list to calculate the accumulated bonuses, which will affect the actual mechanics of the entity.

You might not need to do this in every update: For towers affected by buff towers, you only calculate this when a tower is placed / destroyed / upgraded.

# Answer
> 1 votes
You can calculate the list of Towers than a Tower D affect in the moment you build it, or when other towers are built in its area of effect.

In memory you will have something like:

```
t1( TowerA ) {...}
t2( TowerB ) {...}
t3( TowerA ) {...}
t4( TowerB ) {...}
t5( TowerD ) {... affects: [t2,t4] ...}

```

And apply the buff/debuff only when it changes /or at the beggining of the frame update.

---
Tags: platformer, tower-defense
---


# Question
Title: Scene graphs and spatial partitioning structures: What do you really need?
I've been fiddling with 2D games for awhile and I'm trying to go into 3D game development. I thought I should get my basics right first.

From what I read scene graphs hold your game objects/entities and their relation to each other like 'a tire' would be the child of 'a vehicle'. It's mainly used for frustum/occlusion culling and minimizing the collision checks between the objects.

Spatial partitioning structures on the other hand are used to divide a big game object (like the map) to smaller parts so that you can gain performance by only drawing the relevant polygons and again minimizing the collision checks to those polygons only. Also a spatial partitioning data structure can be used as a node in a scene graph.

But... I've been reading about both subjects and I've seen a lot of "scene graphs are useless" and "BSP performance gain is irrelevant with modern hardware" kind of articles.

Also some of the game engines I've checked like gameplay3d and jmonkeyengine are only using a scene graph (That also may be because they don't want to limit the developers). Whereas games like Quake and Half-Life only use spatial partitioning.

I'm aware that the usage of these structures very much depend on the type of the game you're developing so for the sake of clarity let's assume the game is a FPS like Counter-Strike with some better outdoor environment capabilities (like a terrain).

The obvious question is which one is needed and why (considering the modern hardware capabilities).

Thank you.

# Answer
> 13 votes
> It's mainly used for frustum/occlusion culling and minimizing the collision checks between the objects.

Not true. It's mainly used for programming convenience and hierarchial animation. There is no way culling and collision checks benefit from scene graphs. Quite the opposite, actually, since it's required to calculate and cache the world space data before doing everything else. Bounding volume hierarchies are what you need for culling and collisions, if anything.

> I've seen a lot of "scene graphs are useless" and "BSP performance gain is irrelevant with modern hardware"

Both are true for simple games, false otherwise. BSP or any other spatial partitioning / bounding volume hierarchy (both are almost the same) system can significantly reduce the time it takes to process things. As for scene graphs, once you want a character that has all kinds of things attached to it or at least, relative object positions in world (light attached to a moving lamp, for example), you'll see that they become useful. Only as far as rendering is concerned, though - physics always has a somewhat flat "scene graph" (sometimes even cyclic, so the DAG (tree) structure of a scene graph isn't useful).

> let's assume the game is a FPS like Counter-Strike with some better outdoor environment capabilities

I'd say you need all of them here, and some more. Bounding volume hierarchy (like BSP or octree), perhaps portal culling too for the static parts of the world, occluder volumes (antiportals in Unreal Engine) for terrains and a scene graph for compound objects (lamps, characters, doors etc.).

# Answer
> 8 votes
Neither is **needed**.

The choice of scene graphs or spatial partitioning or both is a matter of optimisation. And until you have a functioning game, you have nothing to optimise. So obsessing over this sort of detail now is counter-productive to the creation of your game.

My advice: make the game, then measure which bits of it are slow, and finally fix the slow bits. If you start by trying to guess what's going to be slow and obsessing over doing everything in the "right" or the "best" or the "fastest" way before actually having made the game, then you'll never finish.

# Answer
> 7 votes
I tend to disagree with Trevor Powell's answer as there are clearly two different kinds of optimization here. One is optimization after the fact and to make the slow parts go fast, which is what he has touched on, but the other is designing your data structures and flow control to be at least reasonably efficient and sensible in the first place.

The second is the type solved by any spatial partitioning scheme, and if you try to retrofit that on a design that's not built around it, you'll likely make a huge mess and risk ending up even slower.

Premature optimization may be the root of all evil (but don't forget the crucial 3% that Knuth also mentioned) but not optimizing at all is the root of Neverwinter Nights 2.

---
Tags: scene-graph, octree, binary-space-partitioning, bsp-tree, kd-tree
---


title: Separate collision mesh model?

text:
# Question
Title: Separate collision mesh model?
I want to have another go at 3D within XNA. What I have seen from some other games that they just have a separate very low poly model "cage" around the environment model. However I can not find any reference to this. I have not that much experience with XNA 3D either.

Is it possible to have this cage within each of my environmental models already? Lets just say I call the mesh within the .FBX wall and col\_wall. How would I call to these different meshes within XNA?

The player would just have a tight collision cube around. To make it a bit more efficient I will be making divide the map up by cubes and only calculate collision if the player is in it.

Question two: I can't find anywhere to do cube vs mesh collision. Is there a method for this? Or perhaps it is possible to build my collision cage out of cubes in the 3D app and on loading of the models in XNA replace them directly by cubes? So I could just do box to box collision which should be very cheap and still give the player the ability to move over ledges on the static models.

# Answer
> 3 votes
XNA, as far as I know, contains no built-in code to collide `ModelMesh` objects. If you want to collide an arbitrary mesh, you will need to write that code yourself-- not an enviable task if you ask me.

The only built-in collision abilities I'm aware of in XNA are `BoundingBox`, `BoundingSphere`, and `Ray`. All three of these structs have built-in methods to collide with each other.

I believe common practice in XNA 3D development is to use your `ModelMesh` for rendering and create a separate set of `BoundingBox`es and `BoundingSphere`s as a collision model. I'd probably create a container class for `BoundingBox` and `BoundingSphere` called `BoundingPrimitive` and expose the `Intersects` method (it's a little lame that `BoundingBox/Sphere` don't inherit from the same object, making generic collision structures a bit more difficult). Something like this maybe:

```
public class BoundingPrimitive
{
    BoundingSphere? sphere;
    BoundingBox? box;

    public BoundingPrimitive(BoundingBox b) { box = b; }
    public BoundingPrimitive(BoundingSphere s) { sphere = s; }

    public bool Intersects(BoundingPrimitive other, Matrix myWorld)
    {
        if (box.HasValue)
        {
            //a world transformation must be made to translate the bounding structure
            //to world space (it should be created in local space of the object
            //whose collision cage it represents)
            return box.Value.Transform(myWorld).Intersects(other.box.HasValue ? other.box : other.sphere);
        }
        else if (sphere.HasValue)
        {
            return sphere.Value.Transform(myWorld).Intersects(other.box.HasValue ? other.box : other.sphere);
        }
        else
        {
            throw new InvalidOperationException("This BoundingPrimitive contains no bounding structure!");
        }
    }
    /*there are probably some Intersects overrides to also expose*/
}

```

So, then create a collision structure for each object with a `ModelMesh` in which you manually define an array of these `BoundingPrimitive`s to abstract the model's collision 'cage'. This can be done at your discretion. We can call this collision structure `Collider`. `Collider` will have its own `Intersects` method, which takes another `Collider` as a parameter. Then it compares its array of `BoundingPrimitives` to the other's and tests for collision between them. That's kind of an expensive operation as the number of bounding structures per object increases, so you could probably optimize that somewhere, or use a small number of bounding structures to abstract the collision cage.

So this is my best answer for you, I'm sure some of the wiser XNA gurus may have a bone to pick with it.

The main thing to keep in mind is that XNA is not an engine, it's a framework. You don't really get much physics or collision for free. You'll need to come up with the appropriate models, structures, algorithms and resolutions yourself.

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


# Question
Title: InvalidCastException in Farseer's raycasting when trying to use the built-in explosion class?
I'm trying to create an explosion at the point that two entities collide, but whenever explosion.Activate() is called, it causes an InvalidCastException to be thrown in Raycast(), on the line that returns the callback.

`return callback(fixture, point, output.Normal, fraction);`

Is this a bug in Farseer, or am I doing something wrong? It doesn't appear to be a known issue.

# Answer
I was passing a non-integer value into UserData. The built-in Explosion class relies on it being an integer.
> 1 votes

---
Tags: xna, c#, farseer-physics-engine
---


# Question
Title: What programming language were PS1 games written in?
Is there any common language that is used to create Play Station 1 Games? Or how can I find out what programming language is used for one of those games?

# Answer
> 27 votes
Most PS1 games were probably written in C, with some assembly and possibly some light "C with classes." This isn't a universal truth, necessarily -- for example Crash Bandicoot had a good portion of its gameplay logic built in a LISP variant.

In general, you can only find out what languages were used for a game by asking the developers of that game. However, some technologies leave tell-tale signatures or watermarks of a sort that can help you make educated guesses.

For native languages, certain compilers or linkers may leave signature patterns or whatnot in the final binary (for example a tendency to store static data at a particular address, or a certain pattern of bootstrapping machine code instructions for the binary. On the PC, you can often run tools like Dependency Walker against an executable to see which runtime libraries it links against, and from there make educated guesses about which compiler was used to build it.

Similarly, games build in managed languages will require their runtime environments and usually complain loudly if they aren't found when the program is launched (this complaint is usually accomplished via a small bit of native bootstrap code in the executable, which you could also look for if you were so inclined.

Of course, this information is generally of little practical utility, since it doesn't really help you solve any particular problems related to your own game in most cases.

# Answer
> 17 votes
I was first party at SCEA when we launched the PS1, and the overwhelming majority of games were written in C, with some time critical bits in assembler. All of the library calls were C as well.

---
Tags: software-engineering
---


# Question
Title: How do graphics evolve so much on the same console hardware?
Is it only a matter of code optimization?

Do game developers plan to start small on a new hardware, to have space to evolve while creating a series of that game?

Are computer graphics breakthroughs common enough to happen in a console lifetime?

# Answer
> 36 votes
> Is that only a matter of code optimization?

There is indeed an optimization part in this. The more programmers get used to a console hardware, the more they learn how to squeeze graphical quality into it.

But it's far from being the only reason:

* Early console titles are developed on evolving hardware and SDKs, so it's hard to get the most out of a platform when it's not yet stabilized.
* Not only the programmers need to adapt to the constraints of a new platform: it's the same for artists. The more mature an engine gets, the more artists can adapt to it and refine their skills. Existence of previous assets that can be iterated on is also something to consider.
* In general, people are more and more experienced, not only artists, not only programmers, but everybody. And team sizes grow, at least on the AAA market. Putting more experienced people in a production, if well managed, leads to more quality.

> Do game developers plan to start small on a new hardware, to have space to evolve while creating a series of that game?

That's an interesting question. I don't think game developers *intentionally* leave space for evolution when working on a new console. To me this is only incidental. But I stand to be corrected, maybe some big studios do this strategically after all, I'd be curious to see any evidence of that (testimony, anybody?).

> Are computer graphics breakthroughs common enough to happen in a console lifetime?

Yes. At least regularly.

# Answer
> 13 votes
> Do game developers plan to start small on a new hardware, to have space to evolve while creating a series of that game?

They most certainly do not!

When I first joined the games industry, I asked a producer from \[giant publisher you've definitely heard of\] this very question. He told me that every console game his company developed used 100% of the platform's available resources. While this was probably not the literal truth, it's close enough.

If anything, console games spend most of their development using closer to 120-150% of the platform resources. The last few months of development are spent frantically trying to crunch everything down to "only" 100% before the ship date. If subsequent titles need more CPU cycles / RAM / disk space / etc., the developers first have to figure out how to optimize their current technology -- find more efficient algorithms, use better data compression, etc. Thus, rapid evolution by necessity!

It makes perfect sense, actually; what competitive advantage would there be in explicitly *not* trying to reach the full potential of the hardware, given your current knowledge of the system? Would you trust your competitors to show the same restraint?

# Answer
> 10 votes
Since Consoles pretty much have one specification. And not like PC where you have tons of different variations. Developers can optimize their games better. But this doesn't mean it will do space magic in the long run. It will reach a cap. ( currently the 360/Ps3 have 512 mb in total, which to many developers seems to be an annoyance)

Consoles are fairly outdated after 6 months. PCs always grow faster in hardware specs. But games on PC never really get optimized for one hardware set. They have to keep in mind that there are also people with lower specs ( hence the video and other options ). But since developers working on console games can optimize in the longrun they can do neat tricks with the hardware.

PS3/360 games look fairly good in this time of their life cycles. But just imagine if a developer focused on one specified powerbeast of a pc.

In the beginning of a new consoles life developers need to adapt to the hardware. You can't just slap code from one platform to the other. That is why you don't see the games we have now in the beginning of the life cycle. The production pipeline grows overtime. It's not something you can get right the first time. A lot of optimizations need to be made and it just costs time. When you see better features in a sequel it's because the development of the technology was growing during the first game.

Real breakthroughs usually happen with new hardware. But developers can be creative at times that allows them to do things on limited hardware.

# Answer
> 9 votes
New hardware generally just offers the ability to do more than before. Most graphical improvements come from new techniques, new optimisations, and better art.

It's worth knowing that the 'new' techniques that get used are rarely new - they are typically 20 year old techniques that previously were too slow for real-time rendering. These typically get translated into real-time code many years later when a programmer finds a way to do it efficiently with the hardware of the day.

---
Tags: hardware, console
---


# Question
Title: How to correct shooting in touch-screen shooting games?
Assume a shooting game for iPhone that the character shoot toward where player has touched.

But as we know, There may be fault in touching screen by player and it conclude to bad game play and low fun.

So, How can I correct shooting method ?

# Answer
> 1 votes
I think when player touch a point, he target some thing that will place in a cone as below picture show.

So, we just need to check collision of objects in this cone, and if any exist, the player most probably decided to shoot at it.

---
Tags: algorithm, software-engineering
---


# Question
Title: C# XNA 2D Multiple boxes collision detection and movement
**Hi,**

I've been making simple game where you shoot boxes that are coming towards you. All game objects are simple rectangles.

Now I have problem with collision detection; how to check where the collision comes so I can change the coordinates right? I have this kind of situation:

https://i.stack.imgur.com/EdTU6.jpg

Imagine that all of those blocks are moving towards you (green box). If those orange boxes collide with each other, they should "avoid" themselves and not go through each other. I have class **Enemy** which has properties **x**, **y** and such. Now I'm doing the collision like this:

```
        // os.Count is an amount of other enemies colliding with this enemy
        if (os.Count == 0) {   // If enemy doesn't collide with other enemy
            lasty = y;
            lastx = x;
            slope = (x - player.x) / (y - player.y);
            x += slope * l; // l is "movement speed" of enemy (float)
            if (y > player.y) {
                y = lasty;
            } else if (y < player.y) {
                y += l;
            }
        } else {
            foreach(Enemy b in os) {
                if (b.y > this.y) {  // If some colliding enemy is closer player than this enemy, that closer one will be moved towards the player
                    b.lasty = b.y;
                    if (!BiggestY(os)) { // BiggestY returns true if this enemy has the biggest Y
                        b.y += b.l;
                    }
                    b.x = b.lastx;
                }
            }
        }

```

But this is **very, very bad** way to do this. I know it, but I just can't figure out other way. And as a matter in fact, this method doesn't even work pretty good; if multiple enemies are colliding same enemy they go through each other.

I explained this pretty badly, but I hope that you understand this.

And to sum up, as I said: ***How to check where the collision comes so I can change the coordinates right?***

# Answer
You could use a physics library such as Box2DX: this would handle the collisions, as well as physics which would make your collisions work/look better.
> 1 votes

---
Tags: xna, c#, 2d, collision-detection, movement
---


title: Depth is disabled - How to turn on?

text:
# Question
Title: Depth is disabled - How to turn on?
In XNA 3.1 is there any other way to disable depth in 3D Worlds using DirectX models other than

```
GraphicsDevice.RenderState.DepthBufferEnable = false;

```

?

The reason for my question is I have quite a huge program which offers a 3D World with a couple of 3D DirectX models inside. Depth was never an issue since it ever worked fine but since a few days after doing some modifications my models are all depth-translucent i.e. depth-buffering and/or culling seems to be disabled.

But in my whole source code I never touch any of the options related to Depth or Culling which means I never turn these settings on explicitly nor turn it off somewhere.

So I am searching for some other statement maybe related to the GraphicsDevice that implicitly turns depth off - but I can't find it.

(Sorry that I don't post any source code but I have too much source code and I simply don't know where to search)

**UPDATE:**

These are a couple of simple objects seen with correct depth.

These are the same objects in their current state.

# Answer
It does look like the spritebatch overlay drawing is changing your cullmode renderstate setting.

In 3.1 you can tell the spritebatch to save and restore the renderstate with the SaveStateMode parameter;

```
SpriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);

```

From MSDN;

> However, there are cases where render states can change automatically. A common example is the rendering of sprites and 3D objects on the same graphics device. In this case, the SpriteBatch object changes various render states when you call End. If you try any 3D rendering after this step, the results can be unpredictable.
>
> For this reason, you should restore several key render states to their former settings before you try to render any 3D objects. The following code demonstrates this approach.
>
> ```
>     GraphicsDevice.RenderState.DepthBufferEnable = true;
>     GraphicsDevice.RenderState.AlphaBlendEnable = false;
>     GraphicsDevice.RenderState.AlphaTestEnable = false;
>
> ```

More from MSDN

> SpriteBatch.Begin sets the following render states.
>
> * **CullMode**
> * DepthBufferEnable
> * AlphaBlendEnable
> * AlphaTestEnable
> * AlphaBlendOperation
> * SourceBlend
> * DestinationBlend
> * SeparateAlphaBlendEnabled
> * AlphaFunction
> * ReferenceAlpha
>
> Begin sets the following sampler states.
>
> * AddressU
> * AddressV
> * MagFilter
> * MinFilter
> * MipFilter
> * MipMapLevelOfDetailBias
> * MaxMipLevel
>
> If Begin is called with SaveStateMode set to None, then these states must be reset by the caller if they are used elsewhere. Calling Begin with SaveStateMode set to SaveState will reset these values properly, but may adversely affect performance.
> 5 votes

# Answer
Are you using a SpriteBatch to render your overlay in the second image? If so, SpriteBatch in 3.1 sets render states when drawing (including disabling the depth buffer) that you need to restore before drawing in 3D. See this article for the exact states changed.
> 4 votes

# Answer
Thank you for all the comments and efforts.

After having cut my whole program into pieces I found the error which was in fact a silly one. For some reason I set the depth of my main viewport I am using to render the models to

```
_mainViewport.MaxDepth = 2.0f;

```

which was the cause why my models showed no depth!

After setting the MaxDepth value to 1.0f my models were displayed correctly again.
> 1 votes

---
Tags: xna, c#, 3d, directx, xna3.1
---


title: How can I speed up this design?

text:
# Question
Title: How can I speed up this design?
I am currently developing a game that includes a server and some clients. Currently, the server does its work based on user input then draws the image the clients should see and sends it. Unfortunately, the server's time is taken up almost exclusively by the drawing and encoding. Is there a better way for me to design this?

# Answer
OK, the obvious answers would be:

1. Don't do drawing on the server. Just have the server tell the client what it needs to draw and let the client handle the actual drawing.
2. Have the client keep track of the information it's previously received, so that the server only needs to send it a list of changes rather than sending everything again.
3. Have the client predict (as far as possible) what will change based on the player's actions, so that the server only needs to send it any changes the client doesn't already know about (such as those caused by actions of other players).

Yeah, I know that's not very specific, but neither is your question. If there's something in particular that you'd like more detail about, you can comment or edit your question to tell us what it is.
> 6 votes

---
Tags: server, optimization
---


# Question
Title: Better ways of handling the server for a Multiplayer Browser Based Game
I am looking to create a multiplayer browser based game, similar to tribal wars and such, and i'm trying to think of better ways of handling the server, for example when troops and buildings are completed and the landing of troop movements

# Answer
> 7 votes
Tribal Wars is a browser-based, massive multiplayer online real time strategy game, set in the Middle Ages.

Now Tribal Wars is a browser based game and was released in 2003 as a text based game.

Browser-based games usually rely on some kind of server-side code, such as Perl, PHP, Ruby, Python, or Java; though some will use technologies like Flash, ActiveX, and Java applets to store data on the client's computer.

Unlike a stand-alone client or video game, being confined to a browser limits to some degree the extent to which 3-D rendering can be supported.

**The following resources may help you**

**Basic Guideline**

**HTML5**

**Flash**

**Java**

**Community Resources**

**EDIT :**

> better ways of handling the server, for example when troops and buildings are completed and the landing of troop movements

**You should have persistent connection with server as every connection takes time for extra resource, Point-to-point connection, Low latency for better interaction.**

It varies from platform to platform. For example, for browser game **tribal wars** used the followings

* Server End Code # **PHP**, Some **Java**
* Server # **Amazon**: **EC2, CloudFront, S3, Hadoop/Elastic Map Reduce, Hive, some SQS, some SimpleDB**
* Load Balancing # **HAProxy**
* Sharded, Blob Storage # **MySQL**
* Point-to-point connectivity # **YAMI4**
* Low latency # **YAMI4**

---
Tags: multiplayer, server
---


# Question
Title: Moving the jBullet collision body to with the player object
I am trying to update the location of the rigid body for a player class, as my player moves around I would like the collision body to also move with the player object (currently represented as a cube). Below is my current update method for when I want to update the xyz coords, but I am pretty sure I am not able to update the origin coords? :

```
    public void Update(float pX, float pY, float pZ) {
    posX = pX;
    posY = pY;
    posZ = pZ;

    //update the playerCube transform for the rigid body
    cubeTransform.origin.x = posX;
    cubeTransform.origin.y = posY;
    cubeTransform.origin.z = posZ;

    cubeRigidBody.getMotionState().setWorldTransform(cubeTransform);

    processTransformMatrix(cubeTransform);
    }

```

I do not have rotation updated, as I do not actually want/need the player body to rotate at all currently. However, in the final game this will be put in place.

# Answer
You need to make the physics object a kinematic object. See Bullet Physics Manual for more information. Bullet Physics ask every frame the current transformation from kinematic objects. You need your own MotionState implementation for that. Mine is as simple as this:

```
public class KinematicMotionState extends MotionState {
    private Transform worldTransform;

    public KinematicMotionState() {
        worldTransform = new Transform();
        worldTransform.setIdentity();
    }

    @Override
    public Transform getWorldTransform(Transform out) {
        out.set(worldTransform);
        return out;
    }

    @Override
    public void setWorldTransform(Transform worldTrans) {
        worldTransform.set(worldTrans);
    }
}

```

In addition you must tell the rigid body that it's a kinematic object:

```
rigidBody.setCollisionFlags(rigidBody.getCollisionFlags() | CollisionFlags.KINEMATIC_OBJECT);
rigidBody.setActivationState(CollisionObject.DISABLE_DEACTIVATION);

```

And then updating the transformation of the kinematic object:

```
Transform transform = new Transform();
transform.setIdentity();
transform.origin.set(x, y, z);
motionState.setWorldTransform(transform);

```
> 3 votes

---
Tags: java, collision-detection, movement, bullet-physics
---


# Question
Title: Monogame/SharpDX - Shader parameters missing
I am currently working on a simple game that I am building in Windows 8 using MonoGame (develop3d). I am using some shader code from a tutorial (made by Charles Humphrey) and having an issue populating a 'texture' parameter as it appears to be missing.

**Edit** I have also tried 'Texture2D' and using it with a register(t0), still no luck

I'm not well versed writing shaders, so this might be caused by a more obvious problem.

I have debugged through MonoGame's Content processor to see how this shader is being parsed, all the non 'texture' parameters are there and look to be loading correctly.

**Edit** This seems to go back to D3D compiler.

Shader code below:

```
#include "PPVertexShader.fxh"

float2 lightScreenPosition;

float4x4 matVP;

float2 halfPixel;

float SunSize;

texture flare;

sampler2D Scene: register(s0){
    AddressU = Clamp;
    AddressV = Clamp;
};

sampler Flare = sampler_state
{
    Texture = (flare);
    AddressU = CLAMP;
    AddressV = CLAMP;
};

float4 LightSourceMaskPS(float2 texCoord : TEXCOORD0 ) : COLOR0
{
    texCoord -= halfPixel;

    // Get the scene
    float4 col = 0;

    // Find the suns position in the world and map it to the screen space.
        float2 coord;

        float size = SunSize / 1;

        float2 center = lightScreenPosition;

        coord = .5 - (texCoord - center) / size * .5;
        col += (pow(tex2D(Flare,coord),2) * 1) * 2;

    return col * tex2D(Scene,texCoord);
}

technique LightSourceMask
{
    pass p0
    {
        VertexShader = compile vs_4_0 VertexShaderFunction();
        PixelShader = compile ps_4_0 LightSourceMaskPS();
    }
}

```

I've removed default values as they are currently not support in MonoGame and also changed ps and vs to v4 instead of 2. Could this be causing the issue?

As I debug through 'DXConstantBufferData' constructor (from within the MonoGameContentProcessing project) I find that the 'flare' parameter does not exist. All others seem to be getting created fine.

Any help would be appreciated.

**Update 1** I have discovered that SharpDX D3D compiler is what seems to be ignoring this parameter (perhaps by design?). The `ConstantBufferDescription.VariableCount` seems to be not counting the texture variable.

**Update 2** SharpDX function 'GetConstantBuffer(int index)' returns the parameters (minus textures) which is making is impossible to set values to these variables within the shader. Any one know if this is normal for DX11 / Shader Model 4.0? Or am I missing something else?

# Answer
Don't know much about internals of MonoGame, but texture are definitely not stored in a ConstantBuffer. The texture is not a constant buffer, it is a texture which has its own slot and is bounded completely separetly from the ConstantBuffer.

To get the slot of the texture, this is done through the ShaderReflection object and method reflect.GetResourceBindingDescription(i);.
> 2 votes

---
Tags: xna, shaders, sharpdx, monogame, windows-8
---


title: cocos2d mask rotation

text:
# Question
Title: cocos2d mask rotation
I've been experimenting with Ray Wenderlich's tutorial about masking sprite using shaders with cocos2D 2.0.

It works pretty well but now I'd like to rotate the mask independently of the masked texture.

Does anyone have any idea about how to achieve it ?

# Answer
you can use 2 different varying coordinates one for the texture and one for the mask. then you need to add a uniform to your vertex shader program which indicates how much MaskTextureCoordinates should be rotated.
> 2 votes

---
Tags: shaders, cocos2d-iphone, opengl-es2, masking
---


title: How does gluLookAt work?

text:
# Question
Title: How does gluLookAt work?
From my understanding,

```
gluLookAt(
        eye_x, eye_y, eye_z,
        center_x, center_y, center_z,
        up_x, up_y, up_z
    );

```

is equivalent to:

```
glRotatef(B, 0.0, 0.0, 1.0);
glRotatef(A, wx, wy, wz);
glTranslatef(-eye_x, -eye_y, -eye_z);

```

But when I print out the `ModelView` matrix, the call to `glTranslatef()` doesn't seem to work properly. Here is the code snippet:

```
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>

#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

static const int Rx = 0;
static const int Ry = 1;
static const int Rz = 2;

static const int Ux = 4;
static const int Uy = 5;
static const int Uz = 6;

static const int Ax = 8;
static const int Ay = 9;
static const int Az = 10;

static const int Tx = 12;
static const int Ty = 13;
static const int Tz = 14;

void init() {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);
    glShadeModel(GL_SMOOTH);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    GLfloat lmodel_ambient[] = { 0.8, 0.0, 0.0, 0.0 };
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
}

void displayModelviewMatrix(float MV[16]) {
    int SPACING = 12;
    cout << left;
    cout << "\tMODELVIEW MATRIX\n";
    cout << "--------------------------------------------------" << endl;
    cout << setw(SPACING) << "R" << setw(SPACING) << "U" << setw(SPACING) << "A" << setw(SPACING) << "T" << endl;
    cout << "--------------------------------------------------" << endl;
    cout << setw(SPACING) << MV[Rx] << setw(SPACING) << MV[Ux] << setw(SPACING) << MV[Ax]  << setw(SPACING) << MV[Tx] << endl;
    cout << setw(SPACING) << MV[Ry] << setw(SPACING) << MV[Uy] << setw(SPACING) << MV[Ay]  << setw(SPACING) << MV[Ty] << endl;
    cout << setw(SPACING) << MV[Rz] << setw(SPACING) << MV[Uz] << setw(SPACING) << MV[Az] << setw(SPACING)  << MV[Tz] << endl;
    cout << setw(SPACING) << MV[3] << setw(SPACING) << MV[7] << setw(SPACING) << MV[11] << setw(SPACING) << MV[15] << endl;
    cout << "--------------------------------------------------" << endl;
    cout << endl;
}

void reshape(int w, int h) {
    float ratio = static_cast<float>(w)/h;
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, ratio, 1.0, 425.0);
}

void draw() {
    float m[16];
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glGetFloatv(GL_MODELVIEW_MATRIX, m);
    gluLookAt(
        300.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f
    );
    glColor3f(1.0, 0.0, 0.0);
    glutSolidCube(100.0);
    glGetFloatv(GL_MODELVIEW_MATRIX, m);
    displayModelviewMatrix(m);
    glutSwapBuffers();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(400, 400);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Demo");
    glutReshapeFunc(reshape);
    glutDisplayFunc(draw);
    init();
    glutMainLoop();
    return 0;
}

```

No matter what value I use for the `eye` vector:
`300, 0, 0` or
`0, 300, 0` or
`0, 0, 300`
the translation vector is the same, which doesn't make any sense because the order of code is in backward order so `glTranslatef` should run first, then the 2 rotations. Plus, the rotation matrix, is completely independent of the translation column (in the ModelView matrix), then what would cause this weird behavior? Here is the output with the eye vector is `(0.0f, 300.0f, 0.0f)`

```
        MODELVIEW MATRIX
--------------------------------------------------
R           U           A           T
--------------------------------------------------
0           0           0           0
0           0           0           0
0           1           0           -300
0           0           0           1
--------------------------------------------------

```

I would expect the `T` column to be `(0, -300, 0)`! So could anyone help me explain this?

The implementation of `gluLookAt` from http://www.mesa3d.org

```
void GLAPIENTRY
gluLookAt(GLdouble eyex, GLdouble eyey, GLdouble eyez, GLdouble centerx,
      GLdouble centery, GLdouble centerz, GLdouble upx, GLdouble upy,
      GLdouble upz)
{
    float forward[3], side[3], up[3];
    GLfloat m[4][4];

    forward[0] = centerx - eyex;
    forward[1] = centery - eyey;
    forward[2] = centerz - eyez;

    up[0] = upx;
    up[1] = upy;
    up[2] = upz;

    normalize(forward);

    /* Side = forward x up */
    cross(forward, up, side);
    normalize(side);

    /* Recompute up as: up = side x forward */
    cross(side, forward, up);

    __gluMakeIdentityf(&m[0][0]);
    m[0][0] = side[0];
    m[1][0] = side[1];
    m[2][0] = side[2];

    m[0][1] = up[0];
    m[1][1] = up[1];
    m[2][1] = up[2];

    m[0][2] = -forward[0];
    m[1][2] = -forward[1];
    m[2][2] = -forward[2];

    glMultMatrixf(&m[0][0]);
    glTranslated(-eyex, -eyey, -eyez);
}

```

# Answer
`gluLookAt` will rotate and translate the world in a way, that the camera will be located at `{0, 0, 0}` and looks towards the negative z-axis. This is the camera setup used in OpenGL. The camera actually never moves, the world does. Sound confusing? Hell yeah, let me try to explain :)

Lets take this example:

```
eye    :  {300, 0, 0}
lookat :  {  0, 0, 0}
up     :  {  0, 1, 0}

MODELVIEW MATRIX
--------------------------------------------------
R           U           A           T
--------------------------------------------------
0           0           -1          0
0           1           0           0
1           0           0           -300
0           0           0           1
--------------------------------------------------

```

First we need to analyze the rotational part of the matrix: `R`, `U` and `A`. As you can see the right vector (`R`) is not in the x-axis anymore `{1, 0, 0}`, it is in the z-axis `{0, 0, 1}`. That means it is rotated by 90 degrees around the y-axis. The same happens to the eye-position. Rotating `{-300, 0, 0}` by 90 degrees around the y-axis lets it end up at `{0, 0, -300}`, voila, there it is.

It is `-300` and not `300` because the world is moved and not the camera, so the world is moved in the opposite direction, still 300 units away from the camera at `{0, 0, 0}`. And again, it is moved towards the negative z-axis, because that is where the OpenGL camera looks to, as mentioned above.

---

Note: there is an an anomaly in your example, the normalized vector from eye-position to look-at-point must not be the same as the up-vector, so:

```
eye    : {0, 300, 0}
lookat : {0,   0, 0}
up     : {0,   1, 0}

normalize(eye - lookat): {0, 1, 0} -> the same as the up-vector

```

will in fact not work, we must pick another up-vector, for instance `{1, 0, 0}`
> 8 votes

---
Tags: c++, opengl, matrix, glut
---


# Question
Title: What are good ways to find collaborators for a coding weekend?
Not sure if this belongs here, feel free to push it somewhere else if needed.

When i was at university we would sometimes come together into a room full of beer and fast food and crank out software in a weekend. Unfortunately the group has kind of split up and its just not possible any more.

My question is now: Where can i find like-minded people on the Internet that would like to do something like this? I have an idea what i wanted to do next, but of course other people have ideas too.

# Answer
I suggest searching in Meetup for a relevant group. I'm a member of two groups that are local to me and focused on mobile development. One often sponsors "hackathons" like you describe for prizes.
> 2 votes

---
Tags: game-design, open-source
---


# Question
Title: How to do profiling and memory pooling per system?
I have been interesting in profiling and keeping a managed memory pool for each subsystem, so I could get statistic on how much memory was being used in something such as sounds or graphics. However, what would be a design that works for doing this? I was thinking of using multiple allocators and just using one per subsystem, however, that would result in global variables for my allocators (or so it would seem to me). Another approach I have seen/been suggested is to just overload new and pass in an allocator for a parameter.

I had a similar question over on stackoverflow here with a bounty, however, it seems as if perhaps I was too vague or just there is not enough people with knowledge in the subject.

# Answer
Its definitely a question that could sound vague to some ;)

But I think I know where you are coming from.

You have a million choices for how you could choose to implement this. Some of those choices should revolve around both the target platforms and the overall design goals. Those considerations will break any ties, until you feel comfortable enough with different implementation costs enough to grow the design from the platform and general design concerns first. So until then, here are some ways that wont cost you in terms of complexity (management burden) or in dealing with removal or changes if you change your mind...

If the goal is to measure and allocate, with the possibility of using pools, then you need to think first bout the minimum set of livable code to get started. For the sake of explanation, if you are partial to classes, you could make one class, an let that stand for a heap, or instead use a set of functions that take a handle or a heap name. Its really an issue of semantics to be honest. Next decision is new or malloc; I'm partial to malloc because many times I'm dealing with low level constructs and I know in most implementations that new calls malloc, and I don't have to worry about the complexity of overloading new, and worrying about that on all platforms. However I have many times built systems or components around overloading or hooking new. And of course the core problem or difference, is that 'new' must know the type before the allocation, where as 'malloc' doesn't care and with malloc you resolve to a type after the allocation. All that detail is to give you an idea and some context for making design decisions in these types matters :)

So I'm going to pick class and malloc, because its easier to explain here, but it really doesn't matter in the end. The internals will end up bearing little material difference as compared to the rest of the overall design.

So in this hypothetical, I know that (or going to assume that) i may end up with 7-8 real sub-system class instantiations, and anticipate 100s of thousands of calls for allocation and free. Since much of my curiosity and real thrust in all this, is really about the sizes and profile side, I don't want to burden the the app performance wise. For starters I might decide to just leave the whole thing open and public until I have it nailed down, as I walk through implementing it throughout the rest of the app; a struct will do this nicely. The 's\_' is to show which vars are clearly intended for statistics.

```
struct Mem
{
  int s_allocs;
  int s_frees;
  int s_peak;
  int s_current;
  void* heap; // if you wanted to go into having real actual separate heaps, else ignore
  void* alloc(int size);
  void free(void* p);

  Mem() {memset(this,0,szieof(Mem));}  // want this to be inlined with the call site constructor (a design decision example)
}

class MySubSystem
{
   Mem mem;
   ....  you get the idea
}

```

This is *extremely* lightweight on many fronts, and maybe a good place to start to flesh out where ever you really wanted to go with this. And you immediately have a problem, how do you know the size of freed item. (This would be a problem to solve for nearly any approach.) Since this is a game forum you could consider doping the first few bytes with the size, or else you have to either wrap or remember in some other way. Most game dev sensibilities shouldn't be too much against the doping, and its the simplest example, considering I've already made a wall of text. Basically goes like this: you don't want if can be helped to destroy the inherent alignment, you do want to know, since almost for free, if the size is coherent. So something as simple as "s\_allocs++; s\_total+=size; uint64\* p = (uint64\*)malloc/calloc(size += 8); \*p = 0xDEADDAED00000000 | size; return p + 1;" where allocations will be less than 4GB, and uint64 is whatever the compiler thinks a 64 bit unsigned int is, and where you can check the sanity value on free.

This is all one way to get you the bare minimum at a bare minimum cost that satisfies the requirements. It does *not* address allocating classes that have virtual functions if those are in scope for profiling or management, as you cant anticipate the size the c++ environment you are using needs for those without overloading or hooking new, or if you are relying on the constructor in one of the odd ways that couldn't be handled by some other 'init' function. Otherwise a stuct is a class is a arbitrary alloc and is all the same, when you cast. If you are partial to new and need the inherent virtual table or constructor semantics, then you must hook new, but that's a whole 'nother animal, which you need to really study to make sure you are doing what new needs and would have to signal your code thats handling new, which bucket this applied to. But otherwise the above concept is the same.

More importantly this should get your brain going, and hopefully along the lines of what you need and what your tolerances are, now that you've seen behind the curtain a little more. There is no wizard :)
> 1 votes

# Answer
You don't need to implement anything in your game for this data. Tools such as Massif Valgrind can extract all necessary data from the Debug Symbols. You can view the dumps of Massif in Massif Visualizer.
> 1 votes

# Answer
I highly recommend not to write your own memory allocator. You need a stable, reliable and tested one, with good debugging functionality like corruption detection and most importantly: with reliable statistics. This is not an easy task and has many pitfalls. There are great and easy to utilize ones out there, for instance:

Doug Lea Allocator

It comes with the concept of memory spaces, you can use one per subsystem. It's highly optimized and gives you great statistics and runtime-information.
> 1 votes

---
Tags: c++, architecture, design-patterns, profiling
---


# Question
Title: Why does using glReadBuffer/glReadPixels returns black image on Intel cards?
I have this piece of code

```
glReadBuffer( GL_FRONT );
glReadPixels( 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer );

```

Which works just perfectly in all the Nvidia and AMD GPUs I have tried, but it fails in almost every single Intel built-in video that I have tried. It actually works in a very old 945GME, but fails in all the others. Instead of getting a screenshot I am actually getting a black screen.

If it helps, I am working with the Doom3 Engine, and that code is derived from the built-in screen capture code. By the way, even with the original game I cannot do screen capture on those intel devices anyway. My guess is that they are not implementing the standard correctly or something. Is there a workaround for this?

# Answer
Intel graphics have historically always had problems with reading from, or drawing to, the front buffer. A good rule of thumb I follow with Intel is this - if you can't do it in D3D then don't even attempt to do it in OpenGL, even if the spec says that you should be able to - and D3D doesn't allow access to the front buffer in this manner so... just use GL\_BACK instead.
> 5 votes

---
Tags: opengl
---


# Question
Title: Ensuring that saved data has not been edited in a game with both offline and online components
I'm in the pre-planning phase of coming up with a game design and I was wondering if there was a sensible way to stop people from editing saves in a game with offline and online components.

The offline component would allow the player to play through the game and the online component would allow them to play against other players, so I would need to make sure that people hadn't edited the source code/save files while offline to gain an advantage while online.

Game likely to be developed in either .Net or Java, both of which are unfortunately easy to decompile.

# Answer
Being able to decompile/reverse engineer the client code easily is really only a slight hindrance. Enterprising hackers have been bending executables to their will (maliciously and non-) for years before high-level, trivial-to-decompile languages like C# came on to the scene. Security through obscurity alone is no security at all.

Any data on the user's machine (code or regular asset data) is essentially compromised already. You can't really protect yourself against that -- if you don't want people editing data, don't put it on their machine, save it on your servers. Similarly if you don't want them modifying the code in the client, make sure the client doesn't have control over anything useful.

If that's not an option (for example your multiplayer is entirely peer-to-peer) you can do things like compute hashes of the relevant assets and only allow people to play with eachother if the hashes match. Yes, somebody could carefully craft an edit to the executable such that it returned a different hash, but all that should mean is that the offending player will desynchronize and disconnect from the game relatively quickly because his or her assets don't match the rest of the players'.

You could also employ a "majority rules" type of test that allows for you to disconnect players whose simulation has drifted out of sync with other players, giving the "host" player (whoever started the game) the tie-breaking vote.
> 10 votes

# Answer
If the data is all generated client-side, there's nothing you can do about this. You can't tell the difference between an edit done by your software and an edit done by someone or something else pretending to be your software.

One deterrent you can try is encrypting the save file, using a key in the software. Unfortunately, if the user is good enough to edit a save file, they're good enough to find the key in your software too.

You can stop people editing the saves by not storing them on the client's machine, eg. by uploading them to the server - but that doesn't stop them uploading a hacked save in the first place! Online games solve this problem by keeping the authoritative game state on their server all the time, but that won't work for your offline mode.

So really, the answer is no - anything your game can do to edit, obscure, or encrypt the data can also be done by a hacker.
> 3 votes

# Answer
When we were just starting development of our current game, we, too, wanted to have offline play mode. The idea was to let players play through game levels while offline, and then somehow sync their progress when they come online. So, we thought long and hard about how we can prevent cheating. The conclusion was: we can't. There's really NO way to let players play offline and be 100% sure they didn't cheat.
> 1 votes

# Answer
One simple solution used with file downloading is hashing. Hash the save file and store this "fingerprint" somewhere. When you load it, hash the file, and check it against the fingerprint. If they don't match, the file has been modified.

Of course, if someone decompiles your code, there's nothing you can do. For this answer, this means they can store the hash of the modified save file, too.

Another option would be to send the fingerprint to a server somewhere, where the end-user can't manually modify it if they've modified the save file. This is similar to what iTunes does when restoring iPhone images.
> 1 votes

---
Tags: online, anti-cheat
---


# Question
Title: What platform were old TV video games developed on?
I am very eager to know how TV video games (which we all used to play in our childhood) were developed and on which platform.

I know how games are developed for mobile devices, Windows PC's and Mac but I'm not getting how (in those days) Contra, Duck Hunt and all those games were developed. As they have high graphics and a large number of stages. So how did they manage to develop games in such a small size environment and with lower configuration platform?

# Answer
The really old games - written for NES, Game Boy, SNES, and even older systems like the Atari family - were usually written in *assembly* language. This was necessary because C compilers of the time were either non-existant or not up to the task of generating sufficiently efficient code.

They were able to squeeze all of that stuff into small cartridges - for NES, even 256KB was a lot of data (though larger games existed) - because they used clever tricks, such as tile-based and low-color graphics, enabling a lot of data to be stored in very little space. Additionally, specialized chips for video and audio made it possible to handle these things more efficiently, without having to do everything in software.

Over time, C compilers became more efficient and devices became more powerful - N64, GBA and later devices all used C or even C++ by default - and assembly was reserved for small pieces of code where extra optimization was necessary in order to consistently meet the 60FPS target (or whatever framerate the game runs at).
> 17 votes

# Answer
I remember writing simple games for the Commodore 64/Vic20 back in the early 80's. Some BASIC(believe it or not - some games were completely BASIC encoded - BASIC was on the machine's ROM so was a freebie) - but mostly assembler. Assembler was not consistant either - most machines had several commercial assemblers available (though like most back then, I wrote my own). Graphics on the C64 was very advanced for the time with raster hardware sprites (only 8 allowed on screen at a time - but these could be duplicated in software with some tricks, giving hundreds but only 8 varieties on screen at a time). They were 16 colour (palette - which could be changed at run time as could the sprite). Sprites were 2D of course.

The first "home computer" I played with (ignoring earlier scientific and business machines) was a ZX81 (my school had a ZX80 - but it was locked in a glass box like a museum exhibit - no one knew how to use it!). Imagine writing a game in 1/4 of a K (that's 256 bytes!) - now that's skill!
> 3 votes

# Answer
The video game systems or first generation consoles (before they were called consoles) from the late 1970s and still today are developed much like any embedded computer system.

An embedded computer is a computer (i.e. a microcontroller or microprocessor) in an electronic system that does not resemble a personal computer, or larger multi-user computer system (e.g. time-sharing system, mini-computers, and mainframes); one major difference being they typically lack of the now standard input/output via a video terminal and keyboard.

The development is done on another computer, these days typically a developer PC or workstation using a cross-platform development environment which produces executables for the **target** system - the video game system in this context, which is often be a different microprocessor architecture versus the development system's own (or **host**) CPU.

Two examples of current video game systems are the for Sony's Playstation 3 which is based upon the Sony, Toshiba and IBM's Cell processor, and for mobile devices (smart phones, tablets) which are often ARM based microprocessors.

As `Michael Madsen` indicated the majority of the programming was done in assembly rather than a high level compiled language, such as C or Pascal. This was necessary to fit the game's entire content within the confines of the highly constrained system (very little RAM and limited cartridge ROM capacity), as well as to access co-processors such as the Atari 2600's TIA.
> 3 votes

---
Tags: graphics, game-industry
---


title: UDK license (DLLBind)

text:
# Question
Title: UDK license (DLLBind)
I dont understand part of UDK's license about DLLBind:

does it allow to use DLLBind in UDK projects? Could I use DLLBind for commercial games without buying c++/native license?

# Answer
> 0 votes
> This functionality is intended for use by UDK developers

What don't you understand?

---
Tags: udk, licensing
---


# Question
Title: How to convert pitch and yaw to x, y, z rotations?
I'm a beginner using XNA to try and make a 3D Asteroids game.

**Update:** I'm having a slightly hard time describing this so I made a little animation to show what I'm talking about: http://www.youtube.com/watch?v=4TyGQX\_iRI4&feature=youtu.be

I'm really close to having my space ship drive around as if it had thrusters for pitch and yaw.

The problem is I can't quite figure out how to translate the rotations, for instance, when I pitch forward 45 degrees and then start to turn - in this case there should be rotation being applied to all three directions to get the "diagonal yaw" - right? I thought I had it right with the calculations below, but they cause a partly pitched forward ship to wobble instead of turn.... :(

So my quesiton is: how do you calculate the X, Y, and Z rotations for an object in terms of *pitch* and *yaw*?

In this picture the first is the starting position, the second is after pitch is applied, and the third is after both pitch and yaw are applied. I'm trying to figure out how to get the fourth picture to be the result of consecutive pitch and yaw operations (yaw being applied to already pitched ship).

Here's current (almost working) calculations for the Rotation acceleration:

```
        float accel = .75f;

        // Thrust +Y / Forward
        if (currentKeyboardState.IsKeyDown(Keys.I))
        {
            this.ship.AccelerationY += (float)Math.Cos(this.ship.RotationZ) * accel;
            this.ship.AccelerationX += (float)Math.Sin(this.ship.RotationZ) * -accel;
            this.ship.AccelerationZ += (float)Math.Sin(this.ship.RotationX) * accel;
        }

        // Rotation +Z / Yaw
        if (currentKeyboardState.IsKeyDown(Keys.J))
        {
            this.ship.RotationAccelerationZ += (float)Math.Cos(this.ship.RotationX) * accel;
            this.ship.RotationAccelerationY += (float)Math.Sin(this.ship.RotationX) * accel;
            this.ship.RotationAccelerationX += (float)Math.Sin(this.ship.RotationY) * accel;
        }

        // Rotation -Z / Yaw
        if (currentKeyboardState.IsKeyDown(Keys.K))
        {
            this.ship.RotationAccelerationZ += (float)Math.Cos(this.ship.RotationX) * -accel;
            this.ship.RotationAccelerationY += (float)Math.Sin(this.ship.RotationX) * -accel;
            this.ship.RotationAccelerationX += (float)Math.Sin(this.ship.RotationY) * -accel;
        }

        // Rotation +X / Pitch
        if (currentKeyboardState.IsKeyDown(Keys.F))
        {
            this.ship.RotationAccelerationX += accel;
        }

        // Rotation -X / Pitch
        if (currentKeyboardState.IsKeyDown(Keys.D))
        {
            this.ship.RotationAccelerationX -= accel;
        }

```

I'm combining that with drawing code that does a rotation to the model:

```
public void Draw(Matrix world, Matrix view, Matrix projection, TimeSpan elsapsedTime)
{
    float seconds = (float)elsapsedTime.TotalSeconds;

    // update velocity based on acceleration
    this.VelocityX += this.AccelerationX * seconds;
    this.VelocityY += this.AccelerationY * seconds;
    this.VelocityZ += this.AccelerationZ * seconds;

    // update position based on velocity
    this.PositionX += this.VelocityX * seconds;
    this.PositionY += this.VelocityY * seconds;
    this.PositionZ += this.VelocityZ * seconds;

    // update rotational velocity based on rotational acceleration
    this.RotationVelocityX += this.RotationAccelerationX * seconds;
    this.RotationVelocityY += this.RotationAccelerationY * seconds;
    this.RotationVelocityZ += this.RotationAccelerationZ * seconds;

    // update rotation based on rotational velocity
    this.RotationX += this.RotationVelocityX * seconds;
    this.RotationY += this.RotationVelocityY * seconds;
    this.RotationZ += this.RotationVelocityZ * seconds;

    Matrix translation = Matrix.CreateTranslation(PositionX, PositionY, PositionZ);

    Matrix rotation = Matrix.CreateRotationX(RotationX) * Matrix.CreateRotationY(RotationY) * Matrix.CreateRotationZ(RotationZ);

    model.Root.Transform = rotation * translation * world;

    model.CopyAbsoluteBoneTransformsTo(boneTransforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.World = boneTransforms[mesh.ParentBone.Index];

            effect.View = view;

            effect.Projection = projection;

            effect.EnableDefaultLighting();
        }

        mesh.Draw();
    }
}

```

# Answer
### Issues with the code

Two things are not making sense in the code:

* changing the yaw should only modify the rotation around axis Z, not X or Y.
* the angular acceleration should be set immediately, and not depend on the current ship orientation

So your rotation acceleration code should IMHO look like this:

```
    // Rotation +Z/-Z -- Yaw
    if (currentKeyboardState.IsKeyDown(Keys.J))
        this.ship.RotationAccelerationZ = accel;
    else if (currentKeyboardState.IsKeyDown(Keys.K))
        this.ship.RotationAccelerationZ = -accel;
    else
        this.ship.RotationAccelerationZ = 0;

    // Rotation +X/-X -- Pitch
    if (currentKeyboardState.IsKeyDown(Keys.F))
        this.ship.RotationAccelerationX = accel;
    else if (currentKeyboardState.IsKeyDown(Keys.D))
        this.ship.RotationAccelerationX = -accel;
    else
        this.ship.RotationAccelerationX = 0;

```

### About Euler and Tait-Bryan angles

There are two main ways to describe a rotation in terms of angles and XYZ axes:

* when the 3rd axis is the same as the 1st axis, *eg.* XYX (also known as **Euler angles**)
* when all 3 rotation axes are distinct, *eg.* XYZ (also known as **Tait-Bryan angles**)

The Wikipedia article on Euler angles has more information, but I must admit the article is a real mess. And then there are two basic conventions for axes:

* when all rotations are performed around fixed axes, for instance XYZ for a rotation around axes X, Y and Z in that order
* when each rotation also rotates the referential used for subsequent rotations; in that case the notation XY'Z" is used instead of XYZ

One nice property of the above is that a rotation of angles a, b and c around X, Y' then Z" is equivalent to a rotation of angles c, b and a around Z, Y then X.

The common understanding of **pitch**, **yaw** and **roll** for aircrafts is that they are Tait-Bryan angles with the referential rotating with the aircraft. So assuming Z is up and Y is forward, it is a ZX'Y" rotation. Which we just saw is equivalent to a YXZ rotation.

What you are calling “yaw being applied to already pitched ship” is actually no longer yaw: there is some roll involved, too. But one way to achieve what you want is simply to switch the order of the rotations for pitch and yaw.
> 3 votes

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


# Question
Title: What implications does JIT (javascript/canvas) vs. AOT (Flash) have in terms of browser based game performance?
In my experience, even till this day, I still see more of a visual lag in entity movement / animation in JavaScript (Canvas) based games than I do in Flash based games.

Why is this - what exactly is the descrepancy at the most basic level between an JIT vs AOT compiler in the specific scenario of JavaScript vs. Flash.

# Answer
> 4 votes
It's not the compilation method that makes the games lag, it's the garbage collector, and the Flash garbage collector is separate from the browsers.

I think I can pretty confidently reason that you run Firefox, because the Firefox garbage collector is the worst piece of crap you can get, from a gaming point of view. If you open just one tab and run a light JavaScript game in it, it is usually tolerable, maybe even unnoticeable. But if you open a bunch of tabs, run something a bit more demanding or use Firebug you'll easily get regular lag spikes beyond 100 ms.

I haven't done any extensive testing for a while, but Chrome has always done really well in this regard, and both IE9 and Safari seemingly do an acceptable job as well.

I made a tool for testing JavaScript lag, you can play with it if you like: http://ebusiness.hopto.org/lagtest/

# Answer
> 3 votes
It's hard to say without looking at actual code but a few points:

* Flash has been around longer. People who author tools and libraries for it have more experience handling animation. I'm not a big fan of the tools and the proprietary technology but I'll never knock an ActionScript dev who knows what s/he's doing.
* JIT browsers are also relatively new to JS developers. The best choices for really fine-honed perf-intitiatives are still something we're sorting out as a community. Inline function defs used to be a borderline dumb thing to do in a lot of cases. Now it's a great way to boost perf in a lot of JIT scenarios.
* Normalizing for umpteen browsers doesn't have to but often does result in failing to take full advantage of a given browser's full capabilities.
* (edit: not quite right on this one but there might still be a point here - Erik) The Flash plug-in is vector friendly and it is widely understood how to take maximum advantage of that. Whether inheritance schemes will do us a ton of good with canvas context objects remains to be seen but I doubt it will be to the same degree of win you get out of vector.

# Answer
> 3 votes
One interesting thing that I'm surprised nobody has mentioned yet is the difference in the types of JIT compilation, because Flash is still JIT compiled, and, in most modern browsers, so is JavaScript, however Flash is a strongly typed language, which means there are a whole realm of optimizations that it can do (such as emitting a call to a method directly (something JavaScript cannot do)), that JavaScript cannot do because it is dynamically typed. You can replace the entire definition of a function in JavaScript at any point you want, and that new definition is what must be called. (it is still possible for JavaScript to do an indirect call that wouldn't be that much more expensive though) Field access on a field is actually a better example than method calling, because JavaScript cannot even do this indirectly, it has to first look the field up by name (hashed) on the current type of the object.

Another difference in performance is, as is already mentioned, the GC. I suspect (I've not checked) that most browsers use either a reference counting GC (because all memory the GC allocated for a page can be freed when the page is left, it's actually one of the best places to use a reference counting GC), or a conservative scanning GC (such as Boehm). The latter can be considerably slower than the former if it's not implemented right. (Boehm is an example of a right implementation) Flash on the other hand uses a precise GC (much easier to do in a strongly typed system). Because Flash uses a precise GC, it doesn't have the runtime overhead of reference counting. (which isn't huge, but is still there) A good example of a precise GC is Mono's SGen, which also compacts the heaps.

Then there comes the fact that JavaScript wasn't designed with animation in mind. (as was also mentioned) As far as I know, no browser will emit SSE-style instructions for the animating loops, where-as the core rendering functions in Flash have probably been hand optimized for peak performance. (in some places being written in raw assembly)

All-in all, it comes down to the fact that a dynamic language will always be slower than a statically typed one if it has to be compiled in a timely manner so as to not make the user complain about it's slowness.

# Answer
> 0 votes
IMHO that differnece comes from the fact that Flash was build from the ground to do exactly that, animations. Flash implements (even though poorly by major judgement) techniques for smoother visualization running by default, when in JS you would need to make those implementations manually.

There are examples of great implementations of JS/Canvas running even better then most Flash games I see around. It all comes to the developer making them.

# Answer
> 0 votes
aside from the GC, JIT aspect of these technologies, there is gap between the usage of hardware.

in the latest version of flash player, flash has began resort to hardware acceleration for rendering those images, which makes the rendering process faster and quality better. while on the other hand, JS driven games on some browsers( FF, CHROME ) haven's started this yet. There was one exception though, the IE9 browser has began to re-architect from the hardware abstraction layer, browsers from IE9 had made tremendous progress on making use of hardware acceleration, thus graphics rendering on these browsers is definitely better and faster than other browsers.

---
Tags: flash, javascript, performance, html-canvas, browser-based-games
---


# Question
Title: HLSL: how to get/set effectvariable to an array of structs with Direct3D10
**HLSL Code:**

```
//Lights
struct Light
{
    float3 pos;
    float3 dir;
    int type;
} m_aLights[3];

```

How can I get/set an effectvariable to m\_aLights with Direct3D10?

Thanks

# Answer
> 1 votes
say you have a global effect variable in your effect file like:

```
float myVariable;

```

you have to create a pointer to this in your code like this:

declare it:

```
ID3D10EffectMatrixVariable* pointerToVariable; //declaration

```

point to the effect:

```
pointerToVariable = pEffect->GetVariableByName("myVariable")->AsScalar(); //in your initialisation

```

Set it:

```
myVariable += 0.5f; //so whatever to the variable in a draw call for example
pointerToVariable->SetFloat(&myVariable); //and send it through

```

There are also methods which are called appropriate things such as AsIntVector, AsFloatVector, AsMatrix, SetMatrix, SetIntVector etc for the appropriate types of variables.

# Answer
> 1 votes
This is simple.

First skip when you initialize your effect variable AsScalar() or whatever because this is your own structure, and DirectX does not know your stuff.

Then, the most important thing is when you refresh effect variables every frame.

Do: `NameOfYourVariable->SetRawValue(void*)` (so address of your struct)

P.s: if it is already a pointer, pass it without "&", offset (if padding problem, add offset or shift will be shifting everything in your structure by passing in the shader), `sizeof(yourStruct)`).

Note: First, padding can be caused by virtual function thanks to inheritance, so struct should be okay, it is not a class which inherits. Second, in your struct, be sure to place bigger variable first, then place other in a decreasing size order. Make sense? Should be.

Therefore, weird things can appear if not power of two with DirectX so if you start with a float4 as color and place couple of vector3 after, add a float between each vector3 as padding and don't worry, you're not going to add these float but they will set your variable's values in the shader to the right BYTE.

```
e.g. Vector3
     INT64    (smaller than vector3 = sizeof(FFLOAT) * 3).
     FFLOAT   (32 bits < 64).
     CCHAR    (8 bits < 32).

```

That's it.

---
Tags: hlsl, directx10
---


title: 3d vertex translated onto 2d viewport

text:
# Question
Title: 3d vertex translated onto 2d viewport
I have a spherical world defined by simple trigonometric functions to create triangles that are relatively similar in size and shape throughout.

What I want to be able to do is use mouse input to target a range of vertices in the area around the mouse click in order to manipulate these vertices in real time.

I read a post on this forum regarding translating 3d world coordinates into the 2d viewport.. it recommended that you should multiply the world vector coordinates by the viewport and then the projection, but they didn't include any code examples, and suffice to say i couldn't get any good results.

Further information.. I am using a lookat method for the viewport. Does this cause a problem, and if so is there a solution? If this isn't the problem, does anyone have a simple code example illustrating translating one vertex in a 3d world into a 2d viewspace?

I am using XNA.

# Answer
> 2 votes
The Viewport class has two methods that are very useful for what you want...

Viewport.Project and Viewport.UnProject,

The UnProject method converts a screen space point into a point in world space, so if you calculate two points with different Z, you can build a ray in world space or in object space if you pass the right world matrix...

Whith that ray you can calculate collisions with your triangles...

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.unproject.aspx

```
  Vector3 pos0 = new Vector3( input.Ms1.X, input.Ms1.Y, 0 );
  Vector3 pos1 = new Vector3( input.Ms1.X, input.Ms1.Y, 1 );
  pos0 = device.Viewport.Unproject( pos0, camera.Projection, camera.View, World );
  pos1 = device.Viewport.Unproject( pos1, camera.Projection, camera.View, World );

  MouseRay = new Ray( pos0, pos1 - pos0 );

```

# Answer
> 0 votes
Blau's answer says the most important stuff. Once you know how to find the ray that goes from the near plane to the far plane corresponding the exact pixel you selected, in order to do what you need, you have to check all vertices and check their distance to the ray: http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html

If the distance is smaller than a certain threshold you define, then you consider the vertex to be selected for manipulations.

---
Tags: xna, 2d, 3d, transformation, viewport
---


# Question
Title: SDL_DisplayFormat works, but not SDL_DisplayFormatAlpha
The following code is intended to display a green square on a black background. It executes, but the green square does not show up. However, if I change `SDL_DisplayFormatAlpha` to `SDL_DisplayFormat` the square is rendered correctly.

So what don't I understand? It seems to me that I am creating `*surface` with an alpha mask and I am using `SDL_MapRGBA` to map my green color, so it would be consistent to use `SDL_DisplayFormatAlpha` as well.

(I removed error-checking for clarity, but none of the SDL API calls fail in this example.)

```
#include <SDL.h>

int main(int argc, const char *argv[])
{
    SDL_Init( SDL_INIT_EVERYTHING );

    SDL_Surface *screen = SDL_SetVideoMode(
        640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF
    );

    SDL_Surface *temp = SDL_CreateRGBSurface(
        SDL_HWSURFACE, 100, 100, 32, 0, 0, 0,
        ( SDL_BYTEORDER == SDL_BIG_ENDIAN ? 0x000000ff : 0xff000000 )
    );

    SDL_Surface *surface = SDL_DisplayFormatAlpha( temp );

    SDL_FreeSurface( temp );

    SDL_FillRect(
        surface, &surface->clip_rect, SDL_MapRGBA(
            screen->format, 0x00, 0xff, 0x00, 0xff
        )
    );

    SDL_Rect r;
    r.x = 50;
    r.y = 50;

    SDL_BlitSurface( surface, NULL, screen, &r );

    SDL_Flip( screen );

    SDL_Delay( 1000 );

    SDL_Quit();

    return 0;
}

```

# Answer
I was using the wrong format for SDL\_MapRGBA. Should have been

```
SDL_FillRect(
    surface, NULL, SDL_MapRGBA(
        surface->format, 0xff, 0xff, 0x00, 0xff
    )
);

```

(`surface->format` instead of `screen->format`.) I thought the two would be equivalent. And they are after calling `SDL_DisplayFormat()`, but *not* after calling `SDL_DisplayFormatAlpha()`. The screen surface doesn't have an alpha channel, so the format is different between the two.
> 0 votes

# Answer
I don’t know if this is the issue, but the masks in your `SDL_CreateRGBSurface()` call look wrong. Perhaps try what the SDL wiki says:

```
const SDL_PixelFormat& format = *screen->format;

SDL_Surface* surface = SDL_CreateRGBSurface(
  SDL_HWSURFACE,
  width,
  height,
  32,
  format.Rmask,
  format.Gmask,
  format.Bmask,
  format.Amask
);

```

Perhaps the upper bits (where the red channel ought to be) are being interpreted as the alpha channel; since they’re zero, the resulting surface would be fully transparent.
> 1 votes

# Answer
If you set the pixel colors in your surface before calling `SDL_DisplayFormatAlpha`, it might work:

```
int main(int argc, char *argv[])
{
    SDL_Init( SDL_INIT_EVERYTHING );

    SDL_Surface *screen = SDL_SetVideoMode(
        640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF
    );

    SDL_Surface *temp = SDL_CreateRGBSurface(
    SDL_HWSURFACE, 100, 100, 32, screen->format.Rmask, screen->format.Amask, screen->format.Bmask, screen->format.Amask);

Uint32 *pixels  =(Uint32*) temp->pixels;

for(int i = 0; i < 10000; i++)
{
    pixels[i] = SDL_MapRGBA(screen->format, 0, 255, 0, 255);
}

SDL_Surface *surface = SDL_DisplayFormatAlpha( temp );

    SDL_Rect r;
    r.x = 50;
    r.y = 50;

    SDL_BlitSurface( surface, NULL, screen, &r );

    SDL_Flip( screen );

    SDL_Delay( 1000 );

    SDL_Quit();

    return 0;
}

```

I also removed your endianness check. I'm using the masks provided by the `SDL_PixelFormat` structure. See my comment to Jon Purdy's answer for more information.
> 0 votes

---
Tags: c++, sdl
---


# Question
Title: Keeping Android Screen bright during Game
I have a game that uses the accelerometer to move a guy back and forth on the screen. After a few seconds the screen goes dim. Is there any way to keep it alive and bright during the game activity?

# Answer
With the PowerManager API, you can acquire and release locks to:

* prevent your device to pause;
* prevent your device to dim;
* force brightness
* ...

Warning you must add one permission:

```
<uses-permission android:name="android.permission.WAKE_LOCK" />

```
> 20 votes

# Answer
I try like that in oncreate on activity start

```
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

```
> 3 votes

# Answer
This blog post covers the three ways of achieving this:

http://blog.blundell-apps.com/tut-keep-screen-onawake-3-possible-ways/

Basically, you either:

* tell android through your layout xml that you want to keep the screen alive
* tell android through a call to window manager to keep the screen on during oncreate
* use wakelocks to force the device to use full power at all time (and drain batteries)
> 0 votes

---
Tags: android
---