title: Moving models with a matrix

text:
# Question
Title: Moving models with a matrix
Currently I have a playerWorld matrix which holds the position of my player, just a simple sphere. When I press a key to move the model, it does some crazy thing and flies off the screen really fast, and not even in the direction I want it to go.

```
    if (kbs.IsKeyDown(Keys.W))
        {
            playerWorld += Matrix.CreateTranslation(playerWorld.Forward * elapsed);
        }

```

Why is this happening? elapsed is a float variable:

```
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

```

Here is the draw code, maybe it's being drawn wrong?

```
    public void Render(ThirdPersonCam cam)
    {
        foreach (ModelMesh mesh in playerModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.View = cam.view;
                effect.Projection = cam.proj;
                effect.World = playerTransforms[mesh.ParentBone.Index] * playerWorld;
            }
            mesh.Draw();
        }
    }

```

# Answer
> 2 votes
When adding (combining) the movement or rotation (or scale) of two matrices together the arithmetic to apply on them is multiplication rather than addition.

change your += to \*= and your original code will work as expected.

```
if (kbs.IsKeyDown(Keys.W))
    {
        playerWorld *= Matrix.CreateTranslation(playerWorld.Forward * elapsed);
    }

```

one matrix multiplied by another matrix results in what you would conceptualize as adding the SRT of one matrix to the SRT of the second. (SRT is Scale/Rotation/Translation)

# Answer
> 2 votes
Use a vector to store translation and build the matrix from it.

```
   if (kbs.IsKeyDown(Keys.W))
      {
          playerPos += playerForward * speed * elapsed;
      }

   playerWorld = Matrix.CreateScale(playerScale)
               * Matrix.CreateFromQuaternion(playerRotation)
               * Matrix.CreateTranslation(playerPos);

```

---
Tags: xna, 3d
---


title: how to use texture atlas

text:
# Question
Title: how to use texture atlas
I am trying to implement texture atlas.

1) I am using the texturepackerGUI and the result is taking 2 files , one png (whicj contains all the images and one .atlas (and not .pack).

2) Now , I want to use the above instead of every seperate image.

Right now , I use for example:

```
private void loadTextures() {
bobTexture = new  Texture(Gdx.files.internal("data/images/bob_01.png"));
blockTexture = new Texture(Gdx.files.internal("data/images/block.png"));
    }

```

I want to use texture atlas , so instead of the above :

```
TextureAtlas atlas;
atlas = new TextureAtlas(Gdx.files.internal("data/images/bobs"));  //bobs.atlas
Sprite bobsprite = atlas.createSprite("bob-01");
Sprite blocksprite = atlas.createSprite("block");

```

Now,I must initialize TextureAtlas I think because it gives me error "Syntax error on token ";", , expected".I don't know how.

3) I put TexturePacker2 in the android project (MainActivity) :

```
  ...
  AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
    cfg.useGL20 = true;
    cfg.useAccelerometer = false;
    cfg.useCompass = false;
    cfg.useWakelock = true;
    TexturePacker2.process("my-gdx-game-android/assets/images/", "/my-gdx-game-android/assets/data", "bobs.atlas");
 ...

```

The folders inside TexturePacker are ok syntaxed? Or I must remove the "my-gdx-game-android/assets/"?

Thanks!

# Answer
> 2 votes
OK, I found it .

1) Using the texturepackerGUI you leave the "File Name" blank and this way you get 2 files , one png and one .pack (and not .atlas!)

2)In order to use textureatlas , you use it like this (from here):

```
private void loadTextures() {
TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("images/bobs.pack"));
bobIdleLeft = atlas.findRegion("bob-01");

```

No need to use the `TexturePacker2.process("my-gdx-game-android/assets/images/", "/my-gdx-game-android/assets/data", "bobs.atlas");` anywhere in your code.

---
Tags: android, libgdx
---


title: Are collision detection always O(n^2)?

text:
# Question
Title: Are collision detection always O(n^2)?
Are physics engine able to decrease that complexity, for example by grouping objects who are near each other and check for collisions inside this group instead of against all objects ? (for example, far objects can be removed from a group by looking at its velocity and distance from other objects).

If not, does that make collision trivial for spheres (in 3d) or disk (in 2d) ? Should I make a double loop, or create an array of pairs instead ?

EDIT: For physics engine like bullet and box2d, is collision detection still O(N^2) ?

# Answer
Spatial division is always O(N^2) in worst case and that is what complexity in informatics is about.

**However there are algorithms that work in linear time O(N)**. All of them are based on some kind of sweep line.

Basically you need to have your objects sorted by one coordinate. Let's say X. If you perform the sort every time before collision detection, the complexity will be O(N\*logN). The trick is to sort only when you are adding objects to the scene and later when something in the scene changes. Sorting after movement is not trivial. See the linked paper below for an algorithm that takes into movement and still works in linear time.

Then you sweep from left to right. Each time your sweep line crosses beginning of an object, you put it inside a temporary list. Every time your sweep line exits the object, you take it out from the list. You consider collisions only inside this temporary list.

The naive sweep line is O(N^2) in worst case as well (you make all objects span the whole map from left to right), but you can make it O(N) by making it smarter (see link below). A really good algorithm will be quite complex.

This is simple diagram how the sweep line works:

The line sweeps from left to right. Objects are sorted by X coordinate.

* Case one: First two objects are checked. Nothing else matters.
* Case two: First object was checked and is gone from the list. Two and three are checked.
* Case three: Even if that object IS colliding, we don't check.
* Case four: Because we check in this case!

Algorithms like this have complexity O(C\*N) = O(N).

Source: Two years of computational geometry courses.

In collision detection this is typically called **Sweep and Prune**, but sweep line family of algortithms is useful in many other fields.

Further recommended reading that I believe is out of scope of this question, but nevertheless interesting: Efficient Large-Scale Sweep and Prune Methods with AABB Insertion and Removal \- This paper presents an enhanced Sweep and Prune algorithm that uses axis-aligned bounding boxes (AABB) with sorting that takes into account movement. Algorigthm presented in the paper works in linear time.

---

Now note that **this is the best algorithm in theory**. It doesn't mean that it is used. In practice, O(N^2) algorithm with spatial division will have better performance speed wise in typical case (close to O(N)) and some extra requirement for memory. This is because the constant C in O(C\*N) can be very high! Since we usually have enough memory and typical cases have objects spread evenly in space - such algorithm will perform BETTER. But **O(N) is the answer to the original question.**
> 21 votes

# Answer
No. Collision detection is *not* always O(N^2).

For instance, say we have a 100x100 space with objects with size 10x10. We could divide this space in cells of 10x10 with a grid.

Each object can be in up to 4 grid cells (it could fit right in a block or be "between" cells). We could keep a list of objects in each cell.

We only need to check for collisions in those cells. If there is a maximum number of objects per grid cell (say, there are never more than 4 objects in the same block), then collision detection for each object is O(1) and collision detection for all objects is O(N).

This is not the only way to avoid O(N^2) complexity. There are other methods, more adequate for other use-cases - often using tree-based data structures.

The algorithm I described is one type of Space partitioning, but there are other space partitioning algorithms. See Types of space partitioning data structures for some more algorithms that avoid the O(N^2) temporal complexity.

Both Box2D and Bullet support mechanisms to reduce the number of checked pairs.

From the manual, section 4.15:

> Collision processing in a physics step can be divided into narrow-phase and broad-phase. In the narrow-phase we compute contact points between pairs of shapes. Imagine we have N shapes. Using brute force, we would need to perform the narrow-phase for N\*N/2 pairs.
>
> The b2BroadPhase class reduces this load by using a dynamic tree for pair management. This greatly reduces the number of narrow-phase calls.
>
> Normally you do not interact with the broad-phase directly. Instead, Box2D creates and manages a broad-phase internally. Also, b2BroadPhase is designed with Box2D’s simulation loop in mind, so it is likely not suited for other use cases.

From the Bullet Wiki:

> There are various kinds of broadphase algorithms that improve upon the naive O(n^2) algorithm that just returns the complete list of pairs. These optimised broadphases sometimes introduce even more non-colliding pairs but this is offset by their generally improved execution time. They have different performance characteristics and none outperform the others in all situations.
>
> Dynamic AABB Tree
>
> This is implemented by the btDbvtBroadphase in Bullet.
>
> As the name suggests, this is a dynamic AABB tree. One useful feature of this broadphase is that the structure adapts dynamically to the dimensions of the world and its contents. It is very well optimized and a very good general purpose broadphase. It handles dynamic worlds where many objects are in motion, and object addition and removal is faster than SAP.
>
> Sweep and Prune (SAP)
>
> In Bullet, this is the AxisSweep range of classes. This is also a good general purpose broadphase, with a limitation that it requires a fixed world size, known in advance. This broadphase has the best performance for typical dynamics worlds, where most objects have little or no motion. Both btAxisSweep3 and bt32AxisSweep3 quantize the begin and end points for each axis as integers instead of floating point numbers, to improve performance.
>
> The following link is a general introduction to broadphase and also a description of the Sweep and Prune algorithm (although it calls it "Sort and Sweep"):
>
> http://www.ziggyware.com/readarticle.php?article\_id=128
>
> Also, take a look at the wikipedia page:
>
> http://en.wikipedia.org/wiki/Sweep\_and\_prune
> 9 votes

# Answer
O(N^2) refers to the fact that if you have N objects, figuring out what is colliding with what is, *worst case*, N^2 collision computations. Say you have 3 objects. To find "who is hitting who", you have to find:

```
o1 hitting o2?  o1 hitting o3?
o2 hitting o1?  o2 hitting o3?
o3 hitting o1?  o3 hitting o2?

```

That's 6 checks for collisions, or N\*(N-1) checks. In asymptotic analysis we'd expand the polynomial and approximate as O(N^2). If you had 100 objects, then that'd be 100\*99, which is close enough to 100\*100.

So if you partition space using an octree for example, the *average* number of comparisons between bodies is reduced. If it is possible for all the objects to gather into a very small area (say if you're doing some kind of particle flow simulation, where particles can gather in the same area) then the O(N^2) may still occur at points in the simulation (at which points you'll see slowdown).

So, the whole point of O(N^2) there is because of the nature of each body checking every other body in the scene. That's just the nature of the computation. A lot of things can help to make this cheaper though. Even a scene graph (say detecting between objects in the same *room* only) will reduce the number of collision computations to be done significantly, but it will still be O(M^2) (where M is the number of objects in the room to be collision detected against). Spherical bounding volumes make the initial check *very* fast (`if( distance( myCenter, hisCenter ) > (myRadius+hisRadius) ) then MISS`), so even if collision detection is O(N^2), the bounding sphere computations are likely to happen very fast.
> 2 votes

---
Tags: collision-detection, physics, optimization, physics-engine
---


# Question
Title: TBN Matrix : Eye vs. World Space Conflict
I am tired of misleading and insufficient articles making me more confused each time I read, I need a clarification that will solve my TBN matrix problem forever.

Each article I read informs me differently about from which space TBN matrix converts to tangent space. One article says that it converts from eye space, other one says that it converts from world space to tangent space.

As far as I know, world space is `ModelMatrix * vertex`, eye space is `ViewMatrix * ModelMatrix * vertex`. Another article says that transpose of TBN Matrix actually does it.

Can you please explain me how to use TBN matrix, does it (or transposed tbn) convert from eye or world to tangent ? Should I convert my lighting vectors from eye space to world and then apply TBN on them ?

# Answer
Since you didn't provide links to these tutorials that confused you, I am going to assume that they weren't written by idiots and that the code in them is correct (where possible).

They're *all* correct (well, except transpose guy; I'll get to him). Your problem (likely stemming from the writers not being clear) is that you're not seeing the other differences in the examples.

A matrix converts vectors from space A to space B. The columns of this vector are the basis vectors of space A, expressed in the space of B. It is what space A looks like to objects in space B.

The TBN matrix is composed from 3 normals which are all in some space. That's your space A, the *source space* for the transform. The destination is of course tangent space.

Therefore, if you construct a matrix from these 3 normals, using them as the *columns* of the matrix, you will have created a matrix that goes from whatever space those normals were in to tangent space. What space those normals are in is entirely up to the code in question. I'm sure some example code transforms the normals to camera space before putting them in the matrix. I'm sure other example code transforms them to world space.

Again, it's all about what the code is doing; *conceptually*, it all does the same thing. This (note: it is likely that the transform of the normals is in the vertex shader, while the multiplication is in the fragment shader):

```
mat3 worldToTangent_tbn = mat3(
  normalModelToWorld * tangent,
  normalModelToWorld * bitangent,
  normalModelToWorld * normal)
vec3 tangent_space_light_direction = worldToTangent_tbn * world_space_light_direction;
//do lighting in tangent space.

```

Is fundamentally no different from this:

```
mat3 cameraToTangent_tbn = mat3(
  normalModelToCamera * tangent,
  normalModelToCamera * bitangent,
  normalModelToCamera * normal)
vec3 tangent_space_light_direction = cameraToTangent_tbn * camera_space_light_direction;
//do lighting in tangent space.

```

They both get the light direction into tangent space. You can even do things directly from model space (which is what I suggest):

```
mat3 modelToTangent_tbn = mat3(
  tangent,
  bitangent,
  normal)
vec3 tangent_space_light_direction = modelToTangent_tbn * normalCameraToModel * camera_space_light_direction;
//do lighting in tangent space.

```

That requires transforming the camera-space light direction into model space, so you need a matrix to do that. Or you could do that transformation on the CPU and save time, so you'd be passing the model-space light position/direction.

So there isn't just one possible TBN matrix; there are many forms. It's all about what space you want to transform from and to.

And this is just my personal opinion, but if you see a tutorial that suggests you do lighting in world space, stop reading it. Read something written by someone who's *not* an idiot.

As for transpose guy, he is simply wrong. The transpose of a pure rotation matrix is its *inverse*, so what he's doing is take a matrix that transforms from normal space (the space the normals are in, which as shown above is dealer's choice) to tangent space and doing it backwards. The goal of that is to transform the normal fetched from the tangent space bump map into the space of the normals, so that you can do your lighting computations in a space other than tangent space.

His erronous assumption is that the TBN matrix *is a rotation matrix*; it isn't. TBN matrices will almost never be orthonormal; even if you compute the bitangent by cross-product, the normal and the tangent do not have to perpendicular, and they often will not be. Indeed, they should only be perpendicular if the surface is flat. The tangent and bitangent point along the flow of the surface in the S and T components of the UV. That's almost never in the plane of the normal.
> 4 votes

---
Tags: opengl, glsl, normal-mapping
---


# Question
Title: How to create a similar 2.5D art style character
EDIT: I am asking about the characters not the 2.5 scene

I am the graphic designer of a game and I want to recreate the look and feel of these images:

My questions are:

1. Does this style have a specific name?
2. Can you link me to tutorials for this game style?

# Answer
As for your first question, do you mean Weebles? Matryoshka dolls? Have you heard it called something before? I can't seem to pinpoint a certain term, but perhaps you can be the first to call it something!

The shading is basically a gradient of darker values toward the bottom of each major part of the character (body and head) and lighter toward the top.

As for the general style, seems like Hello Kitty anime, with a big head and small body. Maybe a form of Chibi Animation?

What came up in a 5-minute google search:

http://tvtropes.org/pmwiki/pmwiki.php/Main/InvisibleAnatomy

http://en.wikipedia.org/wiki/Super\_deformed

http://www.youtube.com/watch?v=0Fr4\_0YHrA4

Again, probably a question for a graphical art stacks exchange hub.
> 2 votes

---
Tags: 2d, graphics, art, 2.5d
---


# Question
Title: Level/Map file creation and processing with OpenGL
How do levels/maps work in the game development world? Counter strike, which is a popular FPS that uses OpenGL as it's graphics library, has it's levels/maps created as \*.bsp files. How do you create files like this, and use OpenGL to load them?

Thanks!

# Answer
This will depend a lot on your game.

Counter-Strike, or any source engine game or any Quake derivative, and most other FPSs will have custom editing tools for the actual act of crating a level. That tool will bake the specified static meshes into the format by applying some algorithm. That format will be a spacial index. In the example case, BSP stands for binary space partition. You will basically be separating (and in some cases splitting) polygons into groups based on their location so it will be quick to query what polygons are visible from a location in a direction. Now days there will be various BSP implementations of with different optimizations since the initial BSP design from Quake.

Now days you can probably scrap custom editing tools for a general purpose 3D editor and just parse the file it outputs.

In addition to that you will have dynamic objects that can move about that won't work in a BSP (the structure just doesn't support making alterations at runtime with any decent levels of efficiency). The objects will just link their position to their object informations (such as the 3D mesh to draw at the location).

BSPs date back to the original Quake engine. Now days it might be a better idea to use an object based approach rather than a giant polygon mesh. For example Skyrim uses a modular level design. Basically rather than keeping everything as a giant mesh of polygons, you will just have a list of objects and their positions, the actual mesh will be stored separately.

BSP isn't the only spacial index around. It's good for indoor environments such as FPS shooters. For an outdoor game like GTA you might do better with an Octree (or Quadtree for flatter game worlds). Those 2 are able to be used for both lowlevel polygon level storage or higher level object level storage (off hand I'm not sure if BSP would be useful for objects).

In addition to the raw mesh data, there are extra things you can bake in. For example if you know your mesh is static and your lights are static then you can prerender the lights into a lightmap. Basically it's an extra texture that is applied to the polygons of the level for light the lights brightness so you don't have to do it at runtime. You increase your memory but save runtime processing. You could even look at hooking up a whole raytracer so you get raytrace quality lighting (although the generation would be very slow, but the resulting quality would be great).
> 1 votes

---
Tags: maps, levels, binary-space-partitioning
---


# Question
Title: Android Loop : Draw Loop : How to pull off smooth FPS?
I am writing 2D side scrolling bullet hell-like game. I am at a point where I struggle to pull off smooth fps. I have separated loop that manages drawing.

However I want update the position of sprites from game logic(for bullets). Since there are many bullets, waiting for new set of position significantly decreases the speed in which the drawing loop executes itself.

I thought about another approach like this:

I could upload and stack positions of bullets somewhere. So my drawing method can pull off only the previously completely uploaded data, but doing so it can free itself from worrying about waiting for updating since stacked data is already in there. however \<- that approach seems counter intuitive.

# Answer
I read from a book (the book is "Starting android game development") that the Garbage collector is your worst enemy at the moment of making a game. That's because it takes time of it's own to recycle objects.

So **try to reuse your bullet instances instead of trashing them**. That way you will not necessarily run out of memory. Also try to keep a static count on bullets and fix a max number of them. If you use some kind of list you can even stack them for recycling.
> 3 votes

# Answer
The idea you describe is sound. See Replica Island for an example of a game that generates "draw lists" in one thread, and renders them from a `GLSurfaceView` draw callback.

The only tricky part is to make sure that keep the lock held for as little time as possible, so you don't stall the renderer. Since your game state updates are expensive, you'll want to do the slow updates into a "private" data structure, then grab the lock, update the draw list, and release the lock.
> 2 votes

---
Tags: android, performance, game-loop
---


# Question
Title: Why would you use a negative value for Bounding Box?
I have the following code I'm working with in XNA from the book Professional XNA Programming.

It's just pong on a 2d screen plane. We use bounding boxes for collision detection. I'm just having trouble understanding why we would use a negative paddle size for the RedPaddleBox. I read bounding boxes define the minimum and maximum corners of the box, but I'm not sure what that means--minimum in terms of coordinate values? If so, why use a negative value when the paddle isn't partly off screen?

This is the code line that gave me trouble:

```
            new Vector3(-paddleSize.X/2,

```

in context of:

```
        BoundingBox leftPaddleBox = new BoundingBox(
            new Vector3(-paddleSize.X/2,
                leftPaddlePosition-paddleSize.Y/2, 0),
            new Vector3(+paddleSize.X/2,
                leftPaddlePosition+paddleSize.Y/2, 0));

```

in the following code:

```
        // Check for collisions with the paddles.
        // Construct bounding boxes to use the intersection helper method.
        Vector2 ballSize = new Vector2(
            GameBallRect.Width / 1024.0f, GameBallRect.Height / 768.0f);
        BoundingBox ballBox = new BoundingBox(
            new Vector3(ballPosition.X - ballSize.X / 2,
                ballPosition.Y - ballSize.Y / 2, 0),
            new Vector3(ballPosition.X + ballSize.X / 2,
                ballPosition.Y + ballSize.Y / 2, 0));
        Vector2 paddleSize = new Vector2(
            GameRedPaddleRect.Width / 1024.0f,
            GameRedPaddleRect.Height / 768.0f);
        BoundingBox leftPaddleBox = new BoundingBox(
            new Vector3(-paddleSize.X/2,
                leftPaddlePosition-paddleSize.Y/2, 0),
            new Vector3(+paddleSize.X/2,
                leftPaddlePosition+paddleSize.Y/2, 0));
        BoundingBox rightPaddleBox = new BoundingBox(
            new Vector3(1-paddleSize.X/2,
                rightPaddlePosition+paddleSize.Y/2, 0),
            new Vector3(1+paddleSize.X/2,
                rightPaddlePosition+ paddleSize.Y/2,0));

```

# Answer
Mathematically, it's super-convenient when ranges go from -1 to +1 (`[-1,+1]`). All kinds of formulas and such are just way more powerful if you make that assumption, one reason being that when scaled it has further mathemetical meaning than other arbitrary coordinate systems (like using a corner). It can hence be useful for a bounding box to be represented as `<-1,-1>` to `<+1,+1>` scaled by the half-sizes of the box with `(0,0)` being the center of the box.

That is, for a box with dimensions `<2,4>`, you'd give it the min/max vectors `<-2/2,-4/2>=<-1,-2>` to `<+2/2,+4/2>=<+1,+2>`, dividing by 2 because you want the *half-sizes* here. You use the half-sizes because that represents a width of `+1-(-1)=2` and a height `+2-(-2)=4`, which are the original dimensions, and they nicely represent that `[-1,+1]` scaled up to represent those dimensions.

Now you might want to also encode the object's position with its bounding box in some cases. Or you might want to store it separately. Depends on what specifically you use the bounding box for. It's certainly more common to add the object's position to its extents to change from offsets from the object's center into points representing the outer vertices of the object in the world. Sometimes this is not done, though.

Part of understanding this is understanding coordinate system. Positions are given *relative* to some other position. If I tell you I'm 5 miles East of a particular landmark then you need to know where that landmark is in order to know where I'm at. Hence you can give coordinates in a game relative to an object, relative to some arbitrary "center" of the level, or whatever else you want. A simple bounding box's extents are relative to the center of the object. In order to know where those corners actually are, however, you must know where the box is. That's why you calculate the extents of the box as if the center is at `(0,0)` (*object-space* or *model-space*) and can translate them to *world-space*.
> 3 votes

# Answer
If we take the paddle position as defining the center of the paddle:

To find the top edge we need to find the value that is half of the paddle height less than that center point.

This code achieves that goal:

```
leftPaddlePosition-paddleSize.Y/2

```

Note: I think there is a typo in the code for the Y-axis component of the first Vector3 used to define the rightPaddleBox, as I read it the '+' should be a '-'.

**Edit:**

The left paddle's horizontal range is 0-paddleSize.X/2 to 0+paddleSize.X/2

The right paddle's horizontal range is 1-paddleSize.X/2 to 1+paddleSize.X/2

They will both extend beyond the screen but will appear symmetrical to the player. The author may have done this so the code is repetitive/formulaic and may be easier to understand.

In my opinion the (implied) 0 for the left paddle and the 1 for the right should be variables rather than magic numbers, this way it would be easier to shift them if you wanted.
> 1 votes

---
Tags: xna, bounding-boxes
---


title: Generating spritesheet(s) on load

text:
# Question
Title: Generating spritesheet(s) on load
I would like to reduce the size of the spritesheet I am loading by only loading the specific sprites I need. Is there a way to crop and splice images at runtime using javascript? Creating separate spritesheets for each level is not ideal, as that would mean lots of repeated sprites.

*edit for clarification*: Say I want to replace the 5 sprites in the top right corner of my spritesheet based on user input. Is there a way to remove the sprites that are there and replace them with some from a different file?

# Answer
> 3 votes
Sure. You can create an offscreen canvas:

```
var modifiedSpriteSheet = document.createElement('canvas');
//Your dimensions here
modifiedSpriteSheet.width = 400;
modifiedSpriteSheet.height = 400;
var modifiedContext = modifiedSpriteSheet.getContext('2d');

```

...and draw exactly which graphics you want to use to the context. Of course, the images you are pulling from will have to finish loading first.

```
if(userInput === 34) { //Whatever your logic is...
    modifiedContext.drawImage(img1, 0, 0, 32, 32, 64, 0, 32, 32);
} else {
    modifiedContext.drawImage(img1, 32, 0, 32, 32, 64, 0, 32, 32); //Different!
}

```

When finished with logic, you can then draw the off-screen canvas you created and use it as if it were an image.

```
drawingContext.drawImage(modifiedSpriteSheet, 64, 0, 32, 32, 0, 0, 32, 32);

```

That should be all!

# Answer
> 1 votes
You are overthinking it, if you want to do context dependent loading just make one sprite sheet for the common graphics and one for each specific context. There is no need to combine them.

# Answer
> 0 votes
Yes there is, you can make a composite image for your sprite sheet using the drawImage() canvas method out of the two original images.

---
Tags: javascript, sprites, image, spritesheet
---


# Question
Title: HLSL Pixel Shader Compile, Flow Control, Instruction Count, XNA Issue
im trying to find help with an issue im having moving from the XNA 3.1 framework to XNA 4.0. The shaders I wrote for my **2D game** work fine in XNA 3.1, but wont even compile in 4.0.

At first I got insanely huge instruction count messages, but I switched it to compile them optimized which reduced that, but still over the limit. FXC.exe compiles them fine, but XNA 4.0 wont. I am not well versed in HLSL and could use some tips on what to do without having to redesign everything drastically.

I have tried some different approaches, \[loop\] attribute, etc., with mixed results. First off here is one of them that has the issue:

```
float4 GetLightColor(float2 position)
{
    float4 color;
    position += lightOffset; // Offset position

    // Figure out which texture this position is in, then return
    // The color in that texture
    if(position.x <= (LightSize1.x + LightSize1.z))
    {
        // Top left or bottom left
        if(position.y <= (LightSize1.y + LightSize1.w))
        {
            // Top left
            float2 offsetPosition = float2((position.x - LightSize1.x) / LightSize1.z,
                                           (position.y - LightSize1.y) / LightSize1.w);

            color = tex2D(LightSamp1, offsetPosition);
        }
        else
        {
            // bottom left
            float2 offsetPosition = float2((position.x - LightSize3.x) / LightSize3.z,
                                           (position.y - LightSize3.y) / LightSize3.w);

            color = tex2D(LightSamp3, offsetPosition);
        }
    }
    else
    {
        // Top right or bottom right
        if(position.y <= (LightSize2.y + LightSize2.w))
        {
            // Top right
            float2 offsetPosition = float2((position.x - LightSize2.x) / LightSize2.z,
                                           (position.y - LightSize2.y) / LightSize2.w);

            color = tex2D(LightSamp2, offsetPosition);
        }
        else
        {
            // bottom right
            float2 offsetPosition = float2((position.x - LightSize4.x) / LightSize4.z,
                                           (position.y - LightSize4.y) / LightSize4.w);

            color = tex2D(LightSamp4, offsetPosition);
        }
    }

    return color;
}

float4 PSBaseDoorColor(PS_INPUT input) : COLOR
{
    // Get light color from one of the 4 light textures, based on world position!
    float4 lightBase = GetLightColor(input.worldPosition);

    // I dont know why getting the texture information from the
    // regular sampler through XNA doesnt work correctly??
    float4 objectBase = tex2D(BaseSampler, input.texCoord);

    float4 ret;
    bool found = false;
    bool convertColor = false;
    int testx, testy, testz;
    float3 hsv;

    testx = round(objectBase.r * 255);
    testy = round(objectBase.g * 255);
    testz = round(objectBase.b * 255);

    for(int i = 0; i < ignoreColorsTrickNum; i++)
    {
        if(ignoreColors[i].x == testx && ignoreColors[i].y == testy && ignoreColors[i].z == testz)
        {
            found = true;
            break;
        }
    }

    if(!found)
    {
        ret = float4(2*objectBase.rgb*lightBase.rgb, objectBase.a);
    }
    else
    {
        // Do we need to convert color?
        for(int i = 0; i < 16; i++)
        {
            if(baseDoorColorChange[i].x == testx && baseDoorColorChange[i].y == testy && baseDoorColorChange[i].z == testz)
            {
                convertColor = true;
                break;
            }
        }

        if(convertColor)
        {
            hsv = rgb_to_hsv(objectBase.rgb);
            hsv.x += input.color.a;
            if ( hsv.x > 1.0 ) { hsv.x -= 1.0; }

            ret = float4(hsv_to_rgb(hsv)*pulseEffect*2, objectBase.a);
        }
        else
        {
            ret = objectBase;
        }
    }

    return ret;
}

```

**The first issue** is the GetLightColor() function which I use in several other shaders as the way lighting is designed is there are predefined lights, so its all precomputed into textures, but due to texture size limits I broke down these textures into like 2048x2048 blocks. So a player character could be standing on the four way intersection of these, necessitating 4 possible texture lookups.

XNA compiler gives warnings: Warning X4121: gradient-based operations must be moved out of flow control to prevent divergence. Performance may improve by using a non-gradient operation

While only warning, it also claims the shader is using 648 instructions, which is over the limit of 512 for ps\_3\_0 ! There is more to the sahder, mainly the rgb\_to\_hsv and back conversion functions, but those seem fine.

**The second issue** is I have two hardcoded int3 arrays one has like 101 elements, the other 16, of color values that I compare in the shader to the current pixel to determine if lighting should be done or not:

```
    for(int i = 0; i < ignoreColorsTrickNum; i++)
    {
        if(ignoreColors[i].x == testx && ignoreColors[i].y == testy && ignoreColors[i].z == testz)
        {
            found = true;
            break;
        }
    }

```

At first the variable was a constant, and it seemed like the compiler was unrolling the loop, so i tried switching it to a shader variable that I would just set from C# before running, which seemed to work, but then it was giving me a new compiler error:

(257,28): error X4505: maximum temp register index exceeded

Times about 60.

I also tried using float3's instead, and doing a threshold check but same result.

Perhaps a bad way to go about all this, but I dont understand why XNA 4 is having such issues with this. Even a shader that was written ages ago for ps 2.0 it reported it way over the instruction count limit.

Any help is appreciated, thanks.

# Answer
`float3` and `float4` will in general use the same number of registers. Registers on GPUs are inherently all `float4`, with smaller vectors using up one of those. The compiler will try to be smart about it and combine smaller variables into a single register where it makes sense, but that's an optimization privilege the compiler has, not a guaranteed behavior that you can rely on as a shader author.

If-statements and loops are best avoided as much as you possibly can in shaders; when using them, try to ensure they're uniform (don't depend on per-pixel values, only uniforms). GPUs are inherently bad at branching, which is one of the costs of being able to shove 1,000+ shader cores into a single chip. Your shader code is not at all friendly to how GPUs work and the newer compiler is trying to point that out to you in its awkward way.

The gradient texture lookups are warnings because of how the hardware and math works. The way that gradients are calculated is dependent on uniform-flow. They become erroneous in some cases when in non-uniform flow control. It depends on how the texture is filtered (set outside of the shader) which is why this is a warning and not an error, but in general do all your texture accesses ahead-of-time outside of any non-uniform code-paths.

The older compilers sometimes were more permissive. There's various reasons why, but the end result is that code which gets warnings on newer versions probably wasn't working efficiently before. Don't get irritated at the newer compiler, it's just being more informative and helpful than the old one was.

For register and instruction counts, remember that D3D guarantees a *minimum* not a maximum. D3D might state that some limit must be a minimum of 512 but the hardware might support going up to 768 or 2048 or whatever else. The minimum is there to let you write an app that you know for sure will work on any hardware supporting that version of D3D, not to stop you from using more if you know your target hardware is newer and will support it.
> 2 votes

# Answer
Here's some ideas to optimize that light function, off the top of my head:

* If you just want to eliminate those compiler warnings use tex2Dlod() instead of tex2D(). I'm guessing you don't care about mip mapping since it's 2D.
* Set up your textures to use border address mode and make the border colour black. That way you can simply read from each texture and sum the results without any if tests.
* That leaves the problem of texture coordinates. Firstly those can be computed in the vertex shader which should be much quicker because there's usually less vertices than pixels, especially in 2D. The only limit is the number of available interpolators.
* The maths for the texture coordinates should also be possible to simplify significantly. Calculate the position within the top left texture, ignoring the fact that it might be outside it, because the border address mode will handle it. For the top right one simply subtract 1 from the u coordinate. The bottom ones need a similar offset in the v coordinate.
> 0 votes

---
Tags: xna, directx, graphics, shaders, hlsl
---


# Question
Title: How to render polygons of arbitrary shape?
I am trying to render a plane with nodes.

FYI : Nodes know what other nodes it is being attached to.

I can think of a way to render them as long as they are aligned in a circular pattern; have a center and draw triangles. However I want the shape to be not necessarily circular.

I have a picture below to enhance my description. Attempting to draw such a vertices with my previously stated method will result into an undesired shape, like the third picture.

# Answer
> 2 votes
If you take the points A,B,C and derive the vectors AB and BC you will find that:

```
atan2(AB.x,AB.y) - atan2(BC.x,BC.y) < 0

```

Conversely if you take the points B,C,D and derive the vectors BC and CD you will find that:

```
atan2(BC.x,BC.y) - atan2(CD.x,CD.y) > 0

```

By using this test you can identify which points define concave or convex angles.

---
Tags: 2d, rendering
---


# Question
Title: Workaround for reading and writing same texture?
To apply post effects, it is often needed to read the preliminary image, perform computations on its pixels and store the result in the same texture again. For example, think of a tone mapping or desaturation effect. The input and output should be the same texture, but this isn't allowed by OpenGL.

Therefore, what is a good workaround?

One idea I came up with but which isn't very satisfying is to have two image textures and automatically use them alternating. Also keeping track of which is the newer one to finally display it on the screen.

# Answer
> One idea I came up with but which isn't very satisfying is to have two image textures and automatically use them alternating. Also keeping track of which is the newer one to finally display it on the screen.

This is actually the way it's commonly done, and the technique even has a name: "ping-ponging".

There's some discussion on the technique here (look for the section headed "ping-pong texturing").

As for the "why", if you think about it, it makes sense. Many post-processing effects don't actually have a direct one-to-one mapping between source and destination texels (or "fragments" if you prefer; I'll just continue to use "texels" here as it may be clearer to aid understanding). Common examples would be blur and distortion effects, where the source texel position may not be same as the destination position. What this could mean is that your input could have been a texel that was previously already processed, and so is not valid.

This is leaving aside any hardware considerations, but it is worth noting that hardware can make certain assumptions ahead of time if it is guaranteed that you're not going to read from and write to the same image, and that those assumptions can lead to better performance.

If you're running an effect where you know that you're always going to have this one-to-one mapping (e.g. maybe simulating a gamma curve using FBOs) then you've got image load/store in OpenGL and that provides an option that would meet this requirement, although I'd encourage you to do a comparative benchmark before committing, as it may be the case that you'll still get better performance from doing it the traditional way.
> 3 votes

---
Tags: opengl, textures, shaders, deferred-rendering, post-processing
---


title: Manage VBO/VAO in a graphic engine

text:
# Question
Title: Manage VBO/VAO in a graphic engine
I'm trying to make a 2D Graphic engine for training me. I've actually made it with immediate draw and I've made the renderer outside (so I can switch between OpenGL and DirectX).

**How can I manage Vertex Buffer Object and Vertex Array Object?** I've made a geometry object, and I don't think VBO and VAO need to be here.

**It is the work of my renderer to manage the scene?** (Group object in a large VBO, hide object out of screen, Order object by transparency, …)

More explications on my architecture:

* Spacial : Spacial element containing spacial elements (like a node).
* Mesh : Object with a geometry and a material
* Scene : Manage spacial element (like mesh) and lights.
* Renderer : Draw the given scene (mesh and lights)

Where I should manage buffers (Index buffer, Vertex Object Buffer and Vertex Array Buffer)? In first, I started to put them in the Geometry class, but it seem obvious because a buffer can stock multiple Geometry object.

So, I'm thinking to put buffers in a buffer manager (in the scene object) -\> Scene can manage meshes (order + static/dynamic to regroup them in buffers).

What do you think about that?

Thanks!

# Answer
> 5 votes
If this is for desktop OpenGL or OpenGL|ES 3 and you're doing a common 2D sprite-style engine, you won't have a lot of repeat geometry. Everything is quads. You only need a single vertex buffer and index buffer (describing a quad). Use *instancing* to put all the transformation matrices for your scene objects into a single buffer and then draw that single quad X times (where X is the number of sprites you're drawing) with a single draw call. No need for dynamic buffers, no need to store buffers with "sprites," etc. Even with a fairly complex multi-part sprite animation system, each part is typically just a single quad, all arranged in a tree. You can still render multiple sprites/parts with a single draw call.

Generalizing to 3D (and some more complex 2D needs), each mesh would store the VBO of its attributes and an index buffer. Your renderer would try to group these together to use instancing; that is, if you're drawing 20 copies of the same mesh, only call draw once but use instancing to make that draw call draw all 20 copies. In 2D, there may be some use for this for more complicated objects, like paths or shapes that you need to triangulate, though usually sprites are enough.

For older OpenGL support or OpenGL|Es 2 you can't use instancing. In this case, just keep a single "large enough" VBO for a decent number of sprites. When your scene draws, first insert a transformed quad into the buffer for each object. That is, transform the vertices of a standard `(-1,-1),(+1,+1)` quad on the CPU to get the world positions of the quad representing that object, then copy those vertices into the VBO (and update the index buffer too, of course). Then draw that single buffer. You may need to split up rendering if your buffer can only hold X objects but you have X+Y objects to draw. E.g., if your buffer can draw 1000 but you have 2456, you'd make three draw calls: one for the first 1000, another for the second 1000, and a third for the remaining 456. In your VBO building loop, just check if the buffer is full after adding each object, and if so, draw and flush the buffer.

Just remember to *discard* the buffer before reusing it that same frame using `glBufferData(vbo_id, 0, NULL, GL_DYNAMIC_DRAW)` otherwise you'll stall the pipeline (you can't update a buffer while the GPU is rendering from it). You that call or the newer GL API to discard buffers (I forgot what it was), not `glDeleteBuffer`, which is something else entirely (recreating a new VBO every time is much slower than discarding a buffers contents).

# Answer
> 0 votes
It depends on how large your buffers are going to be, their usage, and how you work with your shaders.

If you have large static buffers then you should really be grouping them with your mesh and then have your renderable nodes reference their mesh, but since you are talking about 2d I can't imagine this is going to be your style. For 3d meshes that makes a lot of sense though.

For 2d I personally would just create 1 giant dynamic usage buffer that holds enough for say 10k objects, so 10000x2x3 points assuming you are basically working with 2d sprites. Then just you could update sub-sections of that buffer which lines up to an object or the whole thing. This would mean that each renderable scene node would have something like a offset into the buffer.

It may not be efficient for updating and may be difficult due fragmentation and order dependent transparency but it would be pretty efficient for rendering if you could use texture lookups and render it all in a single shader with a single call. If transparency is a big issue you can just be lazy and use multiple layers - thus multiple buffers or calls - like they've done in 2d games for generations.

---
Tags: opengl, architecture, vbo, vao
---


title: 3D drawing precision problem. XNA

text:
# Question
Title: 3D drawing precision problem. XNA
I have a simple scrolling camera positioned 2000 units about the 3D 'floor' that moves forward by 1 unit every frame and looks down on the floor at a point that also moves forward by 1 unit every frame in the same direction.

I am then drawing a sphere where the mouse coordinate ray (unprojected from near plane to far plane) is intersecting the plane parallel to the floor plane but at height 2000 (the same plane that the camera position is). I am using this technique to acheive this:

http://msdn.microsoft.com/en-GB/library/bb203905(v=xnagamestudio.40).aspx

The intended behavior is for the camera to be looking down at a scrolling world and the sphere to exist on the 2000 height plane with its center where the mouse is pointed at.

This works fine for about 30 seconds, but then I notice that the sphere starts jittering forwards and backwards after a while, this increases with time. The scroll direction is only in the -z direction (forward) so it seems related to the growth in total scroll amount. I am thinking this might be a precision problem. I debugged the first three sphere location calculations and got these results:

```
z = -466.2891f
z = -465.2905f
z = -464.3159f

```

I then paused again when it started jittering and got these results:

```
z = 3848.743f
z = 3849.764f
z = 3850.956f

```

I am guessing the jittering starts as the Z number goes into the thousands and worsens as it goes into 10,000 e.t.c. The levels of the game won't extend past 10 minutes so my solution doesn't need to work past a certain Z value but the current solution doesn't work past 30 seconds.

I cannot change to double precision as I am using the XNA built in structs which all use floats. I also want to avoid scaling everything down as I don't want to rescale all the assets in the game. Is this another solution to this problem?

EDIT:

The game is fixed time step and I changed the code to make the scrolling every frame a constant amount.

I have done some further debugging and I noticed that if I do the following conversion:

screen coords -\> world coords -\> screen coords. All using XNA inbuilt methods. I see that the ranges of the delta between initial screen coords and output screen coords gets larger over time. This means to me that the drawing code is likely correct and it might be something to do with the conversion code or the camera itself. I have fixed the mouse cursor position to the middle of the screen and I have checked that the scrolling logic works correctly. It does a simple addition of z:-1 every frame.

**The calculation of the viewMatrix:**

I don't think this is the culprit but the code was as follows:

```
        lookingAt = scrollPosition;
        position = new Vector3(lookingAt.X,
            lookingAt.Y + (float)Math.Cos(angle) * distance,
            lookingAt.Z + distance * (float)Math.Sin(angle));
        viewDirty = true;

        viewMatrix = Matrix.CreateLookAt(position, lookingAt,
            new Vector3(0.0f, 1.0f, 0.0f));

```
* scrollPosition: the total scroll location e.g. x:0, y: 0, z: -240
* angle: The angle that the camera is rotated around the x axis (set to 25 degrees). 0 degrees would be a straight down top-down view.
* distance: The distance of the camera position from the scrollPosition. (set to 2500f)

**The conversion of the screen coords (Mouse) to the world coords.**

yPlane is set to 1000f (height of the sphere).

```
    private Vector3 convertScreenToWorldCoordinateFlat(Vector2 position, float yPlane)
    {
        Vector3 nearsource = new Vector3(position.X, position.Y, 0f);
        Vector3 farsource = new Vector3(position.X, position.Y, 1f);

        Vector3 nearPoint = Carriers.device.Viewport.Unproject(nearsource, CameraSystem.projectionMatrix, CameraSystem.viewMatrix, world);

        Vector3 farPoint = Carriers.device.Viewport.Unproject(farsource, CameraSystem.projectionMatrix, CameraSystem.viewMatrix, world);
        Vector3 direction = farPoint - nearPoint;
        direction.Normalize();
        Ray pickRay = new Ray(nearPoint, direction);
        float? maybe = pickRay.Intersects(new Plane(new Vector3(-1, yPlane, 0), new Vector3(1, yPlane, 0), new Vector3(0, yPlane, -1)));
        float f = maybe.HasValue ? maybe.Value : 0;
        return nearPoint + direction * f;
    }

```

This code was mostly copied from the MSDN tutorial except I am intersection with a plane at height 1000f.

# Answer
I solved this problem by making everything relative to the camera position. The camera view and projection matrices don't ever change. The scroll is added to the world transformation instead of the camera position/lookat. This means that since everything on the screen is relatively close to the origin (where the camera is looking). The precision of the float is kept high as the value of the float never goes into the 1000's meaning the precision of the fractional component is never below 3 numbers.
> 0 votes

---
Tags: xna, 3d, camera, raycasting
---


# Question
Title: How can I remove the view and projection matrix from ray position to get only the ray model?
I've got a little problem with my picking module and I need your help.

I have a method to project a ray from the camera to a fixed point when I click somewhere. The computed ray looks good, it go to the asked direction and passes through the pointed box, so I'm thinking everything is OK here.

**When I'm trying to pick an object a little further from the origin, there is no intersection found.**

---

I'm sure that the ray is correctly projected and computed to the screen (I draw it) but coordinates are bad during intersection test.

---

Currently, I compute the ray with this code :

```
const glm::vec3 position    = glm::vec3( mouse.x, mouse.y, 0.f );
const glm::mat4& view       = camera.getViewMatrix();
const glm::mat4& projection = camera.getProjectionMatrix();
const glm::vec4& viewPort   = camera.getViewport();

ray.origin =  glm::unProject( glm::vec3(mouse.x, mouse.y, 0.f ),
                                        modelView,
                                        projection,
                                        viewPort );

ray.direction =  glm::unProject( glm::vec3( mouse.x, mouse.y, 0.f ),
                                            modelView,
                                            projection,
                                            viewPort );

```

So, I think the ray origin and direction are computed to world position (with camera matrix: projection and view).

When I test intersection, I use object model (without camera transformation), so I'm thinking error is here.

**The question:** *How can I remove view and projection matrix from ray position to get the ray model only ?*

Thanks a lot!

PS: To test intersection, I create a bounding box from my object's model matrix and I test intersection with the ray computed previously.

---

**EDIT:**

Code to compute ray positions in world space :

```
////////////////////////////////////////////////////////////
bool computeRayPositions( Ray* ray )
{
    glm::vec3 start = ray->getOrigin();
    glm::vec3 end   = ray->getDirection();

    glm::mat4 startMatrix   = glm::translate( glm::mat4(1.f), start);
    glm::mat4 endMatrix = glm::translate( glm::mat4(1.f), end);

    const glm::mat4& viewMatrix       = camera->getViewMatrix();
    const glm::mat4& projectionMatrix = camera->getProjectionMatrix();

    glm::mat4 startWorldMatrix  = startMatrix * glm::inverse(viewMatrix * projectionMatrix) ;
    glm::mat4 endWorldMatrix    = endMatrix * glm::inverse(viewMatrix * projectionMatrix);

    ray->setOrigin( glm::vec3 (startMatrixFinal[3][0], startMatrixFinal[3][1], startMatrixFinal[3][2] ) );
    ray->setDirection( glm::vec3 (endMatrixFinal[3][0], endMatrixFinal[3][1], endMatrixFinal[3][2] ) );

}

```

# Answer
> 1 votes
Your ray is possibly in view (camera) space. I'm unsure exactly how `glm::unproject` works. If I'm right, pass its end points through the inverse camera matrix to put then in world space.

Remember that a coordinate is expressed in some *basis*, which for our purposes can be considered a *vector space* (mathematically there is some difference) or commonly just a *space* in graphics terms. The vertices on a model are in *model-space*. You run those through the model-specific *model-world matrix* (sometimes called a model-view matrix, though that term is highly misleading IMO). Then you run the vertex through the *world-view matrix* (the *camera matrix*) to put the vertex in *view space* (*camera space*). Then finally you run through the *view-projection matrix* and divide by the `W` component to end up in *NDC space*. A final step performed automatically by the graphics API is to multiply another matrix moving from NDC space to *screen space*.

To move backwards in spaces, you simply use the *inverse* of the corresponding matrix, paying special attention to NDC space and the projection matrix (and that divide by `W`). We normally call matrices *from-to* to indicate which spaces/basis they transform from and to. The inverse of any such matrix should be named accordingly, e.g. the inverse of the *world-view matrix* is the *view-world matrix*.

`glm::unproject` is possibly doing the equivalent of multiplying by the *screen-ndc* matrix and then the *projection-view* matrix, with the `W` divide as necessary (often you can ignore it if you construct your points appropriately). This means the the output of `glm::unproject` would be in view space. You need to multiply by the *view-world matrix* (inverse camera matrix) to then take the point from view space to world space, which is generally where you'll be doing collision and intersection tests. (Although for individual model test, you'll often take the incoming ray and multiply it by the *world-model matrix*, e.g. the inverse model-world matrix, to make the math way easier and possibly more efficient.)

`glm::unproject` also takes the `modelView` matrix in your example which indicates it is maybe trying to unproject through the whole pipeline, so it's possible that it's just expecting that either the `projection` matrix or the `modelView` matrix passed in is already concatenated with the camera matrix and that its results are intended to be in model-space. You might try concatenating that matrix, or if you're looking for world-space coordinates, pass in the camera matrix as the model-view matrix.

---
Tags: mathematics, raycasting, picking, glm, intersection
---


# Question
Title: Vertices shaking with large camera position values
Basicly when i set the position of my camera (my character in game) to a high value, the geometries seems to be shaking, the higher the position value, the more they shake. On low position values you can't seem to notice any shaking.

I create a video to make it easyer to explain: http://www.youtube.com/watch?v=dxg6wIl1U1Q

In the video i'm changing to chunkAmount from 100 -\> 100000 this is a value i use in the following:

```
player.position.z = blocksize*((chunksamount/2)*blocksPerRow);
player.position.x = blocksize*((chunksamount/2)*blocksPerRow);

```

Which is something like 50'000 * 32 * 16 =\> position.x = 25600000

# Answer
Floating point values lose precision when they get larger. Keep your values as close to zero as you can. For large worlds, split them into chunks (addressed by integer chunk coordinates) and then make world coordinates relative to the "current" chunk (where the player or camera is), shifting objects whenever you move to another chunk. With this approach your world coordinates will snap back closer to zero when you move far enough, avoiding precision problems.

For instance, if you're in chunk `3,2` and your chunks are 64 units wide then the world coordinate used for the center of chunk `4,7` would be `(64,320)`. If the camera moved to chunk `4,5` then chunk `4,7` would be centered at world coordinate `(0,192)` instead, being shifted along with all of its children.

You can either update all chunk/object world positions as you move between chunks or you can store everything in a tree and recalculate hierarchical model-world matrices using the delta of integer coordinates for each chunk from the cameras chunk.

For large distances, scale down the objects being rendered. You don't need centimeter precision for a view where each pixel is roughly a meter of terrain. Use scaled coordinates for rendering if you can.

You could also switch to using doubles but then you'd need recent hardware and things will be slower; better to spend effort on fixing your world basis.
> 5 votes

---
Tags: 3d, camera, geometry, floating-point
---


# Question
Title: 2D character tile based movement problem
I am making a Super Mario like 2D platformer and I've encountered a problem. I need to move this sprite :

When a player presses the right key, the sprite moves by 32 px to the right. The process of moving the sprite is as follows :

* The sprite begins in a `StandingIdleFirstStep` state (Image 1).
* Then the sprite enters a transition state (Image 2). The sprite is moved by 16 px to the right. This state is visible for 256 ms.
* Finally, the sprite ends the movement in a `StandingIdleSecondStep` and has moved 32 px from its starting position (Image 3 - first and third step images differ).

During this entire process, the user cannot interact with the sprite. I can feed the process with a approx. 30 ms delta per frame.

Currently I'm thinking about this solution :

1. User presses move right
2. Set `moving` flag to `true`
3. Move sprite by `x+=16 px`.
4. Update sprite animation
5. Draw everything

(after 256 ms)

1. Check `if currentAnimationImageIndex % 2 == 1`.
2. If true (odd image, can't stop there), move sprite by another `x+=16 px`.
3. Update sprite animation
4. Draw everything
5. Set `moving` flag to `false`

# Answer
Try thinking this way:

**UI thread:**

1. User presses move right
2. Set `moving` flag to `true`

**Game Loop Thread, measure elapsed time between updates**

1. show current character sprite frame
2. if `moving` add elapsed time to total animation time, else show frame 1
3. if animation time \< 256ms show frame 2, if animation time \> 256ms show frame 3 (ando so on for longer walk)
4. update sprite position by distance (if it moves 128 pixels per second, move it 128 * elapsed time in seconds)
5. perform checks
6. draw everything

---

Don't try to do everything in one thread, don't let UI or waiting for another frame block the whole game.
> 0 votes

---
Tags: animation, sprites
---


title: How do I use Opengl 3.2?

text:
# Question
Title: How do I use Opengl 3.2?
My computer is using OpenGL 3.1 and I want to develop in OpenGL 3.2 but I don't know how. Thanks in advance all help is appreciated.

# Answer
> 3 votes
Your computer needs to have a graphics card and driver that supports a version of OpenGL before you can test it on your machine. Since OpenGL is a specification, you could technically write and compile code that uses OpenGL features that are not supported on your system, but you're not going to have a way to see if it works.

The first thing that you should do is check for graphics card driver updates. Often times, it's just the drivers that need to be updated. The next thing to do is see if the features from OpenGL 3.2 you want are available as extensions. If so, then just use the extensions and you're set.

Worst case scenario, you upgrade your graphics card (assuming you're working on a desktop) and get OpenGL 4.3+ as well. You could also try testing the parts of your code that rely on 3.2 features on a friend's machine that has support.

---
Tags: opengl
---


title: OpenTK 2D Engine

text:
# Question
Title: OpenTK 2D Engine
I'm looking for a 2D gaming engine for C#/Windows. OpenTK seems reasonable, albeit made for 3D. I didn't find anything (other than an old thread from 2008) that talks about a 2D game engine.

Are there any decent (well-supported, free) 2D game libraries for OpenTK?

# Answer
Try MonoGame, it's a multi-platform (Windows, Android, iOS, Linux, Xbox) port of XNA and is in active development. It uses some OpenTK under the hood (for platform specific capabilities on non-Microsoft systems) but provides an easier level of abstraction for 2D game development.
> 1 votes

# Answer
You could also take a look at Duality. It's a complete game development framework (engine + editor) that is open source, based on OpenTK and completely written in C#. Here's a tutorial.
> 1 votes

---
Tags: opentk
---


# Question
Title: CCParticleSystemQuad works as intended every second time
I'm using CCParticleSystemQuad for particles, loading it from plist:

```
flourEmitter = [CCParticleSystemQuad particleWithFile:@"FlourParticles.plist"];

```

But it works not every time. Every second or third time I start a game, particles look different from what I've set them up and there are errors saying it couldn't load image.

> ```
> cocos2d: CCTexture2D. Can't create Texture. cgImage is nil
> cocos2d: Couldn't create texture for file: in CCTextureCache
>
> ```

Of course the image is there and the next time i launch game it works as intended.

I cannot think of any ways how to debug this error.

# Answer
> 0 votes
I've made my filenames lowercase and problem disappeared. It looks like little tricks from '90-ties still work.

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


# Question
Title: When should I use skill trees versus skill lists in an RPG?
What are the pros and cons of skill trees versus flat skill lists in role playing games? In what situations is one more appropriate than the other?

Here is an example of a **skill list**, taken from *Elder Scrolls IV: Oblivion*:

Here is an example of a **skill tree**, taken from *Diablo II*:

Some additional questions:

1. Are skill trees inherently more complex than skill lists?
2. Do skill lists tend to broadly cover a character's abilities, while skill trees focus on specific spells or aspects of a character?
3. *The Elder Scrolls: Morrowind* uses skill lists and has a skill called Athletics that was removed in Skyrim. Do skill lists' loose coupling of skills make it easier to create useless or irrelevant skills?

# Answer
### Summary: Lists provide more agency, while trees provide more easily anticipated results that are simpler to balance and utilize in design.

To be as concise as possible, the difference between lists and trees of decisions is the level of freedom the individual making the choices has.

When speaking of skills and character progression specifically, lists such as found in Elder Scrolls provide freeform decision making. Trees provide a more guided approach, usually representing classes or sub-classes of some form. There is less freedom in character progression/creation, as the concept of a tree necessitates requirements to unlock latter levels/branches.

The freeform list provides a greater sense of agency for the player, allowing a greater number of options. The more guided tree provides a simpler system to consider and anticipate as a designer, resulting in a system easier to balance. So, the end result is that you have a choice for a potentially more balanced system versus a system that provides more agency.

To answer your edit questions:

1. Complexity largely depends on the specifics of implementation. However, all else being equal, a freeform system is far more complex as the potential number of results are significantly higher.
2. Yes, the traditional usage of the two is for lists to be atomic actions (such as Elder Scrolls' system) while trees are used for "Perks" or "Abilities" to simulate a focus on developing enhanced skills in a specific domain. However, this is hardly a requirement.
3. Much changed between Morrowind and Skyrim, largely due to a number of decisions far too complex to attribute simply to "using a list-based skill system".
> 10 votes

# Answer
There are no pros and cons. These two methods fulfill different requirements.

A **skill tree** works usually better in a scenario, where:

* The skill points are limited,
* Skills provide a more significant advantage,
* The game 'feels' better, if the player characters are more specialized (the character classes / roles are easier to distinguish).

The **Elder Scrolls - style** skill advancement is on the other hand:

* More realistic,
* Encourages players to try many different approaches (*the player won't have a significant disadvantage if he switches from melee to magic at level 30, for example*),
* Easier to balance,
* Provides a feel of continuous progression (no ***"the best skill is unlocked at level 30 in the fire magic skill tree, I'll just try to survive until then"*** effect).

In my opinion, the Elder Scrolls approach is more viable in a single-player game. **The player doesn't have to start over if he wants to try a different play style**. In Morrowind for example, you can be an armored melee fighter for the first 30 levels or so - and then decide to try the thieving skills / quests without receiving any penalty (or having to create a new character and start from level 1).
> 5 votes

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


# Question
Title: Input events not working simultaneously on android devices in libgdx
I am making a simple platform game in Libgdx... in which I have made the player to move left, move right and jump. The code works fine on Desktop but on Android devices, Jump is not fired when the player moves left or right. It looks strange. Here is my code...

private void updatePlayerForUserInput(float deltaTime) {

```
    // check input and apply to velocity & state
    if ((Gdx.input.isKeyPressed(Keys.SPACE) || isTouched(0.87f, 1,0,1f)) && world.player.grounded)
    {
        world.player.velocity.y += world.player.JUMP_VELOCITY;
        world.player.state =2;
        world.player.grounded = false;
    }

    if (Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A) || isTouched(0, 0.1f,0,1f))
    {
        world.player.velocity.x -=world.player.MAX_VELOCITY;
        if (world.player.grounded)
            world.player.state =1;
        world.player.facesRight = false;
    }

    if (Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D) || isTouched(0.2f, 0.3f,0,1f))
    {
        world.player.velocity.x =world.player.MAX_VELOCITY;
        if (world.player.grounded)
            world.player.state =1;
        world.player.facesRight = true;

    }
}

private boolean isTouched(float startX, float endX , float startY, float endY)
{
    // check if any finge is touch the area between startX and endX
    // startX/endX are given between 0 (left edge of the screen) and 1 (right edge of the screen)
    for (int i = 0; i < 2; i++)
    {
        float x = Gdx.input.getX() / (float) Gdx.graphics.getWidth();
        float y = Gdx.input.getY() / (float) Gdx.graphics.getHeight();
        if (Gdx.input.isTouched(i) && (x >= startX && x <= endX) && (y>=startY && y<= endY))
        {
            return true;
        }
    }
    return false;
}

```

I took the idea from the demo platform game SuperKoalio by mzencher at

https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/superkoalio/SuperKoalio.java

Please suggest

# Answer
I think you should try `Gdx.input.getX(i)` and `Gdx.input.getY(i)`

From the Gdx.input source:

```
/** @return the last touch x coordinate for the first pointer in screen coordinates. The screen origin is the top left corner. */
public int getX ();

/** Returns the x coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The pointer id
 * identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 is the second and so on.
 * When two fingers are touched down and the first one is lifted the second one keeps its index. If another finger is placed on
 * the touch screen the first free index will be used.
 *
 * @param pointer the pointer id.
 * @return the x coordinate */
public int getX (int pointer);

```

Edit:

LibGDX supports having multiple pointers when running on a compatible device. As the documentation above states each touch is assigned the lowest available ID but retains it's ID for the duration of the touch. This can get complex when tracking more involved gestures but should be trivial when simulating buttons. I haven't heard of an android device that supports more than 10 fingers at once so I would just set the for loop to query pointer IDs 0 through 9.

It sounds like either your update loop is missing gravity & friction or your input is "sticky" (i.e. behaving like a button that is jammed down). If you add a line just before `return true` in `isTouched(...)` that prints the value of `startx` to the log then you will be able to see if / when it plays up.
> 3 votes

---
Tags: libgdx, input
---


# Question
Title: 2D collision resolution: works on each axis individually, but not with both combined
My collision detection method is solid and detects box to box collision every time. Then comes the resolve part which I'm struggling with quite a bit. It works perfectly when I'm manipulating the x-axis and y-axis of the player (tile) but only happens to work when I move on any given axis individually. If I try to move on both axis then the whole thing breaks down and starts acting weird.

I'm trying to implement gravity. And so I keep a constant down force on my player tile. This is when I realized that when I'm applying force on both axis (because gravity is constantly applying force on the y-axis) and moving the player tile right or left on the same time my collision resolve method breaks down.

My collision is working great while moving along each axis individually. Here's the result:

**How can I approach collision resolution in order to avoid this type of result?**

I'm currently predicting the position the player *will* be at, then I'm checking every single collideable tile at that position. If I detect a collision, I move the player back along the axis the collision was detected in.

This is my current code with collisions working well on a single axis at a time:

```
void Tile_Player::Move(double delta, G3::Tile_Map *map)
{
    int xvel = (this->xDirection * (G3::TILE_STEP * (delta/1000)));
    int yvel = (this->yDirection * (G3::TILE_STEP * (delta/1000)));

    G3::xy_pos predictedPos;
    predictedPos.x = this->tile_location.x; predictedPos.y = this->tile_location.y;

    predictedPos.x += xvel;
    predictedPos.y += yvel;

    bool collision_status = false;

    for (int i=0; i< map->GetTotalTileCount(); i++)
    {
        G3::Tile *tempTile = map->GetTileAt(i);
        if (this != tempTile)
        {
            bool coll_bool;
            coll_bool =  this->CheckCollision(predictedPos, tempTile->GetTilePos());
            if (coll_bool)
            {
                //check collision on the left
                if (this->xDirection == -1)
                {
                    predictedPos.x = tempTile->GetTilePos().x+G3::TILE_SIZE+0.1;
                }
                //check collision on the right
                if (this->xDirection == 1)
                {
                    predictedPos.x = tempTile->GetTilePos().x-G3::TILE_SIZE-0.1;
                }
                //check collision on bottom(ground)
                if (this->yDirection == -1)
                {
                    predictedPos.y = tempTile->GetTilePos().y+G3::TILE_SIZE+0.1;
                }
                //check collision on top
                if (this->yDirection == 1)
                {
                    predictedPos.y = tempTile->GetTilePos().y-G3::TILE_SIZE-0.1;
                }

            }
        }
    }

    this->tile_location.x = predictedPos.x;
    this->tile_location.y = predictedPos.y;

    this->xDirection = 0;
    this->yDirection = 0;
}

```

# Answer
In the part of your code where you use 'coll\_bool' to check if there was a collision, I believe you also need to check if your object is colliding only on the X or Y axis.

For example if your object collides with a wall while falling (although there is Y movement it's only colliding in the X axis) you will still check for the Y direction (movement direction, which in this case does not mean there is a collision in that direction) and set the Y position to an unexpected value. I guess your object would instantly move 1 tile downwards.

Might this be your problem?
> 2 votes

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


# Question
Title: Problems implementing a Sign Sprite in Libgdx
I am making a tile based game in LibGdx. I am using the TiledMap in .tmx format. I want when my player reaches a tile whose property is set (tileType -\> sign), he should see a Sign sprite and on colliding which, he should see the signScreen (small) in the Parent screen game screen. Here is my code

//calling this method at the beginning ...in create()

```
    TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1);
    //test ="layer selected :-> "+layer;
    TiledMapTile tile;

        for(int y=0; y< mapHeight;y++){
            for(int x=0;x<mapWidth;x++){

        //Step-1: Search within the level map where should we construct a Sign
        //*
                try{
        tile = layer.getCell(x,y).getTile();

        if("sign".equals(tile.getProperties().get("tileType").toString())){
        layer.setCell(x, y, null);

```

//creating my sign sprite deleting that tile .. at the same position signs.add(new Sign(x , y , signCount++));

```
        }

    }
        catch(NullPointerException e){
            System.out.println("While Searching Tile for Sign ->"+e);
        }
            }
        }
}

```

But this code is not working. I checked ...things look Ok. But if I am placing this code in the collision detection code, where I am checking collision of player with the Layer of map. It works. But I do not want to put the code there.Because, if I am searching and replacing for the tile there..it outputs as if...........

"when the player reaches there and touchs the sign, then my Sign sprite becomes visible and at the same time, the child screen appears"....But I want all the tiles that I have marked as (tileType -\> sign) should be checked at the beginning and replaced with my Sign Sprite.

Please suggest

Is there any problem with the above code or the loop Is there is any other way to implement such a sprite that can communicate to player through a small screen .. i.e. illusion of telling something.

# Answer
First off I would really try to avoid using null in game logic. Inherently it strips away all information about the state. Does null mean nothing is there? There was a failure? There was a success and no problem? Its vague. You are probably the only one working on your project, so you know what your wrote. But no one else will, and you probably won't if you come back to this project 6 months from now.

I would make your collision engine detect multiple things, not just invalid tiles. You could make an enum of collision types like : offscreen, sign, etc. Also you don't have to remove the tile to put a sign there. If you render the tilemap first you can then just draw the sign sprite over it. Or you could even put the sign in your tilemap if you want.
> 1 votes

---
Tags: tiles, libgdx, maps
---


# Question
Title: Scale Matrix Transform without moving primitive
So I have the following....

```
GLbyte vShaderStr[] =
  "attribute vec4 vPosition;    \n"
  "uniform mat4 move;           \n"
  "uniform mat4 scale;           \n"
  "void main()                  \n"
  "{                            \n"
  "   gl_Position = vPosition;  \n"
  "   gl_Position = move * gl_Position;  \n"
  "   gl_Position = scale * gl_Position;  \n"
  "}                            \n";
...
void glScale2D(float y, float x){
float zoom[16] = {
    x, 0, 0, 0,
    0, y, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
};
GLint projectionUniform = glGetUniformLocation(userData.programObject, "scale");
glUniformMatrix4fv(projectionUniform, 1, 0, &zoom[0]);
}
...
glScale2D(userData.widthScreen/userData.heightScreen, userData.heightScreen/userData.widthScreen);

```

This works, however, it also moves the primitive so it goes from...

To...

Is there a matrix I can use to scale the primitive without moving it?

# Answer
> 2 votes
It seems that the problem here is that you have only one coordinate space, a fusion between the world space and the object space. Scaling your object impacts its position because the coordinate space where the scaling occurs isn't centered on the origin object.

To fix this issue, you need to have two different coordinate spaces: the object space, and the world space. You set the vector of your object in its own object space, around its point of irigin, which is the one you will scale, and then you use the world space to put the object at the right position.

You need to represent your object in its own coordinate space :

```
      X     Y    Z
a:   0.0  -0.5  0.0
b:   1.0   0.5  0.0
c:  -1.0   0.5  0.0

```

Here, a triangle centered around the origin point `(0;0;0)`.

Then, you transform the object space with a scale matrix, let's say with twice the size in both X and Y. You do that by multiplying a scaling matrix, just like you did in your code. You get :

```
      X     Y    Z
a:   0.0  -1.0  0.0
b:   2.0   1.0  0.0
c:  -2.0   1.0  0.0

```

And finally, you transform the object-space coordinate system to a world-space coordinate system by multiplying with an object-to-world matrix. In this case, this matrix would be a translation matrix, given that you don't want your object to be at the origin point of the screen. Let's say you want the center of this object to be at `(10.0; 20.0; 0.0)`. With the translation applied, you get :

```
      X     Y    Z
a:  10.0   9.0  0.0
b:  12.0  11.0  0.0
c:   8.0  11.0  0.0

```

As you can see, the position of the object isn't impacted by the scale anymore. You can change the scaling ratio of the object without impacting its position in the world.

# Answer
> 1 votes
You can apply a 2D or 3D scaling matrix along the major axis by multiplying the x/y/z components by the appropriate scaling value. Here are two examples of scaling matrices, in 2D, and 3D, using row matrices.

```
2D: | 0.5f, 0.0f |
    | 0.0f  0.5f |

    | 0.5f, 0.0f, 0.0f |
3D: | 0.0f, 0.5f, 0.0f |
    | 0.0f, 0.0f, 0.5f |

    | 1.0f, 0.0f, 0.0f |
3D: | 0.0f, 2.0f, 0.0f |
    | 0.0f, 0.0f, 1.0f |

```

These will each scale a vertex by half along each axis. The third example demonstrates a scaling of 2.0, on only the Y axis. Again, using row matrices. These are simply modifications of the identity matrices.

**EDIT** I suspect the source of your problem is that you are performing scaling to the object in the incorrect coordinate space. Applying scaling to an object in world space will scale it relative to the world origin. You most likely want to scale it relative to the objects origin, which means you need to scale the object when operating on object coordinates.

---
Tags: opengl-es2
---


# Question
Title: Simple Android loading screen when using OpenGL
My game uses openGL ES 2.0 on Android and it's got to the point where the pause (while loading resources) has become noticeable.

All I'm after is to show a static screen (probably via an XML layout if it's the simplest way, but through openGL is OK too). And then dismiss the view and switch to the game.

I'm loading my resources in the onSurfaceCreated method of my GLSurfaceView class and creating my sprite objects in my onSurfaceChanged method (I need the width and height to scale them, so do it here, plus Google's docs recommend it). I don't load my resources in onCreate.

I've tried creating a simple XML layout called 'loading' and putting something like this into my glSurfaceView class's constructor (glSurfaceView being an inner class of my Activity class)....

```
public MyGLSurfaceView(Context context) {
        super(context);
        {
loading_dialog = new Dialog(context,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
loading_dialog.setContentView(R.layout.loading);
loading_dialog.show();
}

```

This displays my 'loading' screen OK, but I need to call:

```
loading_dialog.dismiss();

```

*at the end* of my onSurfaceChanged method in my GLSurfaceView.Renderer class. I obviously can't do this as the GLSurfaceView.Renderer class has no knowledge of the loading\_dialog object.

I tried to create the object directly in the GLSurfaceView.Renderer class, but I don't have access to the context from here, so I tried to pass it in from the Activity class but then I got different errors at which point, I searched the net and couldn't find a clear answer on how to do this so thought I would post here in the hope that someone could point me in the right direction.

# Answer
Thank you very much for the answer below, however, I worked out a way to do this. It works, so I am going to post here in case it helps someone else.

**In Activity class** \- in *onCreate*, get object to Splashscreen class and pass in width and height

```
    DisplayMetrics display= new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(display);
    width = display.widthPixels;
    height = display.heightPixels;

    Splashscreen splash = new SplashScreen(this.getApplicationContext(), width, height);

```

**In 'MyGLSurfaceView' class** constructor (which is an inner class of my Activity class) , I have the following:

```
public MyGLSurfaceView(Context context) {
        super(context);

            //Create dialogue which will be displayed over the GLSurfaceView while resources load
            Dialog loading_dialog = new Dialog(context,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
            //Set it
            loading_dialog.setContentView(splash);
            //Show it
            loading_dialog.show();

            //You would have already setContentView to your GLRenderer earlier in
            //onCreate, this just goes over the top of it

            //Get object to renderer class and pass in dialogue through constructor
            renderer = new MyGLRenderer(this, loading_dialog);

```

**Then** I have my splashscreen class which uses a simple view (as I only want a basic screen with the ability to add simple animation if I want to later).

```
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.View;

public class SplashScreen extends View{

Bitmap loader;
Bitmap loaderScaled;
int width;
int height;

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    //Show Scaled bitmap.
    canvas.drawBitmap(loaderScaled, x, y, null); //you can define x and y
}

public SplashScreen(Context context, int width, int height) {
    super(context);
    // TODO Auto-generated constructor stub

    this.width = width;
    this.height = height;

    //Initial Bitmap
    loader = BitmapFactory.decodeResource(getResources(), R.drawable.loading);
            //Create scaled bitmap
    loaderScaled = Bitmap.createScaledBitmap(loader, (int) (width*.25), (int) (height*.13), true);
    //And recycle the original bitmap as we no longer need it
    loader.recycle();

}

}

```

Then all you need to do is load your resources (I load mine in onSurfaceCreated). At the very end of onSurfaceChanged, just put the following to dismiss the loading screen and reveal you Open GL Renderer....

```
loading_dialog.dismiss();

```

It works, I've tested it on a couple of devices, There are a couple of small problemsso I'm going to improve it but the basics are there for a very simple splash screen. I hope it helps others who are looking for a simple solution.

PS I know instead of creating a Splashscreen class, I could simply use an XML layout, but I don't like working with XML, I find doing everything in code much more flexible.
> 2 votes

# Answer
Based on personal experience (although I haven't even touched OpenGL yet), my 2D game app has a main Screen class with different screens, independent of that XML layout do-hicky.

I'm not a total fan of XML because it can get kind of messy when trying to do more intricate things with that drag and drop graphics interface in the IDE (i.e., scaling, formatting the layout, etc.)

For me, making an abstract screen class, with subclasses like SplashScreen, LoadScreen, MenuScreen worked out with methods like update, pause, paint, etc. inherited from the abstract class.

Then, all you have to do in those screen classes is use Graphics g = game.getGraphics() in the paint method and then draw images an such for that screen. I then use touch event classes to declare a boundary where an event will occur in the update() method of that screen class like so:

```
public boolean inBounds(TouchEvent event, int x, int y, int width, int height) {
        if (event.x > x && event.x < x + width - 1 && event.y > y
                && event.y < y + height - 1)
            return true;
        else
            return false;
    }

public void updateMenuScreen() {

int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
        if (event.type == TouchEvent.TOUCH_UP) {
                if (inBounds(event, 260, 200, 300, 100)) {
                    game.setScreen(new GameModeScreen(game));
      }

```

Obviously there are some other methods and classes that would make this post huge, but I hope you get the general idea that using screen classes and "buttons" (touch events) to navigate between those screens might help you. Also, don't be afraid to use the Graphics and Canvas classes for some 2D menus.
> 0 votes

---
Tags: android, sprites, opengl-es2, loading, assets
---


title: OpenGL ES - write code in Windows

text:
# Question
Title: OpenGL ES - write code in Windows
Is it possible to write application using OpenGL ES 2.0 "emulator" from AMD (AMD OpenGL ES SDK) and then use the same code (compile again, of course) in my iOS / Android / Whatever application ? The point is, that I write code faster in Visual Studio (where I have some fancy tools). Is it possible to do it that way ?

An second subquestion. So far, I have no experience with OpenGL, I know DX 9/11. Is there a big change (besside initialization) in those APIs in term of "learn basics of OpenGL if I know DX pretty well".

# Answer
GL\_ARB\_ES2\_compatibility

> This extension adds support for features of OpenGL ES 2.0 that are missing from OpenGL 3.x.

While the intention behind this is to assist porting apps from ES2 to GL3, there seems no reason why it can't be used the other way too. So long as you strictly confine yourself to the common subset, you'll come out the other end with valid ES2 code.

Note of course that this will only apply to your *rendering* code. You're going to have a *lot* of other platform-specific code (sound, input, possibly networking, window management, etc) that will also need to be tackled, but that's nothing to do with either OpenGL or ES.
> 2 votes

---
Tags: android, iphone, opengl-es2
---


title: Is this Rotation Matrix correct?

text:
# Question
Title: Is this Rotation Matrix correct?
I'm having heavly troubles with setting up a View Matrix and a Projection Matrix. It simply doesnt work. So I think my problem is related to my rotationMatrix function. I'm using this tutorial to learn some basics about Matrix maths.

This method works fine to rotate a object in 3 angles, but I think it have a bug or something like that. So I need your help just to know if this method is doing hes job right, if so, I'll try to rewrite again all my Camera code to see if I made something wrong (I've do this 2 times already).

```
public static Matrix4 rotationMatrix(float x, float y, float z){
    //Set as Identity Matrix;
    float[] result = {
            1.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 1.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f
        };

    /*
                      Row-Major Matrix
                  ----------------------------
                 |  1       0       0       0 |
            Rx = |  0       cos(X)  -sin(X) 0 |
                 |  0       sin(X)  cos(X)  0 |
                 |  0       0       0       1 |
                  ----------------------------
                 |  cos(Y)  0       sin(Y)  0 |
            Ry = |  0       1       0       0 |
                 |  -sin(Y) 0       cos(Y)  0 |
                 |  0       0       0       1 |
                  ----------------------------
                 |  cos(Z)   sin(Z) 0       0 |
            Rz = |  -sin(Z)  cos(Z) 0       0 |
                 |  0        0      1       0 |
                 |  0        0      0       1 |
                  ----------------------------
     */

    float cos, sin;

    if (x != 0.0f){ //If it has a X value, lets compute the Matrix.
        cos = (float) Math.cos(x);
        sin = (float) Math.sin(x);

        result[0] += 1.0f;
        result[5] += cos;
        result[6] -= sin;
        result[9] += sin;
        result[10] += cos;
        result[15] += 1.0f;
    }

    if (y != 0.0f){//If it has a Y value, lets compute the Matrix.
        cos = (float) Math.cos(y);
        sin = (float) Math.sin(y);

        result[0] += cos;
        result[2] += sin;
        result[5] += 1.0f;
        result[8] -= sin;
        result[10] += cos;
        result[15] += 1.0f;
    }

    if (z != 0.0f){//If it has a Z value, lets compute the Matrix.
        cos = (float) Math.cos(z);
        sin = (float) Math.sin(z);

        result[0] += cos;
        result[1] -= sin;
        result[4] += sin;
        result[5] += cos;
        result[10] += 1.0f;
        result[15] += 1.0f;
    }

    return new Matrix4(result);
}

```

Also I think this rotation Matrix is in row-major (I dont have sure). I send this Matrix to a Vertex Shader and it multiplies by the Vec3 position, so I think if I got any problem, is with this method.

Thanks for reading it!

# Answer
You're adding the three X, Y, Z rotations together. You need to multiply them, instead. Compute three separate matrices using those three formulas, and multiply them together. (Note that you might have to multiply them in reverse order, Z * Y * X - it depends on what convention you want for your Euler angles.)

Also, you have an incorrect negative sign in your Z rotation matrix. Compare against Wikipedia. Also, you're storing your matrices in row-major order, but OpenGL accepts them in column-major order, so you should transpose them.

The matrices shown on Wikipedia are written for using column vectors, i.e. multiplying matrix * vector, not vector * matrix. (Note that this is an entirely separate issue from whether the matrices are stored in row-major or column-major order.) It sounds like matrix * vector is what you're doing, but if not, the matrices should be transposed again.
> 2 votes

# Answer
As Nathan Reed said. Your adding the matrices, when you need to be multiplying them. He also mentions the row/column major issue.

But, for references sake, when multiplyed together you get the matrix:

```
 cos(y)cos(z)  -cos(x)sin(z) + sin(x)sin(y)cos(z)   sin(x)sin(z) + cos(x)sin(y)cos(z)
 cos(y)sin(z)   cos(x)cos(z) + sin(x)sin(y)sin(z)  -sin(x)cos(z) + cos(x)sin(y)sin(z)
-sin(y)         sin(x)cos(y)                        cos(x)cos(y)

```

Which should produce what you want in that function. But I would suggjest you instead make 3 functions. `rotX(float)`, `rotY(float)`, and `rotZ(float)`. Since that would give you more control over transformations at little to no cost of performance.

Even better, you could make the rotations form about an arbitrary axis! to do that you use the matrix:

```
x*x * (cos(t) - 1) + cos(t)    x*y * (cos(t) - 1) + (z*sin(t))  x*z * (cos(t) - 1) - (y*sin(t))
x*y * (cos(t) - 1) - z*sin(t)  y*y * (cos(t) - 1) + cos(t)      y*z * (cos(t) - 1) + (x*sin(t))
x*z * (cos(t) - 1) + y*sin(t)  y*z * (cos(t) - 1) - (x*sin(t))  z*z * (cos(t) - 1) + cos(t)

```

where `t = rotation amount`, `xyz = 3D rotation axis (3D vector)`. in a functions that called something like `Rotate(float t, float x, float y, float z)`
> 1 votes

---
Tags: opengl, java, mathematics, matrix, rotation
---


# Question
Title: Efficient collision detection using quadtrees
I recently started to learn Java and OpenGL with the LWJGL and I'm making some simple games to get started.

At first, when I was going to implement collision detection I immediately thought there had to be an smarter thing than just cycle through each pair of objects (which is an ugly O(n²) operation), so I did some ressearch. It seems that in 2d, what works for most people is a data structure called quadtree.

As I've been working a lot with binary trees (and implementing them) in college, I don't find much of a difficulty in implementing a simple quadtree, but what's really blocking me right now is movement:

Many of the implementations I've seen out there treat this in a way which I consider rather inefficient, but I can't think of anything better. What they do is, each frame of the game execution, they clear the whole quadtree, and add again all the objects which need to be checked for collision that frame, so that way the position updates will be also updated in the quadtree. Is there a more efficient way to do this? I think the objects should be replaced inside the quadtree, and nodes should be added/deleted taking into account those replacements.

I don't know if I'm over-thinking it. Even with the clearing and re-adding method it turns an n² operation into an almost n·log(n) operation. But this is just theoretically, and I have to add another linear operation (clearing and re-adding the quadtree), so I'm worried it wouldn't do any improvements in the actual speed...

Also, another related doubt. I see many people with different approaches regarding quadtrees. Some state that objects that can't fit completely in a quadrant, for a given level, should be stored at least one level upwards, while some others argue that it is better to store objects only in the quadtree's leafs, and an object overlapping at several quadrants should be stored in all of them. Of course we're talking about references here (I'm using java so I can't work with anything else anyway...), I just mean that this would'nt be a serious memory issue, and thus I'm not taking that into account. Anyway, I was just wondering: Which of those might be better? and why?

Any help and other related comments will be much appreciated

Thanks in advance

# Answer
I'd go with some sort of notification/event system to keep the quadtree updated when an object moves. This would require telling the quadtree the previous location of the object (since that's where it was indexed) and the updated location, so the quadtree can check if the object should be reindexed.
> 2 votes

---
Tags: java, quadtree
---