# Question
Title: Better way to load level content in XNA?
Currently I loaded all my assets in XNA in the main Game class. What I want to achieve later is that I only load specific assets for specific levels (the game will consist of many levels). Here is how I load my main assets into the main class:

```
protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            plane = new Player(Content.Load<Texture2D>(@"Player/playerSprite"), 6, 8);
            plane.animation = "down";
            plane.pos = new Vector2(400, 500);
            plane.fps = 15;

            Global.currentPos = plane.pos;

            lvl1 = new Level1(Content.Load<Texture2D>(@"Levels/bgLvl1"), Content.Load<Texture2D>(@"Levels/bgLvl1-other"),
                new Vector2(0, 0), new Vector2(0, -600));

            CommonBullet.LoadContent(Content);
            CommonEnemyBullet.LoadContent(Content);
        }

        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            plane.Update(gameTime);
            lvl1.Update(gameTime);

            foreach (CommonEnemy ce in cel)
            {
                if (ce.CollidesWith(plane))
                {
                    ce.hasSpawn = false;
                }

                foreach (CommonBullet b in plane.commonBulletList)
                {
                    if (b.CollidesWith(ce))
                    {
                        ce.hasSpawn = false;
                    }
                }

                ce.Update(gameTime);
            }

            LoadCommonEnemy();

            base.Update(gameTime);
        }

        private void LoadCommonEnemy()
        {
            int randY = rand.Next(-600, -10);
            int randX = rand.Next(0, 750);

            if (cel.Count < 3)
            {
                cel.Add(new CommonEnemy(Content.Load<Texture2D>(@"Enemy/Common/commonEnemySprite"), 7, 2, "left", randX, randY));
            }

            for (int i = 0; i < cel.Count; i++)
            {
                if (!cel[i].hasSpawn)
                {
                    cel.RemoveAt(i);
                    i--;
                }
            }
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin();

            lvl1.Draw(spriteBatch);
            plane.Draw(spriteBatch);

            foreach (CommonEnemy ce in cel)
            {
                ce.Draw(spriteBatch);
            }

            spriteBatch.End();

            base.Draw(gameTime);
        }

```

I wish to load my players, enemies, all in `Level1` class. However, when I move my player & enemy code into the `Level1` class, the gameTime returns null. Here is my Level1 class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input;
using SpaceShooter_Beta.Animation.PlayerCollection;
using SpaceShooter_Beta.Animation.EnemyCollection.Common;

namespace SpaceShooter_Beta.Levels
{
    public class Level1
    {
        public Texture2D bgTexture1, bgTexture2;
        public Vector2 bgPos1, bgPos2;
        public float speed = 5f;
        Player plane;

        public Level1(Texture2D texture1, Texture2D texture2, Vector2 pos1, Vector2 pos2)
        {
            this.bgTexture1 = texture1;
            this.bgTexture2 = texture2;
            this.bgPos1 = pos1;
            this.bgPos2 = pos2;
        }

        public void LoadContent(ContentManager cm)
        {
            plane = new Player(cm.Load<Texture2D>(@"Player/playerSprite"), 6, 8);
            plane.animation = "down";
            plane.pos = new Vector2(400, 500);
            plane.fps = 15;

            Global.currentPos = plane.pos;
        }

        public void Draw(SpriteBatch sb)
        {
            sb.Draw(bgTexture1, bgPos1, Color.White);
            sb.Draw(bgTexture2, bgPos2, Color.White);

            plane.Draw(sb);
        }

        public void Update(GameTime gt)
        {
            bgPos1.Y += speed; bgPos2.Y += speed;

            if (bgPos1.Y >= 600)
            {
                bgPos1.Y = -600;
            }

            if (bgPos2.Y >= 600)
            {
                bgPos2.Y = -600;
            }

            plane.Update(gt);
        }
    }
}

```

Of course when I did this, I delete all my player's code in the main Game class. All of that works fine (no errors) except that the game cannot start. The debugger says that `plane.Update(gt);` in Level 1 class has null `GameTime`, same thing with the `Draw` method in the Level class.

Please help, I appreciate for the time.

\[EDIT\] I know that using `switch` in the main class can be a solution. But I prefer a cleaner solution than that, since using switch still means I need to load all the assets through the main class, the code will be A LOT later on for each levels

# Answer
Maybe you should look at

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.gamecomponent.aspx

or

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.drawablegamecomponent.aspx

Game components are class similar to the Game class, you add a game component to your game with

```
MyLevel1GameComponent level1 = new MyLevel1GameComponent();
Components.Add(level1);

```

Game component's loadcontent is automatically called when you do

```
Components.Add(level1);

```

and only when you do that. So you can load content only in the moment in the program when you need it. Draw and Update are automatically called each frame after you've executed the previous instruction (only if the property level1.Enabled for Update and level1.Visible for Draw are true).

That means you don't need to put level1.LoadContent(), level1.Update or level1.Draw() anywhere, the Game will take care of this for you.
> 1 votes

---
Tags: xna
---


title: Last Matrix operation ignored?

text:
# Question
Title: Last Matrix operation ignored?
I have 2 methods, one to rotate my Quad and one to flip it (using scaleM), they are as follows: (Note, all values in these methods have been properly defined).

If I call just one, they work as expected, but if I call both, then only the one that is called last if applied - why is this? If I combine them into on 'flip and rotate method' - then my quad is both flipped and rotated. (See third code snippet)

Why is this?

**Method to rotate**

```
    public void rotate(float x, float y, int angle){

    //Rotate the quad

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

}

```

**Method to 'flip' (horizontally)**

```
    public void flipHorizontal(float x, float y){

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.scaleM(mRotationMatrix, 0, -1, 1, 0f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);
}

```

**Combined method**

```
    public void flipHorizontal(float x, float y, int angle){

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, angle, 0, 0, 0.1f);
    Matrix.scaleM(mRotationMatrix, 0, -1, 1, 0f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

}

```

# Answer
> 3 votes
It´s because you set "mRotationMatrix" to Identity in the beginning of each method, which basically resets every previous operation. Try to call "Matrix.setIdentityM" only once outside of these functions.

---
Tags: java, android, matrix, transformation, scale
---


title: Batching and performances

text:
# Question
Title: Batching and performances
I'm trying to understand batching and I'm not sure to understand how to do that, can I have more informations please? Here is what I found for the moment:

## Batching informations

There is many types of batching:

* Sprite batching
* Geometry batching
* ???

## Sprite batching

This method is useful to draw all sprites with only one draw call. To do that, a SpriteBatcher class need to get all the mesh with the same Material and the same Geometry (sprite = square geometry).

1. Get Sprites with same Material
2. Send all Sprite's matrix to a Sprite shader (http://antonholmquist.com/blog/sprite-batching-opengl-es-2-0/)

## Geometry batching (With static geometry)

Merge meshes's geometry, so you we can draw all meshes in one draw call.

1. Get all static meshes
2. Merge meshes's geometry and calculate their position with there matrix (Compute a single VBO and IBO)
3. Hide original mesh to avoid twice draw.

Am I right with that? Thanks!

# Answer
> 1 votes
Batching is a way of grouping geometry together (they should be compatible, e.g. the same material, context states, etc. ) to use as few draw calls as possible. In this way, you could fully exploit GPU throughput, so as to improve performance.

One method to achieve this is to consolidate geometry by **dynamic** vertex/index buffer. The definition of a dynamic buffer is as below

> A resource that is accessible by both the GPU (read only) and the CPU (write only). A dynamic resource is a good choice for a resource that will be updated by the CPU at least once per frame. To update a dynamic resource, use a Map method.

Some steps to improve performance by using this method,

1. Do a benchmark on the GPU, to have a better understanding of the throughput.
2. Create dynamic vertex/index buffer with a reasonable size according to the benchmark result.
3. Feed the geometries with compatible appearance, rendering states, vertex formats and primitive type to the dynamic vertex and index buffer.
4. Continue to feed geometries as talked above until the buffer is full or the coming geometries are not compatible, then call graphics draw method to flush the buffer.
5. Usually, can have a few other than one dynamic vertex/index buffer set, so if geometry can't be feed into the current buffer, then can use another one instead. until all buffers are occupied, then flush.

Hope this can help.

---
Tags: performance, geometry, spritebatch
---


# Question
Title: How to get position of CCSprite added to CCParallaxNode?
I have a CCparallaxNodeExtras that scrolls infinite (following the space game tutorial). I added as a child a CCSprite made of other CCSprite, like this:

```
_backgroundNode = CCParallaxNodeExtras::node();
this->addChild(_backgroundNode,-2);

    float acum = 0.0;
    back1 = CCSprite::create();
    for(int i = 0; i < num_repeats; ++i) {
        CCSprite *back = CCSprite::createWithSpriteFrameName("rock.png");
        back->setPosition(ccp(acum, 0));
        back1->addChild(back);
        acum+= back->getContentSize().width+150.0;
    }

    _backgroundNode->addChild(back1,  1 , ccp(0.1,0.1), ccp(0, winSize.height * 0.64));

```

now in my update I have this:

```
CCPoint backgroundScrollVert = ccp(-1024, 0);
_backgroundNode->setPosition(ccpAdd(_backgroundNode->getPosition(), ccpMult(backgroundScrollVert, dt)));

```

perfect, the background moves and disappears (that is what I want for now) but I need to get the collision between the sprites on that background and a fixed sprite as a child of the main node.

The problem is that whenever I try to get the collision by the simple way (intersecting the bounding boxes) it doesn't work, so I tried to just get the position of the sprites and all I get is the position fixed in the CCSprite (back1) composed by the sprites (back).

Now, is there a possible way to get the position of any individual sprite located in that parallax node? If i try something like:

```
CCSprite *tempsprite = (CCSprite*)_backgroundNode->getChildren()->objectAtIndex(0);
printf("%f\n", tempsprite->getChildren()->objectAtIndex(0)->getPositionX());

```

it prints always the same value, it is like the position is not being affected by the transformation of the parent in the background node... so, how do I get it correctly? how do I get the position relative to screen and not to the parent?

# Answer
The position of the child is the relative position of the child plus the position of the parent.

So the x position of the child would be something like:

```
tempsprite->getChildren()->objectAtIndex(0)->getPositionX() + tempsprite->getPositionX();

```
> 1 votes

---
Tags: c++, cocos2d, cocos2d-x, parallax-scrolling, ccsprite
---


title: Export object or scene with textures

text:
# Question
Title: Export object or scene with textures
Is there a way to export or publish some work to a folder so somebody else can open the .max file and does not have to reassign all the textures again?

My problem is that i used lots of textures straight from my texture folder in a completely different folder tree. So when i sent the file to someone else he needs to rebuild this tree exactly the same as i did or reassign every texture.

If there is no option like that do i have to change my workflow, in case others need to work with my files, and keep everything in the same folder? What is normal procedure to keep everything organized and compatible for each user?

# Answer
Since 3DSMax doesn't actually use the textures themselves (it just imports them into a format it can use), it's not likely going to be able to export them along with the project file. Exporting is typically done when changing formats, not as a method of "putting everything in one place".

This problem is usually handled with source control. Not only does this easily re-create the directory structure of your project, it also ensures you have backups of textures and models should something go wrong. Pick a source control tool you like and check in your project. Then, when you want to share with someone, they just need to check out your project and it'll be in the same structure as it was the last time you checked it in.

To make this a bit more foolproof, you'll want to make sure that 3DsMax is using relative paths for its resources, instead of absolute paths.
> 1 votes

---
Tags: 3d, textures, 3dsmax, asset-workflow
---


# Question
Title: Efficient way to draw multiple separated quads
Let's assume I want to draw several separated (possibly textured) quads in Direct3D 9, each consisting of two triangles:

How should I draw these for maximum performance, i.e. which of the following ways is better in terms of speed?

1. Describe each quad by 4 vertices, use `D3DPT_TRIANGLESTRIP` and call `IDirect3DDevice9::DrawPrimitive` for each individual quad, since they are not connected.
2. Describe each quad by 6 vertices, use `D3DPT_TRIANGLELIST` and call `IDirect3DDevice9::DrawPrimitive` just once.

The first method uses less memory, while the second one requires only one draw call.

However, the second way seems to be feasible only if all the quads have the same texture, since otherwise a switch would be required.

# Answer
Option 2 should be quicker.

Ideally you'd want to combine it with an index buffer and `DrawIndexedPrimitive()`. That way you'll get one draw call, and only need 4 vertices. The index buffer can be created once on start-up since it'll be exactly the same regardless of what the vertex data is, you just need to tell D3D how much of it to use.

Once you add textures, you'll probably end up with one draw call for each different texture you're using. This can be optimized further with a texture atlas if you really need to do so.

However, unless the quads are tiny, the number of vertices won't have a significant impact on performance, because the per pixel cost will be far higher. For example if there's any transparency in the texture then adding extra polygons so you draw fewer completely transparent pixels will generally make it go faster.

Of course the more optimized it is, the more code you need to write, so don't go overboard optimizing unless you're having performance problems, and a profiler tells you what the causes are.
> 1 votes

---
Tags: sprites, directx9
---


title: Rotate 2D Isometric World

text:
# Question
Title: Rotate 2D Isometric World
Games like RollerCoaster Tycoon allow you to rotate the view at 90 degree intervals. I'm wondering how I could apply this to a game I'm making. I'm using MonoGame... but I'm wondering more if anyone could explain the theory behind the transformation rather than something language specific.

This video is exactly what I want to accomplish: http://youtu.be/qitkgiP13gw?t=15s

Basically all my tiles are in a 2D grid, and I just convert each X and Y to isometric for drawing. I'm assuming the transformation might be straight forward since it's a matter displaying the tiles with the right transformation.

Any help is greatly appreciated!

# Answer
Pretty sure the easiest way to do rotation like this is to actually hard-code a simple rotation of the underlying array representing the isometric world.

Say you have a small array representing tiles, something like this (9 tiles total):

```
[0 2 0]
[1 0 4]
[1 0 1]

```

Rotate 90 degrees clockwise could be done by swapping the numbers in the array around:

```
[1 1 0]
[0 0 2]
[1 4 0]

```

You can do this pretty easily by creating a temporary tile-array, copy over the data in a rotated fashion, then swap the new array for the old tile-array, and delete the old array.

Then your tile engine itself can just render your new tile-array however it currently is laid out in memory. There's no graphical rotation involved in the video you've shown, but instead a clever trick like this is used.

Alternatively you can read from your tile-array in a different order, instead of creating an entire new array. Instead of reading in your array linearly throughout memory, you can traverse your tile-array and render it from a different configuration. This is similar to creating an entire new tile-array, but is swapping reading algorithms instead of swapping tile-arrays. This would definitely be more efficient, but harder to code.
> 5 votes

---
Tags: 2d, isometric, monogame, transformation
---


title: How to understand huge code bases?

text:
# Question
Title: How to understand huge code bases?
I read about game loops, read tutorials of simple games like *Asteroids* and programmed them by myself. Nevertheless if I try to start reading code of a game with many many thousand lines of code, I have no clue at all where to start, what files to open first and which next to understand how it all work together.

My question is, are there any projects/tutorials out there, that gives a rookie some guidance (by example) how to start reading code of large open source game projects?

# Answer
> 2 votes
When I approach a new code base I use a technique I call "tunneling". I start at the highest level, then I jump to the lowest level, and repeat until my knowledge meets in the middle, like two tunnels being dug in opposite directions and eventually meeting.

I start by using the software like an end-user would to familiarize myself with the basic concepts. This might seem obvious, but a lot of people jump straight into the code base, sometimes without a clear idea of what the software actually does. While I do this, I think of how I would implement each feature.

Then I open a few source files of a key system to try to get a feel for what the code looks like. What are the most common data structures? How are objects created and destroyed? What design patterns and idioms do they use? At this point it's crucial that you don't overanalyze any one particular system, especially if the software is mature and heavily optimized, because you could spend days figuring out one system without getting a feel of how the major components of the engine interact.

Going back to the high level, I would run the engine again and step over the game loop, making sure not to stop and think too hard about any given chunk of code. The point is to get a feel for what general operations happen in what order, not to become an expert on every single line of code in the engine. You should be able to look at an engine's update loop and say "There's a lot of minor details in here, but the basic flow is that they run the garbage collector, update all objects, update the physics simulation, and draw all objects".

I developed this technique after struggling with Unreal 3's labyrinthine code base early in my career. I made the mistake of tunnel-visioning the rendering code without trying to use the engine first. I think I spent an entire day trying to figure out how their post-processing system worked, when I never actually bothered to pull up the editor and play with the post-process chain first. It's easy to get caught up in the details and spin your wheels without actually learning anything, especially if the engine uses a lot of macros and uncommon idioms like UE3 does.

# Answer
> 1 votes
There's not really a standard procedure for this. It's just something experience gives you. You're not going to immediately understand a large code base. Everyone has their own coding style and strategies for structuring their code.

Likely what's happening is you're trying to understand too much, too fast. Start slow. Pick something you want to learn more about, like what the character class looks like or how the mouse picking works. Find one thing and focus on it. Trace the usage of those classes throughout the code, see where they're used and how.

Build your knowledge of the code base little by little. Soon you'll be understanding how the designer likes to structure things, and finding features and examining the code will get easier.

# Answer
> 1 votes
Reading that source code won't help you too much unless you spend a huge amount of time reading it. Reading anything large for educational value takes some organization.

If you want to understand an open source project in its entirety you need to do your best to take a huge scan of what each large section of code does. It's best to make a visual flow chart describing the engine. This is what I did when I first studied Box2D's code in order to make my own physics engine.

Once you have a rough flow chart of what each section does you can start delving into the implementation of one at a time.

It's just about organizing the information in a way that is consumable by one piece at a time. Make sure you have a lot of time and are capable of putting out a lot of hard work. Additionally, if you have previous project experience understanding what and why things do and are becomes more natural. Again, it takes time to get this experience in the first place!

---
Tags: architecture, source-code
---


# Question
Title: Pause and Re-Enter Game Component Update (XNA)
I'm currently working on a (trading) card game in XNA and I'm having some trouble with returning results from a popup and immediately using them.

I'm able to make a popup screen (see this tutorial) and get a return value from the Yes/No selection while preventing further updates to the "battle" game component, but I'd like to do this while maintaining my location within one update cycle of the game component Update method as I want the popup in question to happen only once: namely when a particular card is played.

The ideal solution would be a way to pause the Update of one game component, continue updating the rest of the game to get my input data from the popup, and then return to the same spot in the paused game component's Update with my new input data.

Any ideas?

EDIT: This method is an effect called from the game component Update method. As a similar effect could be called in the middle of a process (effect before/after an attack), preserving the location within the game component Update is important.

```
public void Cow(Card c)
    {
        bool temp = YesOrNo("Sacrifice Cow for 300 LP?");
        if (temp)
        {
            if (c.ownerP1) { lp1 = lp1 + 300; }
            else { lp2 = lp2 + 300; }

            Discard(c);
        }
    }

```

Also within the game component.

```
public bool YesOrNo(string message)
    {
        game.StartYesNoScreen(message);
        bool val = Convert.ToBoolean(game.yesNoScreen.result);
        return val;
    }

```

This is within the Game1 class itself. The Show method enables the activeScreen component and makes it visible.

```
public void StartYesNoScreen(string text)
    {
        activeScreen.Enabled = false;
        activeScreen = yesNoScreen;
        yesNoScreen.text = text;
        activeScreen.Show();
    }

```

The Game1 Update method.

```
protected override void Update(GameTime gameTime)
    {
        this.gameTime = gameTime;
        keyboardState = Keyboard.GetState();

        if (activeScreen == startScreen) { HandleStartScreen(); }
        else if (activeScreen == actionScreen) { HandleActionScreen(); }
        else if (activeScreen == quitScreen) { HandleQuitScreen(); }
        else if (activeScreen == yesNoScreen) { HandleYesNoScreen(); }

        base.Update(gameTime);
        oldKeyboardState = keyboardState;
    }

```

Another method in the Game1 class.

```
private void HandleYesNoScreen()
    {
        if (KeyPress(Keys.Enter))
        {
            if (quitScreen.SelectedIndex == 0)
            {
                activeScreen.Hide();
                activeScreen = actionScreen;
                activeScreen.Show();
                yesNoScreen.SelectedIndex = 0;
                yesNoScreen.result = 1;
            }
            else
            {
                activeScreen.Hide();
                activeScreen = actionScreen;
                activeScreen.Show();
                yesNoScreen.SelectedIndex = 0;
                yesNoScreen.result = 0;
            }
        }
    }

```

# Answer
> 1 votes
Usually is done with a stack of scenes or gamestates...

when you push a popup on top of the stack it becomes the active component that get updates...

You can get a microsoft sample about game state management here http://xbox.create.msdn.com/en-US/education/catalog/sample/game\_state\_management

Or you can get it done by yourself:

```
 public abstract class GameState {
        protected  bool UpdateIfNotOnTop = false;
        protected  bool DrawIfNotOnTop = false;

        protected abstract void Update();
        protected abstract void Draw();

      public class GameStateManager  {

         public readonly static Instance = new GameStateManager();

         Stack<GameState> States = new Stack<GameState>();

         public void Push(GameState State) { States.Push(State); }
         public void Pop() { States.Pop(); }

         public void Update() {
              foreach (var state in States.ToArray())
              {
                   if (States.Peek() == state || state.UpdateIfNotOnTop)
                  {
                      state.Update();
                  }
              }
         }

         public void Draw() {
              foreach (var state in States.ToArray())
              {
                   if (States.Peek() == state || state.DrawIfNotOnTop)
                  {
                      state.Draw();
                  }
              }
         }
      }
  }

```

# Answer
> 0 votes
Perhaps you can disable said component(s) (set enabled to false) until you have processed the results, and then re-enable it

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


# Question
Title: Particle dynamics simulation and conservation of energy
Suppose you want to simulate the dynamics of a particle subject to Newton's laws of motion. We could just fix a discretization of the time `dt` and solve approximate differential equations like

```
    y+=vy*dt;
    vy+=ay*dt;

```

and so on for the other coordinates. If we are unsatisfied with the accuracy we could make `dt` smaller or use higher order approximation methods, at the cost of slowing the simulation and this would reduce the error, but the error can still sum up and become big in after a long time.

Now my point is: suppose that you want to run the simulation for long time so you don't mind short run accuracy but you want the system to preserve long run properties such as conservation laws.

Concrete example: suppose the particle is subject to gravity with the acceleration `ay` constantly equal to *g*. We have the conservation law *1/2 m v^2 + m g h =constant*.

Now after the approximation step I could compute the energy and discover it is slightly changed, and this lead to a degeneration after long times (for example it can lead to overflow errors or particle slowing down). At each step I could then adjust *v* and *h* in order to make the energy conserved, but I have a lot of choice here... how do I decide for the better in this constrained choice?

In general what is the best way to deal with situation where you can sacrifice short time accuracy to save speed and preserve the long time behavior?

# Answer
> 3 votes
You're mentioning a very good point! The simple answer is: In some cases simple Euler integration is not good enough, and no increase in accuracy will help.

Clearly, you have to distinguish the goal of your particular simulation. If you're simulating a whole bunch particles bouncing, interacting with each other and/or fields and gravity en masse, then the Euler method should be good enough. Your system might diverge from the "real" solution, but for all practical purposes no one will notice.

That being said, there are cut cases where one intuitively knows the solution or some property of it. If you have a plane orbiting a star, it should do so on an elliptical orbit. If you have a weight attached to a spring, the elongation of the spring should be sinusoidal (without dampening). Then simple Euler integration will not just produce some inaccuracy, it will produce a solution that completely diverges from the closed path. The spring will get ridiculously elongated overtime, a planet will be escape the solar system...

When decreasing the timestep of an Euler integration, it will take longer time for the divergence to become noticeable, but if the system is prone to it, it will always occur.

There are other integrations scheme that inherently perform much better in conservative systems. Most notable are the Verlet integration and the Runge-Kutta methods. Verlet is much easier to understand and already quite good, especially in systems with conservation of energy. The Runge-Kutta method is usually the best in accuracy, but it is quite complicated and it has some inherit dampening which most of the time helps it to converge, but you might find a case where it performs worse.

Here is a nice comparison I just found: http://codeflow.org/entries/2010/aug/28/integration-by-example-euler-vs-verlet-vs-runge-kutta/

Sorry, for not providing implementations to compare. You should be able to find plenty when searching for these keywords.

# Answer
> 4 votes
Pretty sure you can just use symplectic euler integration and call it good. Over time numerical accuracies should be insignificant enough it won't matter.

Often times in a physics simulation you'll have a simple way of measuring error, and add energy back into the system. However with just simple particle dynamics conserving energy like this usually isn't necessary. Usually particle dynamics is only done to animate tons and tons of particles in an efficient manner, whereas accuracy isn't really the goal.

# Answer
> 1 votes
This

> where you can sacrifice short time accuracy to save speed and preserve the long time behavior?

from the request is nonsensical as it stands. As you extend the simulation, and **particularly if you do not carefully guard and preserve the accuracy of every result**, you will end up with the rounding error of your calculations accumulating to overwhelm everything else.

The only way to preserve long-term accuracy is to ensure even greater accuracy at every shorter interval.

---
Tags: physics, simulations
---


title: SAT test for Triangle - convex hull

text:
# Question
Title: SAT test for Triangle - convex hull
I'm having real trouble resolving this issue with triangle-convex hull SAT test intersection.

The problem is as follows:

Misses are detected accurately enough:

## Clear miss

I have not found a problem with false negatives (ie collision is there but not detected).

But I do have a problem with false positives (collision detected even though there is not one)

## Appears to detect false +

This only happens occasionally with orientations like the one shown (that is actually a pretty big gap).

What I'm doing conceptually is just a usual SAT test for the triangle against the hull. I'm pretending the single triangle is a "convex hull", indeed it might be if you imagine it is a *very thin, very flat* tetrahedron. I don't know if I am mistaken in this concept of triangle-convex hull intersection, if the slight inaccuracy is to be expected, or if there is perhaps a bug in my code (the same SAT Test routines work for hull-hull, box-hull, and other test quite accurately though)

The relevant code is at line 621 of hull.h, with the SATTest overlap routine in Intersectable.cpp.

# Answer
> 3 votes
It seems you're testing with the faces of the hull and the triangle, which is good, although these are not the only possible axes of separation.

There exists more axes of separation that are the result of the various edges of the polyhedron. You can compute these axes by taking the actual edges of your two polyhedron and crossing them together. Then projections onto these axes can be used to determine possible overlap along that axis.

Of course, since cross products are involved, you must make sure to ignore edges that are near parallel. It can be shown, theoretically, that if two edges of a polyhedron are parallel then skipping their cross product (and consequently their axis projection test) will not result in a false positive.

This edge checks are literal edge cases, and the necessity of edge checks make the traditional SAT in 3D the time complexity on the order of O(N^3), which is why you don't commonly see it in professional code bases. As a side note there exists a new optimization called Gauss Map optimization, originally popularized on the Bullet forums by Erin Catto. This optimization brings the complexity back down to O(N^2), making it a great candidate for convex hulls with a smaller number of faces. There is a single resource for this optimization as a GDC 2013 lecture by Dirk Gregorius, slides of which are available at Box2D.org's downloads section.

I hope this helps!

---
Tags: collision-detection, intersection, separating-axis-theorem, convex-hull
---


title: How to manage frustum culling

text:
# Question
Title: How to manage frustum culling
I have a **spherical clipmap** based planet terrain. The entire planet is made from a **ring geometry of 1 unit** which the vertex shader moves to cover the entire planet of 6 million unit radius. But the planet gets culled whenever the starting point for this geometry isn't in the camera's view (which is 99.9999% of the planet).

What's the best solution for making sure the planet is viewable even when the original mesh isn't?

This is based on **WebGL and Three.js**.

# Answer
> 2 votes
The solution is to set the boundingSphere attribute on the original geometry to the radius of the planet. Now even though only the vertex shader moved triangles are in view, I can still see the planet.

---
Tags: terrain-rendering, webgl, frustum, three.js
---


# Question
Title: Is there any way to make animations using physical dolls?
I've had trouble animating characters using 3D applications. It is too slow and difficult. I've programmed my own 3D animator that uses only the keyboard to change key angles. The results are much better, yet it draws some considerable time.

http://dl.dropboxusercontent.com/u/62862049/Screenshots/tq.png

I'm reaching the conclusion animating is hard because nor the keyboard nor the mouse are ideal input sources for that kind of thing. I guess the best would be a physical doll one could manipulate. Is anyone aware of such a product?

# Answer
There is actually a doll for exactly this purpose:

It appears to be under development by SoftEther Corporation.

However, I imagine such a solution might be overkill.

An alternative would be to use a GI Joe for your modeling. Record video of your GI Joe manipulations from the front, side and top. Using these synced videos, you can go frame by frame switching between a front, side and top view of your 3D model (or you may be able to do it with two cameras). For each frame align your model to match the GI Joe in the recorded video for that frame. This is similar to rotoscoping for 2D, but you're doing it on each axis to expand it to 3D.

Another alternative would be to use a 3D camera like the Kinect. Remember that you can always elaborate on the animations when you're creating them. You don't need to do a backflip in front of your Kinect to have your character do one. The accuracy may not be great, but it'll give you a good baseline to work off. (However, if you do attempt the backflip, you'll have some sweet 3D video of it.)
> 3 votes

---
Tags: animation, tools, skeletal-animation, productivity
---


# Question
Title: Why is my client laggy despite 60 update packets a second?
I am developing a small multiplayer game with XNA. It's a usual client-server architecture -- I have a server and many clients communicating with it through UDP (via .NET's `Socket` class). These clients send data to the server (for example, the player's position) and the server handles it and decides what to do (send it to every other client or drop it).

What's the most efficient "correct" way to send position of moving object from a client to a server? Currently, I send the client's ID and player position 60 times a second (XNA's default update rate) while a player is moving. When I see my own player on the screen, it moves very smoothly, but other don't, despite every client having the same update rate. What am I doing wrong?

# Answer
> 3 votes
Those packets are still late. Even if you send 1M packets every second, there is still lag. Certain packet is packed at time t1 and it arrives at t1+ping/2.

You send positions of other player to everyone. I assume you then do something like this:

```
player[4].Position = new Vector2(readNextPlayerX(),ReadNextPlayerY());

```

You set that coordinate you sent, directly to player with matching id?

When you get new coordinate, you just apply it and if it has changed a lot, you get jerky movement. Difference between last known position and just updated position is so big, that it just leaps to it. To fix this, you have to use "lerp" to smoothly move towards new coordinates. This is called Interpolation. Instead of immediately move to new position, you have to keep record of you new positions, sent from server. Then in every update loop, push player towards next position. Lerp is a way to move towards other point, certain amount. This "amount" is called "smoothingFactor". It can be number between 0f and 1f. 1f means that vector1 changes to vector2 in:

```
MathHelper.Lerp(vector1,vector2,smoothingFactor);

```

if it's 0.5f, vector1 moves towards vector2 to halfway. So if distance was 10, its now 5. Depending on your smoothingFactor, you can change your movement from jerky, to smooth.

You are sending 60 times per second. That's way too much. If you have 10 players and you send 60\*2 floats and int to server, that means server sends 9\*60\*2 floats and 9\*int to everyone, every second. 20 or 30 times is better. You collect data on server, for player inputs. Generate movement packets from that data. Every 30ms you send collected data to players.

Are you using your own networking code, or some library? Packet dropping can cause this also.

# Answer
> 1 votes
I'm no expert on this , but from what I can remember the best way to do this is to just send packets when actions are taken and not the whole time.

Example:

Player presses a button to move \> send to server \> send to other players \> display stuff on clients Player releases button \> server \> other clients ...

That way you don't have to send so much data. Granted it might be the reason for some problems, like, misleading actions when a packet isn't received/sent , but from what I have heard his is the best way to do mp gaming. (just not sure if UDP is the best protocol for this as mentioned by others)

# Answer
> 0 votes
It looks like you have a pretty good idea of what to do, but there are a few things you really need to look at. I'll briefly talk about them but you really should look over some of the concepts applied to the source engine here. Additionally, there is a good post here which talks about syncing physics over networks and some more details.

I have no real idea 'how' you implemented it, but the concepts below and in the articles are likely going to apply:

Real-time game with low entity count is usually handled with UDP and sending frequent packets (10-30 times a second, depending on how much data you have and how good of a connection you are running). If you are targeting mobile phones keep your data packets small and only send them 10-20 times a second. So using UDP is a perfectly fine, just realize you MUST interpolate because you will have dropped packets (unless you are on a LAN with minimal networking activity).

In all cases for a client-server, your clients shouldn't be determining the positioning information because this means your server cannot easily determine people cheating or not. Usually, the server does the physics then your clients are updated. (P2P follows a very different style so I won't talk about it here). You don't need to update more than a few times a second because you will be interpolating between network updates to keep your client running smoothly at whatever framerate they are.

You likely are going to want to do lag compensation of some sort. (I.e. the famous "user is slowing down the game" you see in Starcraft 2). Your client can run physics to allow you to do client-side prediction, but that has a debatable cost/benefit and is usually worse the more physics objects you have colliding in your game.

---
Tags: xna, multiplayer, udp, socket
---


# Question
Title: Cloud Computing Middleware to Control for Add/Kill VMs + Sessions
I'm working with some people who have a prototype game in Unity and may need to scale it up to address a larger user base. The potential application has the following characteristics:

1. Sessions are multiplayer (e.g., multiple users in a game world)
2. Sessions are independent (e.g., each session knows everything it needs to know)
3. Sessions will log some stats to a centralized server (sessions write here, but do not read from there)
4. Session use is likely to be highly uneven (high peak loads of #users and users/session, with long periods of low usage)
5. Users will interact with the system using a browser

Based on these characteristics, a cloud-based service like EC2 seems like an obvious choice. You only pay for what you use, so you can store an instance of a game server and spin up copies of it when needed, then cut them off when usage bottoms out. However, doing this requires a server dedicated to managing the # of instances online and helping users get properly allocated to a running server. From the end-user, I would imagine a system where a user logs into a web portal and requests a list of sessions that they can join. In the background, the manager would spin up a new session if the number of users waiting in the lobby exceeds the slots available.

In principle, this is a simple concept: you have a lobby, you have a count of users waiting, and you have a count of your servers (and #sessions/server and #users/session). If your ratio of #waiting/#slots available gets too high, you spin up another VM. If the ratio gets low, you start shutting some VM's down. However, in practice this is not likely to be as trivial (lag times to spin up servers are non-trivial, connecting users in browser-based apps to a dynamically-allocated server could have failures, etc). However, this seems like a fairly general use-case. Has anyone already made such a lobby controller? Or even a general load-balancing controller that has similar characteristics? (Preferably one that would work with EC2)

Or, short question: Does anyone know of a library or server application that would be suitable to balance creating servers and sessions on servers, to dynamically spin up servers for Unity games (on EC2)? Alternatively, for those who have attempted to home-brew such a system, what were the primary hurdles? (Beyond the obvious fact that it is almost impossible to simulate load meaningfully)

# Answer
The general problem you are describing (Cloud deployment, auto scale-in/scale-out based on certain metrics) is usually handled by a PaaS - Platform as a Service.

In general, a PaaS allows you to upload your 'application', which could be a VM image or executable files, depending on the PaaS. It is the responsibility of the PaaS to deploy the application to a cloud instance, monitor the application and scale in/out as required.

I don't know of any PaaS that has explicit support for Unity, but the principles hold regardless of what your code does. There is a comparison of PaaS options here: PaaS Providers

Disclaimer: I work for GigaSpaces, developer of the Cloudify open source PaaS stack.
> 1 votes

---
Tags: unity, scalability, virtual-machines, cloud-computing
---


# Question
Title: How do I draw a zoomable image in OpenGL?
Up to now I have used `glDrawPixels` but since my image is a large geotiff one, I'm getting some horrible results for example:
this is the code used for `zoom extent`:

```
void COpenGLControl::ZoomFullExtent()
{
    GLint iViewport[4];
    glGetIntegerv(GL_VIEWPORT, iViewport);
    glPixelZoom((GLfloat) iViewport[2] / (GLfloat)width,
                (GLfloat) iViewport[3] / (GLfloat)height);
}

```

Since the image is a square one, it's not a good result.

This is the code used for zoom in:

```
void COpenGLControl::FixedZoomIn()
{
    glPixelZoom(2.0f, 2.0f);
}

```

but it does zoom in operation just one time and when I again click on the button the zoom in is not done I think it is because that when I call `COpenGLControl::FixedZoomIn` for an instance of the class COpenGLControl infact the openGL window is zoommed not the contents in it.

I have heard about texture mapping and how to zoom by changing z of the camera point.

How would I customize the class COpenGLControl for my purpose?

# Answer
The reason glPixelZoom doesn't work as you expect is that calls to it aren't cumulative; the second call overwrites the first. See the manual at https://www.opengl.org/sdk/docs/man2/xhtml/glPixelZoom.xml

Instead of using glDrawPixels, you should draw the image as a texture mapped square.

Set up the texture object once:

```
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
    image_w, image_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);

```

Draw it on the screen each frame, by first setting up an orthogonal projection to map (0, 0) to the top left corner of the screen, and (screen\_w, screen\_h) to the bottom right corner.

```
glViewport(0, 0, screen_w, screen_h);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screen_w, screen_h, 0, -1, 1);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

```

And then draw a textured square (using a triangle strip in this example):

```
glEnable(GL_TEXTURE_2D);

glBindTexture(GL_TEXTURE_2D, tex);

x0 = 0; // top left corner of image
y0 = 0;
x1 = x0 + image_w * zoom; // bottom right corner of image
y1 = y0 + image_h * zoom;

glBegin(GL_TRIANGLE_STRIP);
{
    glTexCoord2f(0, 1); glVertex2f(x0, y1);
    glTexCoord2f(0, 0); glVertex2f(x0, y0);
    glTexCoord2f(1, 1); glVertex2f(x1, y1);
    glTexCoord2f(1, 0); glVertex2f(x1, y0);
}
glEnd();

```
> 2 votes

---
Tags: c++, opengl, image
---


# Question
Title: How do I manipulate the Url of my Silverlight testpage.aspx?
I am making an XNA game using Silverlight over the web. My testpage.aspx is linked to from a previous page where the client selects certain elements. The testpage.aspx URL changes depending on what I have sent to it. Now in my mainpage.cs file I would like to call certain functions depending on what was passed, but I am unsure how to manipulate or even access the URL. Is there a specific class in the Silverlight library I can use?

Thank you for your time.

# Answer
Try reading the URL parameters like http://markuserlandsson.wordpress.com/2012/02/28/reading-url-parameters-in-silverlight/

Also, it would be a good idea to make sure that the URL isn't visible to the players unless you're fine with players cheating by changing the URL themselves.. (assuming that there is any chance to do it) in which case hiding the parameters in a session might help.

Hope this helps. :)
> 0 votes

---
Tags: xna, silverlight
---


title: Rotations and Origins

text:
# Question
Title: Rotations and Origins
I was hoping someone could explain to me, or help me understand, the math behind rotations and origins. I'm working on a little top down space sim and I can rotate my ship just how I want it.

Now, when I get my blasters going it'd be nice if they shared the same rotation.

Here's a picture.

and here's some code!

```
blast.X = ship.X+5;
blast.Y = ship.Y;
blast.RotationAngle = ship.RotationAngle;
blast.Origin = new Vector2(ship.Origin.X,ship.Origin.Y);

```

I add five so the sprite adds up when facing right. I tried adding five to the blast origin but no go.

Any help is much appreciated

# Answer
if you see the draw, I think is easier to understand.

You should have a ship position that is the same for the blast, and you have two sprites with different sizes. You should realize the rotation is related to the origin, so you have to pair the rotation origins.

The yellow circles are the origins for each sprite:

a) Ship: You have to sure that the origin point to the center of the ship. It seems to be the center of the texture.

```
   o1 = new Vector2(ship.Width, ship.Height) * 0.5f;

```

b) Blast: The blast orign is not the texture center. It seems something like:

```
   o2 = new Vector2(-10, ship.Height*0.5f);

```

That way draw them is pretty easy:

```
batch.Draw(ship, ship_pos, null, color, o1, angle,....)
batch.Draw(blast, ship_pos, null, color, o2, angle,...)

```
> 2 votes

# Answer
You have to rotate first, then move to rotated direction. Also, you have to use position vectors.

Set positions:

```
Vector2 shipPosition = new Vector2(100,100);
Vector2 blastPosition = shipPosition;

```

Set origins to middle of image

```
ship.origin = new Vector2(ship.Heigth / 2, ship.Width / 2);
blast.origin = new Vector2(blast.Heigth / 2, blast.Width / 2);

```

Change rotation:

```
blast.RotationAngle = ship.RotationAngle;

```

Move blast x,y forward from ship position, towards direction its rotated

```
float x = shipPosition.X+(float)(Math.Cos(blast.RotationAngle - MathHelper.PiOver2) * 5f);
float y = shipPosition.Y+(float)(Math.Sin(blast.RotationAngle - MathHelper.PiOver2) * 5f);

```

Apply new position

```
blastPosition  = new Vector2(x,y);

```

Draw ship

```
    spriteBatch.Draw(ship                   //the texture
                , shipPosition              //it's location as a Vector2
                , null                      //no source rectangle - use entire Texture2D
                , Color.White               //with the image's own colors
                , ship.RotationAngle        //at the current XNA radians
                , ship.origin               //rotation point of the image, origin
                , 1                         //use the original scale
                , SpriteEffects.None        //don't flip or otherwise manipulate image
                , 0                         //no changes to layer depth
                );

```

Draw blast

```
    spriteBatch.Draw(blast                  //the texture
                , blastPosition             //it's location as a Vector2
                , null                      //no source rectangle - use entire Texture2D
                , Color.White               //with the image's own colors
                , blast.RotationAngle       //at the current XNA radians
                , blast.origin              //rotation point of the image, origin
                , 1                         //use the original scale
                , SpriteEffects.None        //don't flip or otherwise manipulate image
                , 0                         //no changes to layer depth
                );

```

Hope this works, i can't test this, but it should work.

Difference in this is, that if you rotate first ( you are still in the spot, inside ship, but rotated correctly ), then you move blast forward ( along the rotation its facing ) 5 steps. It should now be perfectly aligned with the ship.

---

**NOTE:**

Position is x,y where texture is located on screen.

Origin is x,y in Texture, that is used as central point when rotating it.

If you move origin from center of picture, rotation gets weird ( atleast in symmetric textures).

EDIT: Added the draw commands also, to make sure its used correctly.
> 0 votes

---
Tags: xna, rotation
---


title: Should I worry about the refresh rate?

text:
# Question
Title: Should I worry about the refresh rate?
I'm working on an RTS and there is a lot of camera movement involved. The camera moves at a constant speed but it stutters (seems to jump/jerky movement) if I don't enable vsync. I understand why this is happening, if the game is running at 74 frames per second then 14 (my refresh rate is 60 Hz) frames will be ignored/skipped. If the camera moves 10 units between two consecutive frames then a skipped frame means a movement of 20 units instead which makes the movement jumpy.

My question is how do other games manage to keep their movements smooth even at odd frame rates and fluctuations?

I've not included the code because I've ran numerous tests and I believe the code itself is fine. I've also read this article and am using the suggested game loop. Cheers!

Edit: Thank you for the suggestion Lachlac and Mr. Beast. I changed my code to use delta time instead but the movement is still jerky at 70 frames per second.

```
while(main_event->type != SDL_QUIT)
{
    last_time = current_time;
    current_time = get_tick_count();
    delta = current_time - last_time;

    SDL_PollEvent(main_event);

    if(rect_data.x < 101) vel_x = 600;
    if(rect_data.x > 1300) vel_x = -600;

    rect_data.x += vel_x * (delta / static_cast<double>(frequency));

    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, rect_texture, NULL, &rect_data);
    SDL_RenderPresent(renderer);
}

```

I've tried both fixed and variable time steps and they produce the same jerky motion. I'm guessing it's because of frames being skipped but I've included my code in case I'm doing something silly.

Edit 2: For eBusiness:

I have my physics set to 120 Hz and I'm also interpolation between the last and current game state. Each time the renderer rendered, I made it output the displacement in the render position from last frame to the current frame and also the time difference between last and current frame. Here is some of the data:

```
10              -0.0159823
10              -0.0160441
9               -0.0158394
9               -0.0150374
9               -0.0150993
10              -0.0160116
9               -0.0159414
10              -0.016037
10              -0.0159659
9               -0.0160212

```

The data was very consistent, it's just that if a frame is skipped because of the refresh rate then instead of moving 9 or 10 pixels, it'll move about 20 pixels which results in the jumpy motion. I also tried to ignore the interpolation value and just use the latest game state and that didn't help either.

Using variable time steps also have the same problem, the displacement and time difference is consistent and frame skips again ruin the smoothness.

# Answer
> 2 votes
I think you may actually have an **input latency** problem, especially if your game involves a mouse (which is often the case in an RTS).

What probably happens when you run with vsync is that you capture the mouse movement at the beginning of the frame, deal with the information to create the new frame (move objects, camera, etc.), then have it displayed. The elapsed time between mouse capture and rendering is about 16.66 milliseconds. And the elapsed time between *user action* and rendering will vary between 16.66 and 33.33 milliseconds, meaning an average of 25 milliseconds latency. Depending on your display device there is additional delay for the image to reach your eyes, but you can’t easily control that.

So here is my first, general tip: **always read the user input as late as possible in the game loop**.

Now if your game can run at 74 fps, rendering still happens at 60 fps but it only takes 13.51 milliseconds to perform all your operations. Since the engine and the renderer are not synchronised, delay will be erratic and you will sometimes get reduced input latency, and sometimes increased latency. In average the latency will be smaller but you will get stuttering.

My suggestion to get the best of both worlds: **if you can render faster than 60 fps, use vsync anyway** to reduce input latency, **even if this implies doing nothing**: if your calculations need 13.51 milliseconds but your rendering needs 16.67, you can reduce input lag by about 3 milliseconds simply by sleeping at the *beginning* of the frame.

This can be tricky. If you miss the vertical refresh, your frame will be delayed 16.66 additional milliseconds. A self-calibrating heuristic to activate or deactivate this mechanism seems like a good option to me.

# Answer
> 1 votes
You shouldn't move anything in game by a fixed amount each frame. You should multiply all movement by delta time which is usually found (or estimated) by measuring the amount of time since the previous frame. Edit : I just went through the article and now I'm confused as to what you're problem actually is.

# Answer
> 1 votes
The Fix your timestep article is about physics, not graphics, for the most predictable result you'll need a fixed timestep, but for the smoothest animation you'll need to use delta time directly.

Realistically, just enable VSync, there isn't really much of a downside. You don't spend your time calculating something you don't need in the end and you get a constant frame-rate.

# Answer
> 0 votes
A few options:

### 120 Hz logic rate:

Fits the common 60 Hz displays nicely, and is fast enough that any possible issues will be minor.

### Ludicrous logic rate:

If only your logic rate is high enough you won't have any visible issue. The downside is of course that it cost a lot of processing power.

### Rendering interpolation or extrapolation:

Gameplay wise a logic rate of 20 or 30 Hz will suit most RTS games just fine. (Though you can go higher if you find that to be an advantage.) When rendering you just have to take into consideration how old the logic frame is and apply a proportional fraction of the objects velocity to the position for rendering.

In pseudocode:

```
[rendering position] = [logic position] + [velocity] * [logic frame age]

```

---
Tags: frame-rate, vsync
---


# Question
Title: How do I rotate a single object in HLSL?
I have a World with a 3D model of a head in it and that World rotates, like such:

```
protected override void Update(GameTime gameTime)
{
    //other stuff

    angle += 0.00005f;

    //more other stuff
}

protected override void Draw(GameTime gameTime)
{
    //other stuff
    Matrix rotation = Matrix.CreateRotationY(3 * angle);
    effect.Parameters["World"].SetValue(rotation * Matrix.CreateScale(10.0f));

    // other stuff
}

```

And then in my Effects file I create a spotlight:

```
float4 SimplePixelShader(VertexShaderOutput input) : COLOR0
{
    float4 lightDirection = { 1, 1, 1, 0 };
    float theta = 10.0f;
    float phi = 30.0f;
    float4 color;
    float4 lambert = DiffuseColor * 0.2 * max(0, dot(input.Normals, input.lambertLightDir));

    float angle = acos(dot(input.lightDir, normalize(lightDirection)));
    if(angle > radians(phi))
        color = AmbientColor * AmbientIntensity;
    else if(angle < radians(theta))
        color = lambert;
    else
        color = max(AmbientColor * AmbientIntensity, smoothstep(radians(phi), radians(theta), angle) * lambert);

    return color;
}

```

And naturally this spotlight also rotates with the world. However, I dont want it to rotate. I tried everything, multiplying, adding, subtracting the rotation matrix and/or the angle from the different lightdirections and angles and nothing works.

Now I could rotate just the model and not the world, that would even be a sensible thing to do, but I have no clue how :P So I'm either looking for a good way to rotate the model or a way to 'counter rotate' the spotlight so it seems to stand still.

Edit: my vertexshader:

```
VertexShaderOutput SimpleVertexShader(VertexShaderInput input)
{
//some other vertexshaderstuff

    float4 lightPoint = {-3, -2, -2, 0};

    output.lightDir = normalize(input.Position3D) - lightPoint;

    output.lambertLightDir = float4(30, 30, 20, 0);

    return output;
}

```

# Answer
> 1 votes
If your "Input.position3D" and your "lightPoint" are not affected by the World Matrix in any way the resulting "lightDir" will allways be the same no matter which Rotation you use there, since you rotate your model for output it will rotate but still keep its constant lighting which will look like the light would rotate with the model.

```
output.lightDir = normalize(input.Position3D) - lightPoint;

```

this should be something like

```
output.lightDir = normalize(worldPos - lightPoint);

```

where worldPos is the Input.pos3D transformed with your world Matrix, the one you use for position output of the vertexshader.

# Answer
> 1 votes
By looking at your code it seems that you are already rotating your object. The *world* matrix is a term used to describe the total transformation that you are applying to whatever you draw after that assignment. In order to "rotate the world", you'd have to change the position of your camera to follow a circular path for example. But by setting a rotation matrix as the World matrix of an effect, you are applying it to whatever is rendered with that effect activated.

**Edit** You should not normalise your object's position (*input.Position3D*) as it is a point, not a vector. You should normalise the result, i.e.: `normalize(input.Position3D - lightPoint);`

---
Tags: xna, c#, shaders, hlsl
---


# Question
Title: Using a Higher Precision (than 8-bit unsigned integer) Buffered Image for Heightmaps in Java
I am generating a heightmap for every quad in my quadtree in openCL. The way I was creating the image is as follows:

```
DataBufferInt dataBuffer =
            (DataBufferInt)img.getRaster().getDataBuffer();
      int data[] = dataBuffer.getData();
      //img is a bufferedimage
        inputImageMem = CL.clCreateImage2D(
        context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR,
        new cl_image_format[]{imageFormat}, size, size,
        size * Sizeof.cl_uint, Pointer.to(data), null);

```

This works ok but the major issue is that as the quads get smaller and smaller the 8-bit format of the buffered image starts to cause intolerable "stepping" issues as seen below:

I was wondering if there was an alternate way I could go about doing this?

Thanks for the time.

# Answer
> 1 votes
Are you using texture filtering when reading the height map? I'd expect that a bilinear filter would smooth things out a bit.

If you still need better precision then change the image format to something like CL\_UNORM\_INT16 or CL\_FLOAT - see http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/cl\_image\_format.html

I'm not quite sure how you do that from Java though.

---
Tags: java, heightmap
---


# Question
Title: How do I determine if a triangle is visible in my view frustum?
I need a fast way to determine if a triangle is visible from a perspective projection view frustum. I am not looking to use an approximation with AABBs or bounding spheres, but need to accurately check an actual triangle against the frustum.

What do I need to do to test whether or not a triangle is completely outside the view frustum volume?

---

*Edit: The nature of my question changed after discussing the actual problem I was trying to solve. I'm not too sure what to do here; do I accept answers based on the original question, or ones that address the actual problem? I'm also writing the original problem here for reference:*

I'm trying to put together a 3d scene where I can get the visible longitude and latitude extents given an Earth sphere (centered at 0,0,0 in ECEF coordinates) and a normal perspective projection camera frustum. I then plan to load assets based on the lon/lat extents returned.

I couldn't figure out how to get extents given a view frustum analytically, so I tried to create a mesh based representation of the Earth at various LODs. I wanted to cull the triangles from this mesh against the view frustum which would leave a bunch of quads I could derive lon/lat extents from. Culling using vertices or bounding boxes wasn't appropriate at lower LODs where the mesh faces were much larger, which is why I needed to test the triangles themselves.

Seth's answer below seems like a better solution than generating meshes and culling them.

# Answer
Get the projection of the triangle and the view frustrum. You then have a 2D box and a triangle.

If the X ordinate of all of the points are less than the minimum X value of the box or is greater than the maximum X value then it's totally outside the box.

If the X value is inbetween these values then repeat the test but with the Y values.

As Nathan points out this isn't the whole solution but will enable you to throw away a large number of triangles in one go. You can couple this with other tests to determine whether the triangles are behind the camera to throw away even more.
> 3 votes

# Answer
Continuing from comments: if you are trying to estimate the visible area of a sphere, you don't need to detect individual triangles at all. You should be able to reduce that to a fixed mathematical process. Doing this should reduce the O complexity of your operation to constant time. The math itself will involve several steps, possibly with branching logic. But unless you have a very small number of vertices, it will be faster than counting triangles.

The goal is to determine the red angle. In any position, this can be calculated from the sphere's position and the frustum's orientation. Once you've done that, you can divide by the angle size of the quad. (Or skip that step, since you said the goal is to determine the angle.) Obviously this is a 2D diagram, so you may need to repeat the process for the frustum's up-down and left-right directions.

I haven't posted anything specific because the process will vary depending on your situation. Is the sphere filling the whole frustum, or is it partially filling it like I show in my sketch? Is the sphere so large that you are seeing only a small portion of it, or is it just barely filling the viewable area? Referencing that sketch, the green triangle's viewable edge is calculated differently than the purple triangle's edge. Regardless, placing the sphere into one of a few different "zones" will still yield the visible area faster than bounds-testing individual vertices.
> 2 votes

# Answer
If you really need an *exact* test, you can use SAT (separating axis test). Google it; there's tons of resources on the web. But it's not all that fast.

If you just need to quickly reject *most* out-of-frame triangles (a conservative intersection test), and the triangles are reasonably small compared to the frustum, then just loop through the frustum's planes and check if all three triangle vertices are on the outside of the plane. This will get rid of most of the triangles, though it will fail to reject some triangles that are outside the frustum near its edges/corners. Most importantly, it won't reject any triangles that are actually visible.
> 0 votes

---
Tags: frustum
---


title: Smooth Ramp to zonal harmonics

text:
# Question
Title: Smooth Ramp to zonal harmonics
I have written in blitz3D some code to generate arbitrary 2D lighting lookup textures and I'm looking for a way to compress them. The idea is that they look rather smooth and low frequency, there must be way to lower the memory cost using spherical harmonics since they represent lighting over a sphere ...

Let say I have a 2D texture (let say 512²) that is a stack of lighting ramp (look up with a half lambert). X is the NdotL ramp and Y an arbitrary index parameter given by some function.

Nodtl lighting can be represented as a symmetrical spherical harmonics known as zonal harmonics. By transferring the ramp to zonal harmonics I can compress the texture from 512x512 to 512x9(+7 free to have power of 2) ie a stack of spherical harmonics coefficients.

Now the math is way above my head, I read the stupid spherical harmonics tricks and nitty gritty details paper, but while I understand the principle, the math and the translation to code is way above my level.

The idea is that instead of going through all the slices by hand (512 per textures at least) to create custom curves fitting, having a generic "ndotl ramp to zonal harmonics" function might improve production.

What I want is how the code would look like to turn a slice (ramp) sampling into a proper zonal harmonics?

(post edited for clarification))

---

Optional: Since a ramp can be assimilated to a 1D lookup function, is there a better GENERIC way to represent it than zonal harmonics?

Relative to the 1D function idea ... Assuming I can get the stack of SH, since SH interpolate linearly, how can I infer a function that fit the Y variation of the SH coefficient? What's the best (free) tools to help me do that ie plotting arbitrary point from a source (ramp texture) and finding/visualizing the correct curve? I heard (and dl) python X,Y can help but it's like handling a Japanese manual written in Klingon to me ...

The idea is to make cheap generic shader by precomputing lighting (similar to unity's shadowgun) and various ndotl effect similar to penner Preintegrated skin shader, among many other ...

Optional 2: Just for curiosity, what is the state of spherical needlet basis to represent smooth lighting? (even more above my punch).

# Answer
Turns out Ready at down does that just fine in the ps4 exclusive (for the same reason): http://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013\_pbs\_rad\_slides.pptx

> One issue we had to tackle with our skin shading was using our pre-integrated diffuse scattering term with our spherical harmonics lighting probes.
>
> Fortunately this is pretty simple to do with SH if you already know how to compute standard diffuse irradiance. With SH you can convolve a radially-symmetrical kernel with a lighting environment using a simple dot product, and for standard diffuse you use a clamped cosine as a kernel. **All you need to do this is a representation of your kernel as zonal harmonics**, *so we compute that by numerically integrating the diffuse scattering function with the zonal harmonics basis functions.*
>
> We then store those ZH coefficients in a lookup texture parameterized by surface curvature, and at runtime we sample the appropriate coefficients and use them to perform the dot product with the lighting environment stored in the probe. Note page 7

My problem is that I still have problem translating this in useable code ;\_;

It's hard to go through the language barrier of the note, but once I pass that the math and it's notation is hard for me to translate (especially anything involving integrale). I hope this useful for someone else ...
> 0 votes

---
Tags: mathematics, shaders, spherical-harmonics
---


# Question
Title: What is physically correct lighting all about?
I can't find anything comprehensive using Google. I'm wondering what the core concepts of physically correct lighting are, and where I could read up on it. What's physically correct lighting all about? Is Phong illumination generally physically incorrect?

# Answer
> 17 votes
This is a much bigger topic than can be covered in an answer, but briefly:

Physically-based shading means leaving behind *phenomenological* models, like the Phong shading model, which are simply built to "look good" subjectively without being based on physics in any real way, and moving to lighting and shading models that are derived from the laws of physics and/or from actual measurements of the real world, and rigorously obey physical constraints such as energy conservation.

For example, in many older rendering systems, shading models included separate controls for specular highlights from point lights and reflection of the environment via a cubemap. You could create a shader with the specular and the reflection set to wildly different values, even though those are both instances of the same *physical* process. In addition, you could set the specular to any arbitrary brightness, even if it would cause the surface to reflect more energy than it actually received.

In a physically-based system, both the point light specular and the environment reflection would be controlled by the same parameter, and the system would be set up to automatically adjust the brightness of both the specular and diffuse components to maintain overall energy conservation. Moreover you would want to set the specular brightness to a realistic value for the material you're trying to simulate, based on measurements.

Physically-based lighting or shading includes physically-based BRDFs, which are usually based on microfacet theory, and physically correct light transport, which is based on the rendering equation (although heavily approximated in the case of real-time games).

It also includes the necessary changes in the art process to make use of these features. Switching to a physically-based system can cause some upsets for artists. First of all it requires full HDR lighting with a realistic level of brightness for light sources, the sky, etc. and this can take some getting used to for the lighting artists. It also requires texture/material artists to do some things differently (particularly for specular), and they can be frustrated by the apparent loss of control (e.g. locking together the specular highlight and environment reflection as mentioned above; artists will complain about this). They will need some time and guidance to adapt to the physically-based system.

On the plus side, once artists have adapted and gained trust in the physically-based system, they usually end up liking it better, because there are fewer parameters overall (less work for them to tweak). Also, materials created in one lighting environment generally look fine in other lighting environments too. This is unlike more ad-hoc models, where a set of material parameters might look good during daytime, but it comes out ridiculously glowy at night, or something like that.

Here are some resources to look at for physically-based lighting in games:

And of course, I would be remiss if I didn't mention Physically-Based Rendering by Pharr and Humphreys, an amazing reference on this whole subject and well worth your time, although it focuses on offline rather than real-time rendering.

# Answer
> 0 votes
"Physically correct" means that the result looks like it would look in reality, assuming that reality would be shaped and textured the same. That means for instance that all surfaces reflect light, mostly diffuse, so most light is indirect. Also, light can travel through materials.

And yes, one specific part of physically realistic lightning includes the correct modelling of light reflected from a surface. Phong is a reasonable approximation, but only works well for point lightsources - so not for indirect lightsources, which you'll have a lot in a physically realistic scene.

Keep in mind that "physically correct" is still an area of research - not just how to model it in a computer, but also reality. It's only a few years ago that scientists discovered that some reflective crystals reflect double the amount of light back to the source compared to other directions.

---
Tags: lighting, pbr
---


# Question
Title: What happens when a texture is too large for a device
The question is two fold:

1. What happens on a device when a texture is too large for it to handle? Will it crash or simply downsize it?
2. In Unity if I use texture atlases of size 4k and then set `Texture Quality` in the `Quality settings` as **half res** will it run normally on devices with maximum texture size of 2k?

# Answer
> 2 votes
According to this thread automatic downsizing may not work, but setting half res should work.

On a related note, do you really need textures that big? If all you want from a big texture is to use it as an atlas there is really very little reason to not just use 4 2k textures instead of one 4k.

And I assume that this is about writing games for phones, for PC graphics anything that doesn't support 4k textures is really ancient.

---
Tags: opengl, unity, textures, texture-atlas
---


title: Mismatch of Entity System and Savegames

text:
# Question
Title: Mismatch of Entity System and Savegames
There is a theoretical mismatch of the entity system and the savegame system, which is think is common, but I haven't found resources about that. Therefore I will explain both systems first, as short as possible. I would really appreciate any thoughts and solutions for this conceptual problem.

## Entity system

I have an entity system for my game. That means there is a function to create a new entity that simply returns a unique integer id. And there are functions to add, get and remove properties, thus any C++ objects, to a given id.

An entity id is just a contiguous integer, which is stored as a member. When a new entity is created, this number is incremented by one and returned as the new id. When entities get deleted, only all of their properties are removed and freed but their id actually remains and is not given to a new entity again.

Now you know the basics of my entity system. As an example, an entity might have properties for physics simulation, character animation, health and skill points, camera to render from its view, and so on.

(Originally, I described my entity system in more detail. But it wasn't directly related to this question and and wanted to shorten the question. It can still be viewed in the revision history.)

## Savegame system

Previously, there was no savegame system and I created all entities as new ones on startup. But now I want to save the state when closing the application and load that on startup so that the player can continue where he left off.

I use SQLlite for storing, where each type of entity property gets its own table. I haven't decided yet if each row should store the entity id as primary key. Because this is part of my current problem.

## Mismatch of both

Unfortunately, I cannot just store simply all of the entities to database, because some entities are only temporarily valid. For example the window property that holds a window handler from the operating system, which must be requested every startup. Or the meshes which aren't kept in memory, but just hold the VBO ids to the vertices on the GPU.

So I have to store some, but not all entities. I could store their entity id in the SQLite table and allow the entity system to add entities by a given new id. But I cannot guarantee that this id isn't already used by entities that where newly created at startup. Do you see the mismatch?

Can can I store the entity id to table, and still ensure that when being loaded, no other entity shares this id? Or how to restructure and rethink my entity system and savegame system to overcome this issue, in general?

# Answer
A window handler should not be an entity property. As you said it will be retrieved every startup. So no need to store it as property. Store the handler in a subsystem responsible for dealing with windows.

Your meshes: the entity properties should contain everything to recreate the meshes, but not the meshes themselves. Read the necessary data from the properties to create the meshes, but hold the mesh ids in a render manager or something similiar.

Think about it that way: your entities and their properties represent state of the game world. They describe the state of the game world and your subsystems (rendering, physics, audio, ai etc.) read these properties and create any necessary internal objects (sprites, meshes, loading sounds etc.).
> 4 votes

# Answer
Two pieces.

First, it's handy to have an idea of "archetypes." This is some data that defines a type of game object and which components it has and what their data is. For instance, you might have data file like:

```
Player:
  Sprite:
    image: character/players.png
  Physics:
    size: [2,2]
    center: [1,1]
  PlayerController
  AudioListener
  Health:
    max: 100
    current: 100
Enemy1:
  Sprite:
    image: character/enemy1.png
  Physics:
    size: [4,2]
    center: [2,1]
  AudioSource
  Brain:
    script: ai/enemy1.lua
  Health:
    max: 50
    current: 50
Enemy2:
  Sprite:
    image: character/enemy2.png
  Physics:
    size: [1,1]
    center: [0.5,0.5]
  AudioSource
  Brain:
    script: ai/enemy2.lua
  Health:
    max: 400
    current: 400

```

Assuming you track for each game object which archetype it was spawned from, you can save levels and save games as a unique ID and a list of data changes from the baseline. Exactly how you do that will vary a lot based on how you represent archetypes and inheritance of game object definitions.

It can seem like this is a class-based architecture, which it is to a degree, but maintains the flexibility of components and their data-driven potential. You can allow a form of "multiple inheritance" for archetypes if you want mixins and the like. Again, there's a bazillion ways to do this. You'll need to design a method that best fits your needs.

With this technique, you'll be default only be saving components that have changed in some way. Say your level has an instance of Enemy1 that has taken some damage. All you'd need to save is something like

```
object #7586 [Enemy1]:
  Health:
    current: 17

```

All the other components and fields are implicitly loaded as part of the Enemy1 definition. No need to save or load that data. Furthermore, since you aren't saving the whole object, the save can react to data definition changes. If you don't want that, just version you data (which you need to do in some capacity for saves *anyway*).

The second part then, which is fairly simple, is to just mark components or fields with extra metadata about whether they persist across save/load. If you mark the Health.max field as being non-persistant, then even if some effect modifies it for a particular enemy, the save file won't contain it. If the effects are saved/loaded and reapplied after load this is probably want you want.

You really want this kind of metadata markup anyway for networking, editors, and so on. You want to be able to mark up a field as being read-only so auto-generated editor GUIs don't let designers modify the field. You want to set which fields will be replicated over the network, and how (highly volatile data or semi-reliable data). Doing this in C++ is a complete pain in the rear, but it's trivial or even already partially built-in in many other languages.
> 4 votes

# Answer
You can split the ID integer space in Temporal IDs and Permanent IDs and treat it different. E.g: using a 16bits unsigned integer:

* \[0 - 32767\] Permanent IDs
* \[32768 - 65535\] Temporal IDs

This way a saved entity never will get a temporal ID and there will be no collision.

You can adjust the ranges knowing the amounts of entities of each type.
> 1 votes

---
Tags: architecture, entity-system, savegame, sql
---


title: Timestamps as ids in an entity manager?

text:
# Question
Title: Timestamps as ids in an entity manager?
I've built my own entity manager, as I found out some days ago, it is very similar to the Artemis framework.

For now, I just use integers as entity ids. Behind the scenes, there is a simple integer counting up every time a new entity is created so that the ids are handed out in incrementing order by the manager.

But recently I faced the problem that I cannot load multiple savegame files into the same scene. The issue here is that two savegames could use the same entity id for different things, causing a conflict when being load into the same scene.

Anyhow, the ability to load multiple savegames is useful to keep separated player data (his skills, inventory, custom items and tools he crafted) with scene data (rocks, trees, players in a town) and data from mods (cool new weapon pack).

So I need unique ids among every savegame file that will be created at all, without them knowing about each other. The idea that came to my mind is using timestamps as entity ids instead of consecutive integers.

(Since multiple entities might be created in the same millisecond, the timestamp should contain microseconds. And to play safe there could be also a mechanism to suffix a consecutive number if multiple entities are created in the same microsecond. To be honest I don't know how fast modern CPUs are and if they could do that, but I guess they can.)

Since I haven't heard of other people doing that, I assume that there is a trade-off. What are the disadvantages of using timestamps as entity ids? I think the performance hit will be minor and be can neglect that point.

# Answer
> 4 votes
Timestamps are a terrible thing to use for IDs, even with a high-precision timer 2 entities do not necessarily have to have a different ID (think how little time can have passed between 2 calls to CreateEntity()). Also you cant fit time into a simple 32bit integer. If you're going to load entities from two different sources there is a much easier fix. Load the first set of entities, find the highest ID and add this number to all IDs in the second set while loading.

Also, since you're talking savegames I'm not sure how ever 2 entities can have the same ID even though they are saved in multiple files. If they contain a saved state from the same game then all IDs should be unique.

Other scenarios you mention, like weapon packs and stuff should be wired by factory methods, which assign each component from the weapon pack fresh IDs while loaded. Wiring everything together instead of relying on predefined IDs.

---
Tags: architecture, entity-system, timer
---


# Question
Title: Triangulating a partially triangulated mesh (2D)
Referring to the above exhibits, this is the scenario I am working with:

* starting with a planar graph (in my case, a 2D mesh) with a given triangulation, based on a certain criterion, the graph nodes are labeled as RED and BLACK. (**A**)
* a subgraph containing all the RED nodes (with edges between only the directly connected neighbours) is formed (note: although this figure shows a tree forming, it may well happen that the subgraph contain loops) (**B**)

*Problem*: I need to quickly build a triangulation around the subgraph (e.g. as shown in figure **C**), but under the constraint that I have to keep the already present edges in the final result.

*Question*: Is there a fast way of achieving this given a *partially triangulated* mesh? Ideally, the complexity should be in the O(n) class.

Some side-remarks:

* it would be nice for the triangulation algorithm to take into account a certain vertex priority when adding edges (e.g. it should always try to build a "1-ring" structure around the most important nodes first - I can implement iteratively such a routine, but it's O(n^2) ).
* it would also be nice to reflect somehow the "hop distance" when adding edges: add edges first between the nodes that were "closer" to each other given the start topology.

Nevertheless, disregarding the remarks, is there an already known scenario similar to this one where a triangulation is built upon a partially given set of triangles/edges?

# Answer
> 2 votes
The only algorithm I've found for solving this problem is the *constrained Delaunay triangulation* algorithm discovered by Paul Chew (http://www.cmlab.csie.ntu.edu.tw/~plokm/htdocs/cmlab/%B1M%C3D/triangulate/Constrained%20Delaunay%20Triangulations.pdf ).

As in the case of the classical Delaunay triangulation, the complexity is still O(n log n), which is probably reasonable.

I wonder if there is a faster way if one starts with a tree instead of a more general, arbitrary set of non-crossing edges.

---
Tags: algorithm, graph, triangulation
---


# Question
Title: 2D Collision detection and reaction: Rect to Line
I'm working on a little 2D side scrolling platformer with a couple of friends. The issue I'm having is the level is completely defined by points. They are just a bunch of points which when I read in I turn into line segments, thus creating the floor in a sense. I've been having a lot of issues with this because I'm trying to make appropriate collision detection and reactions but I've never really approached Rect (which my characters sprite is defined as) to a Line (which would represent the section of the floor) collisions. Now I've already tried a few things and what I put together was I treated the character's Rect as if it were 4 Lines and did 4 Line to Line collisions then finding the points where the line's collided I then used some vector math to push out the line from the box. Now as far as that goes it works pretty well IF I'm colliding with one line at a time running into it straight and not on the end points. I'm really wondering if this was a good way to approach it at all really. What I did for the reaction was make a vector from the center of the character's Rect to the two points then I added them together to make a combined vector then divided it by 2 (so it wasn't to long) and then pushed out by that, which works, some of the time. I can't get it to work without 2 points of intersection.

My questions are: Should I instead go for some other sort of collision detection and reactions? or Given your character's Rect and points of intersection on those lines how would you handle the reaction for this?

# Answer
> 1 votes
Ofen, in 2d games, the collision detection is made using pythagora's theorem to calculate distance between 2 points.

You could check if the character is on a platform by calculating the distance from left and right side of the platform with the bottom center of the character.

If the distance from left and right side of the platform is smaller than the length of the platform, it means your character is on the platform or close to it. You would also probably have to check if the character is above or under it. You will probably have to set some thresold and adjust the y position of your character for it to be exactly on the platform when the character is falling on it.

To calculate pythagora's theorem, you use the following formula:

```
distance = sqrt(abs(x1-x2) * abs(x1-x2) + abs(y1-y2) * abs(y1-y2))

```

where x1,y1 is the first point and x2,y2 is the second point.

---
Tags: c#
---


title: Efficient tile maps in Corona SDK

text:
# Question
Title: Efficient tile maps in Corona SDK
I need to create a tile map based level system for Corona SDK that loads files created with Tiled \[1\]. It also needs to support user touch scrolling and zooming.

I've searched the Corona forums for possible solutions but the ones they talk about don't convince me. They basically have a matrix of Sprite objects which have an image loaded and a given position. That makes scrolling and zooming a bit hard.

Any better ideas?

\[1\] http://www.mapeditor.org/

# Answer
> 3 votes
First off, have you already seen Lime but don't want to incorporate that framework, since its entire purpose is to incorporate Tiled maps in Corona:

http://lime.outlawgametools.com/

In your searches of the Corona forums, did you find these threads?

http://developer.anscamobile.com/forum/2011/01/29/object-culling-render-process-when-not-content-area

http://developer.anscamobile.com/forum/2011/02/03/screen-culling

http://developer.anscamobile.com/forum/2011/03/24/tilemap-using-spritesheet-very-slow-device-any-help

A while ago someone had asked about developing efficient tile map performance/culling and I provided an example of one simple approach using quadrants to organize the tiles for efficiency. Then p120ph37 showed up with an even more efficient technique that changes the frame of the sprite objects without actually showing/hiding sprites.

---

What a coinciendence: just yesterday I saw this preview of the improved tiling performance in Corona's latest build.

http://www.youtube.com/watch?v=nzdjNDcn2gE

# Answer
> 0 votes
check this out running @ 60fps : http://forums.coronalabs.com/topic/33119-million-tile-engine-beta-release/

and should only get better when Corona Graphics 2.0 gets released.

---
Tags: lua, tilemap, corona-sdk
---


# Question
Title: How do I get the coordinates of a rotated shape in SFML?
I am trying to get collisions of bullets working, and am using SFML. I am using code to get the position of the points of the rectangle for collisions, however I think there's a way to do this without having to get points but by simply getting the points from SFML, since the shape is a rectangle and the points are stored in that way. Is there a way to do that? Through a combination of `getPoint()` and `getGlobalBounds()` maybe?

# Answer
1. use getLocalBound of sprite
2. Get transform of sprite
3. use transformPoint of that transform to transform a point to its rotated coords

Also you can visit my post on SFML forums:

http://en.sfml-dev.org/forums/index.php?topic=12604.0
> 0 votes

---
Tags: c++, sfml
---


# Question
Title: OpenGL Maximal amount of debug string reached
I was trying to check my current openGL code in gDEBugger, everything works fine. But, I get these messages

```
Debug String: >>>>>>>>> 1
Debug String: >>>>>>>>> 2
Debug String: >>>>>>>>> 3
...
Debug String: >>>>>>>>> 497
Debug String: Maximal amount of debug string reached (500 strings).
              Additional debug strings will be ignored

```

What are these messages, everything in my code runs fine. But its troubling to see these debug strings.

# Answer
> 3 votes
It sounds like OpenGL is generating debug warnings/errors in its internal queue, and you are never retrieving them, so they just pile up until they reach the limit of 500.

To fix it, you can provide a callback function for OpenGL to inform you whenever it generates one of these messages, rather than putting it on the queue. Or you can query the queue at regular intervals (e.g. once a frame, assuming you don't generate 500 messages in a single frame), and clear out the old messages to make room for new ones.

For more details, see the GL\_ARB\_debug\_output spec.

---
Tags: opengl
---


# Question
Title: How to use UpdateSubresource and Map/Unmap?
From what I understood (from reading various pages) there are 2 ways to update a buffer:

1. `UpdateSubresource()` (when buffer is created with `DEFAULT` usage)
2. `Map()`, copy the new data, `Unmap()` (when buffer is created with `DYNAMIC` usage)

In the first case do I only call this one function (nothing more)? Because I've seen people say they map the buffer and then update subresource, or maybe I misunderstood them.

Also is there any other way (doubt it :P)? Do I understand things correctly?

# Answer
> 12 votes
There's a good presentation about this: Don't Throw It All Away: Efficient Buffer Management by John McDonald at NVIDIA. It covers various topics, but on the subject of your question, the general advice is to create buffers with dynamic usage and use `Map()` with `D3D11_MAP_WRITE_DISCARD`, when the data needs to be updated frequently (like every frame, or multiple times per frame). This would be used for constant buffers, vertex buffers for particle systems, and suchlike.

According to the presentation, default usage / `UpdateSubresource()` incurs more CPU overhead than dynamic usage / `Map()`. However, he does recommend default usage / `UpdateSubresource()` for data that needs to be updated only once in awhile, such as data streamed in from disk in an open-world game.

And yes, in the case where you use `UpdateSubresource()`, you would use it by itself, not in combination with `Map()`.

# Answer
> 3 votes
They may have been referring to the actual act of updating a resource and not to the actual function call. In general, UpdateSubResource should be used for default resources that are not subject to *frequent* updates (i.e.: not every frame. In this case, it is more likely that the buffer could be to be copied to a temporary buffer accessible from the command buffer (due to race conditions for example). It will also allow you the update *sub* resources (in textures, for example).

Map/Unmap should be used when a resource is going to be updated very frequently (i.e. every frame), such as some constant buffers. The most common case is when you are overwriting the whole buffer with WriteDiscard. There's an nVidia presentation where they reccommend this practice.

---
Tags: c++, directx11
---