# Question
Title: How to sync the actions in a mutiplayer game?
I connect the clients with UDP (its a peer to peer connection on a multicast network) and the clients are sending their positions in every frame (in WP7 it means the default 30 FPS) to each other. This game is kinda a pong game, and my problem is the next: whenever the opponent hits the ball the angle will not be the same on both mobiles. I think its because the latency (1 pixel difference can cause a different angle). So my question is: how can I sync the hitting event?

# Answer
In a multiplayer game, every gameplay-relevant decision should be made by only one system. When multiple systems make a decision, like in your case the trajectory of the ball, and they disagree due to timing issues, the game gets out of sync.

When each client calculates the angle only after its own collisions and sends the new trajectory of the ball to the other, you will get the best results.

But note that this allows the players to cheat. They could manipulate their client to always tell the other client that they hit, and that the ball is now flying in an impossible to catch trajectory. The only way to fix that, is to introduce a neutral referee in form of a central server which receives the users input, calculates all game mechanics, and sends the results to the clients.

**By the way:** You could safe a lot of bandwidth when you would send the client positions only when they have actually changed, and not on every single frame.
> 5 votes

---
Tags: xna, networking, windows-phone-7, synchronization, udp
---


title: how to use a mask texture?

text:
# Question
Title: how to use a mask texture?
A texture pack for a sponza model contains mask textures (black and white). I guess that I should read only a red channel from that texture, right ? I use deferred rendering and for shading calculations I use additive blending. A result is first save in a texture (for some post-process operations), so doesn't go directly to the default framebuffer. How to use a mask texture ?

# Answer
> 2 votes
Mask textures basically let you choose different shading branches depending on texels info.

For example simplest reflection mask `Result = Ambient.rgb + Mix(Diffuse.rgb * Texture.rgb, Reflection.rgb, Mask.r);` will mask certain areas as reflective and others as normal.

Depending on mask texture format, e.g. `GL_RGB` it may have each channel used for different purpose (`r` for specular, `g` for reflection, `b` for something else). OpenGL allows number of texture format that have just one component `GL_LUMINANCE` if you need only one mask.

---
Tags: opengl, textures, glsl
---


title: 3d Collision Handling

text:
# Question
Title: 3d Collision Handling
I have trouble while detecting collisions on my 3D-Game.

I have set-up Rays, to detect collisions (Screenshot) and my main-rountine already analyzes them. But now there's the question what to do with that.

One possibility would be, to move the player back to the last position, but that's dirty, and does not work if the player can walk in multiple directions (e.g. if the player runs along a wall).

My question is, what to do with the collision data / or in which direction, by which amount move the player? I'm sure there is an algorithm for that (as for almost all is).

# Answer
I guess you're going the right way, but there's more to that than you imagine. Collision detection is a vast research topic (GAMMA).

From Wikipedia:

"(...) physical simulators usually function one of two ways, where the collision is detected a posteriori (after the collision occurs) or a priori (before the collision occurs). In addition to the a posteriori and a priori distinction, almost all modern collision detection algorithms are broken into a hierarchy of algorithms. Often the terms "discrete" and "continuous" are used rather than a posteriori and a priori."

And it follows as this:

"In the a posteriori case, we advance the physical simulation by a small time step, then check if any objects are intersecting, (...) and the positions and trajectories of these objects are somehow "fixed" to account for the collision."

"In the a priori methods, we write a collision detection algorithm which will be able to predict very precisely the trajectories of the physical bodies (...) and the physical bodies never actually interpenetrate (...)"

**Where to begin:**

From my experience, I read a long time ago David Eberly's "3d Game Engine Design" book, which has a chapter on the subject that ends with a simple collision detection system implementation. I think it is a very adequate starting source, due to the fact you're trying to build a game engine.

Another way to go would be reading this very well recomended book (Real-time collision detection).

In addition, a quick google search on "collision detection state of art" led me to this paper.

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.189.2180&rep=rep1&type=pdf

It's from 2005 but looks ok, at least to me.

Hope this helps,

\[\]'s
> 1 votes

---
Tags: 3d, collision-detection, panda3d
---


# Question
Title: Converting a hipoly model to a lowpoly model
I have a model with more than 500.000 polygons and I want to speed up the drawing process in my game. So I decided to use a lowpoly model and normal mapping, but found no software to get a lowpoly model from my hipoly model. Does anyone have an idea how to do this?

# Answer
For an automated process, MeshLab can decimate meshes reasonably. If you want more control, lots of 3d modeling packages have retopo tools. Blender with the 'Remesh' or 'Decimate' modifier can also do a good job.
> 3 votes

# Answer
Give Progressive Meshes a read (PDF). Scroll to the very end to see some pictures of his results. Obviously that document goes way further than what you're looking for, but the fundamentals of simplification are there.

Basically, for some n edges, turn them into vertices by averaging their two endpoints. The more times you do this, the simpler your mesh will be while maintaining the same rough shape. For best results, get rid of smallest edges first, and try to avoid getting rid of edges on sharp corners or high detail areas. These can usually be detected by using the surface normals.
> 1 votes

---
Tags: models, low-poly
---


title: Build a view frustum from angles

text:
# Question
Title: Build a view frustum from angles
I have 4 angles, left, right, top & bottom. These angles are in degrees. They define the angle between the forward vector and the corresponding side. I am trying to use these to calculate the required values for Perseective Off Centre function found here http://docs.unity3d.com/Documentation/ScriptReference/Camera-projectionMatrix.html I tried doing `(near plane-far plane) * Tan(angle)` But that didn't give the correct results.

# Answer
> 1 votes
You have to know exactly what you're looking for. I believe `TOP` in the referenced link here refers to what I call `o` in the diagram below.

You just need to complete this for every angle. Keep in mind the **far plane** is measured from `eye` TO the far plane, and so is the Near plane. Both **near** and **far** should always be **positive** because they measure a distance **from the eye**. So you *don't* do `far plane - near plane` and you definitely don't do `near plane - far plane` (that will always be a large negative value).

---
Tags: mathematics, algorithm, frustum
---


# Question
Title: Which structures to use for maintaining 2D objects on canvas? How to map clicks to objects?
I need to draw some 2D objects on a canvas. And I need to map the 2D coordinates of clicks to objects.

What is the usual way to maintain a 2D object's size and position (which data structures, etc.)? What's the effective way to say: this object is at coordinates (x, y)?

# Answer
> 1 votes
Iterating through an array of objects checking for their intersection with a given point would be an *effective* method. But a more *efficient* method would be using a spatial subdivision data structure like a Quadtree.

# Answer
> 2 votes
I don't know if you are using a Game Framework, so i will give you here a few hints using 'standard' javascript. You might have to adapt them to your Framework.

So let us say we have a 'namespace' gg:

```
 var gg={};

```

We create an array containing all our graphic objects :

```
 var gg.GraphicObjects = [];

```

We add a method to add a graphic object :

```
 var gg.addGraphicObject = function (x, y, width, height, parameters)
  {
     var newGraphicObject = { x:x, y:y, width: width, height : height,
              id : parameters.id, clickCallback : parameters.clickCallback ,
              hoveringCallback : parameters.hoveringCallback };
     gg.GraphicObjects.push( newGraphicObject );
     return newGraphicObject;
  }

```

parameters containing : id : string identifying the object, hoveringCallback : ..., clickCallback : ... , and you might think of other properties.

Rq that you must bind the callbacks if you reference to 'this' in the callbacks :

```
 var myObjectHandle = gg.addGraphicObject(100,100,60,60, { id : 'start',
                                    clickCallBack: this.start.bind(this) });

```

then you must handle click, which is done like this in a standard way (again, your framework might handle it allready) :

```
// myCanvas is the main page canvas ( = document.getElementById('myCanvasName'); )
myCanvas.addEventListener('click', on_click, false);
var  on_click = function(ev) {
    var mx = ev.clientX ;  //- CanvasLeftOffset ; if you use offsets (offsetLeft)
    var my = ev.clientY ; // - CanvasTopOffset ;  if you use offsets  (offsetTop)
    for (var i=0; i <gg.GraphicObjects.lenght ; i++) {
       var gObj=gg.GraphicObjects[i];
       if (gg._inRect(mx, my, gObj) )
          {
            if (gObj.clickCallBack) { gObj.clickCallBack(); }
          }
     }
 }

 gg._inRect : function(x, y, gObj ) {
         return   x >= gObj.x               &&
                  x <  gObj.x + gObj.width   &&
                  y >= gObj.y               &&
                  y <  gObj.y + gObj.height;
    }

```

if you want to handle mouseOver, it's a little bit trickyer (?), since the mousemove event is just triggering too often and is annoying... but you can cool it down using a setTimeout in this way :

```
gg.mouseMoveRefresh = 30; // number of mouse move refresh per second

gg._onmousemove =   function() {
   for (var i=0; i <gg.GraphicObjects.lenght ; i++) {
       var gObj=gg.GraphicObjects[i];
       if (gg._inRect(mx, my, gObj) )
          {
            gObj.isMouseOver = true;
            if (gObj.hoveringCallback ) { gObj.hoveringCallback (); }
          }
        else gObj.isMouseOver = false;
     }
    myCanvas.onmousemove= null;
    setTimeout( gg.onMouseMoveSet, 1000 / gg.mouseMoveRefresh);
     }

gg.onMouseMoveSet =  function() {
    myCanvas.onmousemove = gg._onmousemove;
  }

gg.onMouseMoveSet();

```

Notice that if you resize your canvas you *might* have to set again event listeners (i couldn't get a clear opinion about this behaviour cross-browsers/OS/versions/etc...).

---
Tags: 2d, html-canvas
---


# Question
Title: The best way to structure/design game code
My question is quite broad and related to the 2D game code design/architecture/structure.

Usually the main game consists of the main loop where you update & render your world states. However, it's recommended for many purposes to separate rendering from the game-logic and so on.

I am kinda confused about the whole situation. Many game engines/libs/sdks don't follow separation schema. They propagate a way where you define some scenes/stages and they contain some objects and the scene/stage controls the user input and so on. For example, in cocos2d(-x) and libgdx (stage2d) the games are usually done the way that the update logic happens at the same time/place as rendering. Also, the propagated way is to have a structure where an object knows how to draw itself - which is not a separation of updating & rendering. The same with Flash based games, they are usually done the way when an object (class) contains a swf or a texture and some data and holds some update logic itself, or updated from main Scene. And again this object already knows how to draw itself via "addChild".

Also, some people recommend to use MVC pattern, which will require to completely obey the structure of those engines/libs/sdks.

Maybe I am overthinking everything, but I am totally confused.

I would be grateful if somebody could point me to a correct direction with the game code structures. What is your way of doing things in libgdx/cocos2d/flash?

# Answer
Sometimes, depending on the chosen tools (language, frameworks, etc.), your game code will get entangled to code that's not specific to it.

Fortunately, you should always be able to grasp the basic elements necessary to work properly with your chosen tools. They'll always be there - they might just have a different name/appearance on each case (i.e.: render callbacks, timer ticks, input event handlers, etc.). Once you recognize how the basic blocks of your game fit along your tools it will just be a matter of how you fill these blanks spaces with your code.

About MVC, I think it's a pattern applicable to only a few and very specific types of games. I'd dare to say that the guideline is to use it only when you want to have a clear separation of user interface, game logic and entity management code. A turn-based strategy browser game, in which you have a large list of game entities you have to persist on disk (FS, DBMS, etc.), a game logic that's constantly evolving and a UI system that targets multiple platforms (IOS, Android, HTML 4, etc.), is a good candidate for a MVC architecture. Again: you could try to apply this pattern to any sdk, engine, lib, etc. - the more flexible your chosen tools are, the easier should be for you to implements these concepts.

From the tools your mentioned, I only have worked with flash. I remember that, when I was using it, all I wanted was to desperately avoid Adobe's hibrid designer/developer environment. So I usually chose between Standard Flash API + FlashDevelop and Flex SDK \+ Flex Builder. It may not appear to, but the choice of IDE/SDK have tremendous influence on the way a flash game is developed.

Last but not least, I guess you need some experience before being able to decide what's the best way to structure a game. Some decisions will depend on structured knowledge, but others are matter of personal taste. Start some self-teaching projects - they're great to give you some insight on specific subjects. Also, try to download a few open source games that use the tools you like. Study their code carefully. When you feel stuck, read about a specific topic in specialized literature (i.e.: real-time rendering).

Well, I know my answer was quite abstract, but I hope it helped.
> 2 votes

---
Tags: 2d, cocos2d, libgdx, architecture
---


# Question
Title: Creating Transparent Game Menu Items using AndEngine
I'm trying to create a Game Menu which contains some Menu Items like

1. New Game
2. Multiplayer
3. Options
4. Exit

I want to make this Menu Items Transparent. Only Text in White color should be visible.
So i guess i do not need any background image for Menu Items.

I have seen examples of SpriteButton like given below.

```
ButtonSprite playButton = new ButtonSprite(0, 0, btnNormalTextureRegion, btnPushedTextureRegion, this.getVertexBufferObjectManager(), new OnClickListener() {
    @Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
        // Do Stuff here
     }
}

```

The thing which i don't understand is how can i initialize **btnNormalTextureRegion**?
I use the code give below to initialize ITexture and ITextureRegion for objects.

```
mBackgruondTexture = new BitmapTexture(activity.getTextureManager(), new IInputStreamOpener() {
                public InputStream open() throws IOException {
                    return activity.getAssets().open("gfx/backgrounds/greenbg.jpg");
                }
            });
mBackgruondTextureRegion = TextureRegionFactory.extractFromTexture(mBackgruondTexture);

```

This code openes up an Image from assest.
As i do not want to use any image for Menu Item How can i initialize **btnNormalTextureRegion** for SpriteButton.

OR

Is there any alternative to create Game Menu?

# Answer
> 1 votes
You can always use the power of Android activites and UI widget to create the Main menu. Here is what you can do :

1. Create an Activity and have this intent filter for it :

`<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>`
2. On this activity have all the menu options you have mentioned. This means create a xml with the design as you want it to be. Also keep it full screen.
3. On 'New Game' click (keep it Button or ImageButton), start the GameActivity which you might have extended from `SimpleBaseGameActivity`, `SimpleLayoutGameActivity` etc. Use `intent.startActivity(/**context**/,/**gameActivity class**/)`

Remember that the game activity you create using andengine is just another Activity. You will just have to take care of the activity life cycles. This is because the AndEngine game activity will be holding the SurfaceView. Let me know if you need detailed help.

---
Tags: android, sprites, andengine
---


# Question
Title: Using C++11 for cross-platform Game Engine Development
**Note:** This is not a 'give your opinion' question about C++03 and C++11.

Our game engine, written in C++03, is designed to be compiled on Windows, OSX and iOS. Linux support is planned for the (very) near future. Our experience is limited when it comes to consoles, which is why I am asking this question.

Currently, we are debating whether switching to C++11 and using non-compatible features of the C++11 standard could pose a problem in the near future when we need to port our engine to any of the current gen consoles (perhaps the compilers supported by some console(s) do not support C++11 yet? We don't know...).

So, game developers who have experience across multiple platforms and consoles, do you think we should stick to C++03 until the new generation of consoles arrive and most everybody has switched to C++11 standard (have they already?). Or are most consoles using/support compilers (VC++, GCC or variants?) that are already supporting C++11 features?

# Answer
> 19 votes
If you rely on your code in order to pay for food and shelter, and you need to support cross-platform on unknown future platforms (or reasonably might need to support cross-platform in the future), then designing your code to rely on a bunch of unknown compiler writers' correct adherence to bleeding edge language standards is dangerous (and I would argue, irresponsible). It's dangerous for you, and therefore also dangerous for your dependents.

If you're willing to take that sort of risk for the sake of `auto`, then by all means, go for it. But I'm not going to advise you to do it.

Because in my experience, going cross-platform, **particularly on consoles**, is best accomplished by aiming for the lowest common denominator which you can be certain will work virtually everywhere, not by relying on all the latest whiz-bang language features. If someday you need to port to a platform which doesn't support them, you wind up having to rewrite your systems from scratch. Can you afford to pay wages/rent while that happens?

# Answer
> 6 votes
If your willing to do a bit more work, you could look into refractoring solutions. clang has some interesting stuff happening in that area currently. It should be possible to use the auto keyword, run it through the refactorer which will find all uses of it, resolve them for you and output the code then compile it with whatever you want.

But that means less time to work on your game.

There is also the potential for some extra features, for example reflection. You could create a class and automatically generate a list of all the properties to inspect at runtime. Could be very useful for scripting, producing game editors and so on. EDIT: Check out clreflect.

http://cppnow.org/session/refactoring-c-with-clang/

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

http://clang.llvm.org/docs/Tooling.html

http://clang.llvm.org/docs/RAVFrontendAction.html

---
Tags: cross-platform, c++
---


# Question
Title: How can I capture every frame in DirectX 9 using a shader
This is actually a follow up to this question How to capture the screen in DirectX 9 to a raw bitmap in memory without using D3DXSaveSurfaceToFile

The proponent of the best solution suggested that I should look at a shader program to capture the screen. How could I do that. I have no clue on how can I use a shader program to do that.

# Answer
Shaders don't capture the screen in and of themselves. What's being suggested in the "shader based approach" is to:

1) Use render-to-texture or the like to render your entire scene to a single texture 2) Render that texture (with, say, a fullscreen quad) to your final output (or another texture if you want to chain effects or do multi-pass effects) using pixel and/or vertex shaders written in HLSL to apply your filtering effect instead of C++.

This has the advantage of keeping everything in GPU memory instead of spending your limited memory bandwidth copying everything from GPU to system memory (where C++ can work on it) and back (where it can be rendered.)

Methods of note for wrangling pixel shaders (commonly used for operations such as bluring, depth of field effects, tinting, you name it): D3DXCompileShaderFromFile, CreatePixelShader, SetPixelShader, SetPixelShaderConstantF

And for render targets: SetRenderTarget, BeginScene, and EndScene.
> 2 votes

# Answer
You cannot directly use a shader program to get the screen but you can copy the back buffer from the gpu to the cpu and then do what you want with it, be it save, etc.
> 0 votes

---
Tags: directx, shaders, directx9, screen-recording
---


# Question
Title: Does XNA/MonoGame have a text caching mechanism, or has an open source one been implemented?
I'm playing around with MonoGame, and I've noticed the SpriteFont class draws static text very inefficiently. Each time the text is drawn the spacing is recalculated. This isn't a big deal on my quad core PC, but on mobile applications it might be a problem.

Before I go and program some text which caches the arrangement of its letters in an array and then feeds that array to the SpriteBatch, I would like to make sure there isn't something available to do this already, either in MonoGame itself or a class someone has implemented and made available for general use.

# Answer
you can convert the spritefont into a Texture2D (RenderTarget inherits from Texture2d i think)

as described in this article http://nullcandy.com/particle-text-in-xna-and-javascript/

```
Vector2 size = font.MeasureString(text) + new Vector2(0.5f);
int width = (int)size.X;
int height = (int)size.Y;

RenderTarget2D target = new RenderTarget2D(device, width, height);
device.SetRenderTarget(target);
device.Clear(Color.Black);

SpriteBatch spriteBatch = new SpriteBatch(device);
spriteBatch.Begin();
spriteBatch.DrawString(font, text, Vector2.Zero, Color.White);
spriteBatch.End();

device.SetRenderTarget(null);   // unset the render target

// read back the pixels from the render target
Color[] data = new Color[width * height];
target.GetData(data);
target.Dispose();

```

if required it may be possible to create your text this way
> 1 votes

# Answer
One option is to use bitmap font rendering instead.

http://www.craftworkgames.com/blog/tutorial-bmfont-rendering-with-monogame/
> 0 votes

---
Tags: xna, text, monogame
---


title: Set Checkpoints vs. Player Saves

text:
# Question
Title: Set Checkpoints vs. Player Saves
I'm making a top-down action / horror game, and I'm in the process of adding a "save game" feature. However, I'm torn between having automatic checkpoints throughout the level and letting the user save the game whenever they please.

What are the pros / cons of each approach?

# Answer
If you're looking at this for the benefit of the player, **allow the player to decide, indirectly, via the difficulty setting.**

Checkpoints Pros/Cons:

* Increases death penalty, Pro for more hardcore gamers, Con for casual players
* Allows player to become more immersed in the game
* Lets the developer choose the save location, so the player is less likely to have a bad save (i.e. a save game that loads into an impossible to survive situation, possibly ruining the entire progress of the game)

Save Game Option Pros/Cons:

* Easier for the casual player
* Cheapens the effect of death
* Could lead to bad saves, as mentioned above

So with that information, it seems to me, that allowing both but they change based on difficulty level.

* **Casual**: Checkpoint frequently, allow player to "quick save" and "quick load"
* **Normal**: Checkpoint semi-frequently
* **Hard**: Checkpoint rarely
* **Insane**: Only checkpoint at start of level/map/whatever

Other options:

* **Choose Wisely**: Allow player 3 player chosen saves, no auto saves

You'd likely offset the choices above with other benefits like only allowing certain weapons to unlock in the harder difficulties or higher level caps.

Additionally, to help mitigate the risk of having a bad save, checkpoint or otherwise, have the save system use a rolling save system with 3 or 4 save slots where the oldest gets overwritten.
> 10 votes

# Answer
Queston's fine. If you're making a horror game, i'd advise against letting the player save. This is simply due to the fact that in a horror game, if you give player tools to defend himself, that may be a gun or a re-load option, you're taking away most of the tension. You can put together the scariest monster anybody could ever imagine, but if it dies to bullets or if you can just reload whenever you want, then all the tension is gone. Just implement checkpoints if you need to save the game periodically, that way the player's atleast fighting to find the next checkpoint (don't make it obvious though, the player will know you're saving his progress anyway, but he doesn't have to know when you're doing it, untill he dies).
> 10 votes

# Answer
I'm not an expert, but personally, I *hate* checkpoint systems. Especially in horror games, or any other games that try to impart a specific experience on the player.

A horror game should bring fear and suspense. However, when you are replaying a section of a game because you screwed up, it *stops* being frightening or suspenseful - after all, you've already seen it! You can replay once, twice, but if for some reason you have to replay the same section many times, the horror experience would be utterly shattered. And with a checkpoint system, the player can do nothing but replay the same section over and over, until she finally succeeds or quits in frustration.

Of course, on the other hand, having a quick save option decreases fear and suspense because the player has "nothing to fear". For me personally, forced replays are far worse, but maybe your intended audience is different.

Anyway, I believe it pays to think about some ways to reduce/eliminate this "forced replay" effect. Instead of, or in addition to, quick saves, you can have some kind of "skip difficult section" mechanic, or dynamically reduce difficulty on replays. Perhaps you can change the game dynamically after load (especially if you're using procedural generation), so that each subsequent replay is different.
> 4 votes

# Answer
Checkpoints? No! If you love your clients and players of game you developed, DON'T use checkpoints. Ever.

Result of checkpoint saves in your game type is obvious: Gamers will get frustrated very fast and will abandon game and then they will tell to others not buy this game because of checkpoints.
> -2 votes

---
Tags: game-design, savegame
---


title: Create and use a Button class on AS3.0

text:
# Question
Title: Create and use a Button class on AS3.0
I am currently working on a game and it is all going well. On the shop screen there are several buttons that affect the player's stats for when the player restarts the game.

The button's names (with a text on the left), however, are rather cryptic and it's hard to figure out what they do unless you test or something.

So the solution I came up with, is to create an InfoBox with an InfoText inside so that when the cursor is over the button it appears with the description, cost and etc.

This I managed to do too however, the way I was about to do it would mean that I had to create 3 event listeners per button (CLICK, ROLL\_OVER, ROLL\_OUT) and, obviously, 3 functions connected to each event listener.

Now, I don't mind much about having 1 event listener per button, for the click, but since the other events are just to make a box appear and disappear as well as display some text, I thought it was way too much of a mess of code.

What I tried to do: I created a new class called InfoBoxButton, and this is the class' code: package {

```
import flash.display.SimpleButton;
import flash.display.MovieClip;
import flash.ui.Mouse;
import flash.events.MouseEvent;

public class InfoBoxButton extends SimpleButton
{
    public var description:String;
    public var infoBox:InfoBox;

    public function InfoBoxButton(description)
    {
        this.addEventListener( MouseEvent.ROLL_OVER, displayInfoText, false, 0, true);
        this.addEventListener( MouseEvent.ROLL_OUT, hideInfoText, false, 0, true);
    }

    private function displayInfoText()
    {
        infoBox.infoText.text = description;
        infoBox.visible = true;
    }

    private function hideInfoText()
    {
        infoBox.infoText.text = "";
        infoBox.visible = false;
    }
}

```

`}`

But now I don't have an idea how to associate it with the button, I have tried this: `public var SoonButton:InfoBoxButton = new InfoBoxButton("This is merely a test");`

The `SoonButton` is a button I made on the shopscreen, SoonButton is it's instance name, but I can't think of a way of associating one button to the other... I have been fiddling with the code for like 3 hours yesterday and no luck... can anyone give me some pointers on how I should go about doing it?

--EDIT--

I tried to trace the SoonButton after it is created like this: public var SoonButton:InfoBoxButton = new InfoBoxButton("This is merely a test");

```
    trace(SoonButton, "whut?");

```

and I got an error saying: 1120: Access of undefined property SoonButton.

if I separeted the first line a bit to: public var SoonButton:InfoBoxButton; SoonButton = new InfoBoxButton("This is merely a test");

```
    trace(SoonButton, "whut?");

```

I would get the same error but two times, for each SoonButton... so clearly it must be the InfoBoxButton that isn't being created... what am I missing?

# Answer
You have to make an instance of the InfoBox in your code:

```
 public function InfoBoxButton(description) {
    this.infobox = new InfoBox();
    this.addChild(this.infoBox);
    this.infoBox.visible = false;
    infoBox.infoText.text = description;
    // add some formatting here - x,y postions etc.

    this.soonButton.addEventListener( MouseEvent.ROLL_OVER, displayInfoText, false, 0, true);
    this.soonButton.addEventListener( MouseEvent.ROLL_OUT, hideInfoText, false, 0, true);
 }

 private function displayInfoText() {
    infoBox.visible = true;
 }

 private function hideInfoText() {
    infoBox.visible = false;
 }

```
> 1 votes

---
Tags: flash, actionscript-3, flash-cs5, flash-develop
---


# Question
Title: How to account for speed of the vehicle when shooting shells from it?
I'm developing a simple 3D ship game using libgdx and bullet.

When a user taps the mouse I create a new shell object and send it in the direction of the mouse click. However, if the user has tapped the mouse in the direction where the ship is currently moving, the ship catches up to the shells very quickly and can sometimes even get hit by them - simply because the speed of shells and the ship are quite comparable.

I think I need to account for ship speed when generating the initial impulse for the shells, and I tried doing that (see "new line added"), but I cannot figure out if what I'm doing is the proper way and if yes, how to calculate the correct coefficient.

```
public void createShell(Vector3 origin, Vector3 direction, Vector3 platformVelocity, float velocity) {
    long shellId = System.currentTimeMillis(); // hack
    ShellState state = getState().createShellState(shellId, origin.x, origin.y, origin.z);
    ShellEntity entity = EntityFactory.getInstance().createShellEntity(shellId, state);

    add(entity);
    entity.getBody().applyCentralImpulse(platformVelocity.mul(velocity * 0.02f)); // new line added, to compensate for the moving platform, no idea how to calculate proper coefficient
    entity.getBody().applyCentralImpulse(direction.nor().mul(velocity));
}

private final Vector3 v3 = new Vector3();
public void shootGun(Vector3 direction) {
    Vector3 shipVelocity = world.getShipEntities().get(id).getBody().getLinearVelocity();
    world.getState().getShipStates().get(id).transform.getTranslation(v3); // current location of our ship
    v3.add(direction.nor().mul(10.0f)); // hack; this is to avoid shell immediately impacting the ship that it got shot out from
    world.createShell(v3, direction, shipVelocity, 500);
}

```

Edit - I switched to:

```
    v3.set(direction);
    v3.nor().mul(velocity);

    if (platformVelocity != null)
        v3.add(platformVelocity);

    entity.getBody().setLinearVelocity(v3);

```

And it seems to work (so adding the velocities and setting them on the body).

However, I'm not sure what the drawbacks are and why the tutorial application used impulses instead of setting velocities.

I also think that while this is physically correct it leads to strange results (gun range is two times further when shooting forward than when shooting sideways).

The root cause is because really the shells are indeed too slow, but I like them slow as otherwise the gameplay is too fast-paced, and they travel too far.

I think I need some compromise between physics-realistic and ignore-platform-velocity.

# Answer
The shell's speed was the same as the ship's speed before it got fired, if you think about it. It was sitting on the ship. So, if you add the velocity from being fired to the velocity of the ship, you should get the correct result.
> 6 votes

# Answer
Replace your new line with:

```
entity.getBody().setLinearVelocity(platformVelocity);

```

You might want to do the same for the shell also instead of finding desired impulse, which depends on the mass of the shell.
> 4 votes

---
Tags: physics, bullet-physics
---


title: How does one accurately design a UI?

text:
# Question
Title: How does one accurately design a UI?
I'm currently wishing to draw up my UI for a 2d game, however I'm not so sure what the normal strategy is for creating the images for a UI. Are there any programmes which are specifically accurate for UI Design or is something like Photoshop perfectly fine?

# Answer
> 1 votes
You can use any graphics tool you are comfortable with. I'm not sure what you mean by "Accurate for UI Design". Besides, are you talking about animations or single images?

I'll assume you are talking about animations. I'm not an artist. But the simple rule is if you made the first image in an animation sequence 50x50 pixels, then the remaining images of the sequence should also be 50x50 pixels. Should and not a must. but it will make the programming issues easier.

Accuracy comes from you.

# Answer
> 1 votes
Something like photoshop would be perfectly fine for creating UI images.

As for accuracy, I'm wondering what you mean. If it means "I want my GUI to fit over my game screen", then simply take a screenshot of your game, and use that as the bottom layer in photoshop. If accuracy means "I want the GUI to look like the default (Windows/Mac/Linux/iDevice) GUI", then you can either use native OS calls, a GUI library, get art from the internet, or draw the assets yourself.

# Answer
> 1 votes
My favorite tool is a whiteboard. If I ever want to make a design "permanent," I just take a picture of it.

# Answer
> 0 votes
To make it clear. Use can use Photoshop or any other image-manipulation or image-editor for 'mock-ups'. This helps you decide the color of each element of your GUI and the look-n-feel of it.

To actually design your UI, you will need a custom application, i.e. not Photoshop, to create your GUI and save the 'layout' (and associated images or sprites) to a file, which can be loaded by the game you're targeting the UI for.

# Answer
> -1 votes
You might want to use something like this to create and implement UI using HTML5, CSS3 and JavaScript. http://www.youtube.com/watch?v=1XxJpghF04g&feature=plcp

---
Tags: ui-design
---


# Question
Title: Orthographic unit translation mismatch on grid (e.g. 64 pixels translates incorrectly)
I am looking for some insight into a small problem with unit translations on a grid.

## Update and Solved

I solved my own issue. See below for details. Everything in this part of the post turned out to be correct. If anything it can act as a miniature tutorial / example / help for the next person.

## Setup

* FBO, VAO, VBO
* 512x448 window
* 64x64 grid
* `gl_Position = projection * world * position;`
* `projection` is defined by `ortho(-w/2.0f, w/2.0f, -h/2.0f, h/2.0f);` This is a textbook orthogonal projection function.
* `world` is defined by a fixed camera position at (0, 0)
* `position` is defined by the sprite's position.

## Problem

In the screenshot below (1:1 scaling) the grid spacing is 64x64 and I am drawing the unit at (64, 64), however the unit draws roughly ~10px in the wrong position. I've tried uniform window dimensions to prevent any distortion on the pixel size, but now I am a bit lost in the proper way in providing a 1:1 pixel-to-world-unit projection. Anyhow, here are some quick images to aide in the problem.

I decided to super-impose a bunch of the sprites at what the engine believes is 64x offsets.

When this seemed off place, I went about and did the base case of 1 unit. Which seemed to line up as expected. The yellow shows a 1px difference in the movement.

## What I Want

Ideally moving in any direction 64-units would output the following (super-imposed units):

## Vertices

It would appear that the vertices going into the vertex shader are correct. For example, in reference to the first image the data looks like this in the VBO:

```
      x    y           x    y
    ----------------------------
tl | 0.0  24.0        64.0 24.0
bl | 0.0  0.0    ->   64.0 0.0
tr | 16.0 0.0         80.0 0.0
br | 16.0 24.0        80.0 24.0

```

For sake of completeness here is the actual array corresponding to the above movements:

```
      x     y    z   w   r   g   b   a      s          t
-------------------------------------------------------------
tl | 0.0   23.0 0.0 1.0 0.0 0.0 0.0 1.0 0.14210527 0.62650603
bl | 0.0   0.0  0.0 1.0 0.0 0.0 0.0 1.0 0.14210527 0.76506025
tr | 16.0  0.0  0.0 1.0 0.0 0.0 0.0 1.0 0.2263158  0.76506025
br | 16.0  23.0 0.0 1.0 0.0 0.0 0.0 1.0 0.2263158  0.62650603
-------------------------------------------------------------
-------------------------------------------------------------
tl | 64.0  24.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0        0.21084337
bl | 64.0  0.0  0.0 1.0 0.0 0.0 0.0 1.0 0.0        0.3554217
tr | 80.0  0.0  0.0 1.0 0.0 0.0 0.0 1.0 0.08421053 0.3554217
br | 80.0  24.0 0.0 1.0 0.0 0.0 0.0 1.0 0.08421053 0.21084337

// side bar: I know that I have unnecessary data with having a z-axis.
//           The engine flips between perspective and orthogonal and I
//           haven't selectively started pruning data.

```

## Projection Matrix

The projection matrix for the 512x448 window looks like this:

```
0.00390625 0.0         0.0  0.0
0.0        0.004464286 0.0  0.0
0.0        0.0        -1.0  0.0
0.0        0.0         0.0  1.0

```

and is constructed with a textbook orthogonal projection function:

```
ortho(-w/2.0f, w/2.0f, -h/2.0f, h/2.0f);
// explicitly: ortho(-512/2.0f, 512/2.0f, -448/2.0f, 448.0f

ortho(float left, float right, float bottom, float top)
{
    projection.setIdentity();
    projection.m00 = 2.0f / (right - left);
    projection.m11 = 2.0f / (top - bottom);
    projection.m22 = -1;
    projection.m30 = -(right + left) / (right - left);
    projection.m31 = -(top + bottom) / (top - bottom);
    projection.m32 = 0;
}

```

## World-view Matrix

The camera's position is just a translation matrix which in this case I just offset by -w/2 and -h/2 to be zero relative to center.

```
1.0 0.0 0.0 -256.0
0.0 1.0 0.0 -224.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0

```

## Solutions I have attempted

1. `player.moveRight()` would move 1-unit with the aspect ratio factored into the equation. So: `gridWidth = 64 / 1.14f`. Movement did not fit within the grid.
2. Forced a 512x512 window with a matching orthogonal projection.
3. Tried various magic numbers and tried to draw correlations between the two.

With that said, all I am left to believe is that I am munging up my actual projection. So, I am looking for any insight into maintaining the 1:1 pixel-to-world-unit projection.

# Answer
> 5 votes
I solved my own problem--and rather than just blow it off as a simple explanation, I want to describe the steps I took to debug the issue. I left out that I was using a single FBO for special-effects.

First, it turns out everything above *is in fact correct* and a step I left out was the problem.

* I verified my orthogonal matrices through-and-through.
* Verified the byte-order of everything.
* Created a square texture. **\<- Here is the magic**
* When I created a square texture, I noticed it was not square on the screen, but square going into the vertex shader.
* This was my first clue that something was wrong. The dimensions of my textures on screen did not match the dimensions that were going to the vertex shader.
* I forgot that I was using an FBO (here comes the sillyness).
* The FBO texture size did not match my viewport texture size for whatever stupid reason.
* Disabled the FBO and the results matched up.
* Fixed the logic with defining my texture size and wah-lah.

I am sorry if this took up anyone's time. I will leave the question around as good measure for anyone that might run into the same problem without knowing it.

---
Tags: opengl, mathematics, camera, coordinates, projection
---


# Question
Title: Drawing multiple triangles at once isn't working
I'm trying to draw multiple triangles at once to make up a "shape". I have a class that has an array of VertexPositionColor, an array of Indexes (rendered by this Triangulation class):

http://www.xnawiki.com/index.php/Polygon\_Triangulation

So, my "shape" has multiple points of VertexPositionColor but I can't render each triangle in the shape to "fill" the shape. It only draws the first triangle.

```
struct ShapeColor
{
     // Properties (not all properties)
     VertexPositionColor[] Points;
     int[] Indexes;
}

```

First method that I've tried, this should work since I iterate through the index array that always are of "3s", so they always contain at least one triangle.

```
//render = ShapeColor

for (int i = 0; i < render.Indexes.Length; i += 3)
{
    device.DrawUserIndexedPrimitives<VertexPositionColor>
    (
         PrimitiveType.TriangleList,
         new VertexPositionColor[] { render.Points[render.Indexes[i]], render.Points[render.Indexes[i+1]], render.Points[render.Indexes[i+2]] },
         0,
         3,
         new int[] { 0, 1, 2 },
         0,
         1
    );
}

```

or the method that should work:

```
device.DrawUserIndexedPrimitives<VertexPositionColor>
(
    PrimitiveType.TriangleList,
    render.Points,
    0,
    render.Points.Length,
    render.Indexes,
    0,
    render.Indexes.Length / 3,
    VertexPositionColor.VertexDeclaration
);

```

No matter what method I use this is the "typical" result from my Editor (in Windows Forms with XNA)

It should show a filled shape, because the indexes are right (I've checked a dozen of times)

I simply click the screen (gets the world coordinates, adds a point from a color, when there are 3 points or more it should start filling out the shape, it only draws the lines (different method) and only 1 triangle). The Grid isn't rendered with "this" shape.

Any ideas?

# Answer
> 0 votes
**Solution:**

```
foreach(ShapeColor render in Shapes)
{
    device.DrawUserIndexedPrimitives<VertexPositionColor>
    (
        PrimitiveType.TriangleList,
        render.Points,
        0,
        render.Points.Length,
        render.Indexes,
        0,
        render.Indexes.Length / 3,
        VertexPositionColor.VertexDeclaration
    );
}

```

# Answer
> 0 votes
Looks like it might be a face culling issue. Try turning off face culling:

```
 GraphicsDevice.RasterizerState = RasterizerState.CullNone;

```

---
Tags: xna, rendering
---


# Question
Title: Point[] and Tri not "could not be found"
Hi I'm trying to learn how to load a .obj file using OpenTK in windows Forms. I have seen a lot of examples out there, but I do see almost everyone uses `List<Tri>`, and `Point[]`. Code examples show these highlighted like there IDE know what these are; for example

```
List<Tri> tris = new List<Tri>();

```

but mine just returns "The type or namespace name 'Tri' could not be found" is there an include I need to add or a using I am missing. Currently have this:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

```

**EDIT**: I have been trying to piece it together primarily from using code samples found here:

http://www.opentk.com/node/1946

As well as from here Missing triangles in model

---

I have been trying to piece it together primarily from using code samples found here

http://www.opentk.com/node/1946

As well as from here Missing triangles in model

# Answer
> 2 votes
`List` is `System.Collections.Generic.List`, which is the standard resizing-array-backed vector class you'd see in Java `ArrayList` or STL `vector`.

`Tri` is part of the other guy's code.

OpenTK provides `Vector3`. If you're representing a model, you're going to need a few more definitions, including your definition of what a "triangle" is. Here's a rough guideline of some classes you'd need to define:

A **Vertex** defines a single point in space, along with additional data required for rendering the mesh, such as texture coordinates, normal vector, and a vertex color.

```
struct Vertex {
    Vector3 Position;
    Vector3 Normal;
    Color4 Color;
    Vector2 TexCoord;
}

```

A **Face** defines a collection of vertices that form a single polygon in space. Most of the time, the only polygon type you'd want to use is a Triangle.

```
class Triangle {
    Vertex[] Vertices = new Vertex[3];
}

```

A **Mesh** or a **Model** defines what you'd think of as a full 3d object; it is a collection of faces. Instead of keeping a List of Triangles around, typically you keep an array of vertices, since in modern OpenGL, you would draw the mesh data by passing OpenGL a pointer to a vertex array.

Note that if you use a Vertex Buffer to render your mesh, after you've registered and populated the buffer with `GL.BufferData` or `GL.BufferSubData` you don't need to keep the array of vertices around.

```
class Mesh {
    // for educational purposes, I'm including this definition here
    // A mesh is really just a collection of triangles / vertices
    // but you don't need to keep the triangles in memory if you
    // have buffered the object data with OpenGL.
    Vertex[] AllVertices;

    // if you buffer the data, this is the buffer ID
    int elementArrayID;
    // if you buffer the data and use indexed rendering,
    // this is the index buffer id
    int indexArrayID;
}

```

# Answer
> 0 votes
Judging from the code samples you provided, Tri is simply a class that holds 3 Points. For example, the Triangulate method in the question you linked to would take an array of points and attempt to turn them into an array of Triangles by iterating through the list of points an "connecting" them via a Triangle object.

The constructor in this case takes 3 points and creates a Triangle object out of those 3 points. This would make per-triangle processing and rendering easier to manage. You would need to make sure though that you only use the same point once i.e. you should only have one Point object that refers to point 12,14 - not doing so would be a waste of memory.

So when you process the model, I would keep a list of all points you create ensuring that there are no duplicates and then process each triangle set by using the points from that list. I am not familiar with the OpenTK format - but the OBJ model format makes this easy as it lists all Vertices and then instead of listing Faces as vertices it lists indexes to the list of vertices so you'll never have the same Point in memory more than once.

---
Tags: c#, opengl, opentk, windows-forms
---


# Question
Title: How to detect whether an Object came to sleep at a specific position?
I'm currently writing a small game with box2dweb and I need some direction for this: I'm throwing a Box and have to hit a specific place and trigger an event when the object that's been thrown isn't moving anymore, "fell asleep" so to say.

What's the proper way / best practice for this?

I'm currently thinking of asking the b2World whether an Object is within a specific AABB and then wait a few seconds, check if it's still there and then trigger the event. But this seems to me like the roundabout way and the object might still be moving inside of that AABB and eventually even drop out of the AABB.

# Answer
> 4 votes
Probably the most reliable way is to modify the source of box2DWeb and have it fire an event when it puts an object to sleep (or maybe this already happens, I don't know much about box2DWeb). When you detect this event, check to see if the object is within the specific AABB you want.

It looks like the live demo found here changes the color of the object when it goes to sleep. Check out the source for that demo and see how it's being detected.

Alternatively, you can poll the object's velocity, when the velocity is all 0's, check to see that it's inside the specific AABB you want.

The latter method may be good if you want to check when the object is "close enough" to stopped. Then you can test for velocities less than a threshold value to see if it's pretty much stopped. This will give you better response times if an object is taking its time coming to a stop (as can happen with these simulations).

---
Tags: javascript, box2d
---


# Question
Title: Crash due to removal of Elements like CCSprite from NSMutableArray
So, here's how it goes.

I am currently working on Cocos2d game, which consists of many Obstacles. One obstacle gets added on the screen at an interval of 10 seconds like this.

```
ObstacleSprite* newObstacle = [ObstacleSprite spriteWithFile:@"Obstacle.png" rect:CGRectMake(0, 0, 20, 20)];
newObstacle.position = ccp(mainPlayer1.position.x,10);
[self addChild:newObstacle];

[self.arrayForObstacles addObject:newObstacle];

```

Now, I insert these obstacles into the arrayForObstacles because I also want to keep checking whether the Obstacles and MainPlayer don't collide.

I check it with the help of this function.

```
- (void) checkCollisionWithObstacle
{
    if(mainPlayer1.playerActive)
    {
        for(int  i = 0; i < [self.arrayForObstacles count]; i++)
        {
            ObstacleSprite* newObstacle = [self.arrayForObstacles objectAtIndex:i];
            if(newObstacle != nil)
            {
                if(CGRectIntersectsRect([mainPlayer1 boundingBox], [newObstacle boundingBox]))
                {
                    mainPlayer1.livesLeft--;
                }
            }
        }
    }
}

```

**THE ISSUE**

Problem is when I get to certain score, one of the Obstacles gets deleted. Removal of Obstacles works as in First In-First Out (FIFO) mode. So, to delete obstacles, I write the following method :

```
- (void) keepUpdatingScore
{
    //update new score
    mainPlayer1.score+=10;
    //remove obstacle when score increases by 5k
    if(mainPlayer1.score > 5000 && mainPlayer1.score > 0)
    {
        mainPlayer1.playerActive = NO;

        if([self.arrayForObstacles count] > 0)
        {
            CCLOG(@"count is %d",[self.arrayForObstacles count]);
            ObstacleSprite* newObstacle = [self.arrayForObstacles objectAtIndex:0];
            [self.arrayForObstacles removeObjectAtIndex:0];
            [self removeChild:newObstacle cleanup:YES];

            CCLOG(@"count is %d",[self.arrayForObstacles count]);
        }
    }
    else
    {

    }
}

```

It crashes when score crosses 5000 mark!

**UPDATE**

Crash happens when it again goes to the method `checkCollisionWithObstacle`.

This is the THREAD Look.

THis is the line Which crashes.

# Answer
> 1 votes
You may have already figured this out.

I had this same issue. For me that problem was that I was enumerating through an array of objects, such as an array of enemy ship objects, and trying to delete one of those objects before the enumeration had completed.

For example. If while looping through the array I found that an enemy was colliding with an asteroid I would then delete the enemy from the array. Let’s say for the sake of argument that my array had 20 enemy ships in it, and while enumerating through it I found that ship 12 hit an asteroid and needed to be destroyed and thus deleted. I could delete the object from the array without any problem, but then the app would crash as soon as it resumed enumerating through the array to check on ships 13 through 20. It didn’t like the fact that I had just deleted an object from an array that it had not finished looping through.

So, if at some point within your game loop you are enumerating through that obstacle array and you end up trying to delete one of those obstacles before that enumeration is finished, this could be the cause of your crash.

# Answer
> 0 votes
Could be a number of things.

For one thing this won't fix anything but it'll make your code easier to follow, you don't have to do for (int i etc.)

```
for(ObstacleSprite *temp in self.arrayForObstacles)

```

does what you did in 3 lines in 1.

This makes no sense

mainPlayer1.score \> 5000 && mainPlayer1.score \> 0

If mainPlayer1.score \> 5000 its greater than 0. So I guess it does make sense I just don't see the point.

And finally...

```
ObstacleSprite* newObstacle = [self.arrayForObstacle objectAtIndex:0];
[self.arrayForObstacles removeObjectAtIndex:0];
[self removeChild:newObstacle cleanup:YES];

```

You set newObstacle to an object in an array then you remove the object from the array then you remove it from it's parent. Don't do that.

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


# Question
Title: Changing background images frequently within a specific time range with Cocos2D
I am working on a game development project for Android. We use the Cocos2d framework. I have to design a page which contains two background images, I need to switch these images repeatedly within 1sec. How can I do this? How can I use `CCTransitionScene` in my Java code and change these images repeatedly?

Thanks in advance.

# Answer
You can also make a CCRepeatForever of a CCSequence of the actions you want to perform, and make the scene run it.
> 1 votes

# Answer
You can't use CCTransitionScene to change just the background. What you are looking for is CCActions.

But first, here is a sample of a simple "animation".

First init a SpriteFrameCache (that will store all your sprites):

```
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"destructible-clock.plist"];

CCSprite *clock = [CCSprite spriteWithSpriteFrameName:@"destructible-clock3.png"];
clock.position =  _countdownTimer.position;

[self addChild:clock];

```

Then when you need to change the sprite use setDisplayFrame:

```
        //Update desctructible clock
        CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"destructible-clock%d.png",(int)(self.countdownTimer.percentage/25)]];
        [self.clock setDisplayFrame:frame];

```

It's important that you understand SpriteSheets and/or SpriteFrameCache. Try this if you can't figure out how to make this work: http://www.raywenderlich.com/1271/how-to-use-animations-and-sprite-sheets-in-cocos2d

After that you can trigger the background swap with CCActions.
> 1 votes

# Answer
I would suggest creating an animation and then use CCAnimate class to change frames repeatedly. creating CCAnimation Object is also an easy task, you have to initialize 2 frames using textures and then passing them to CCAnimate constructor.
> 0 votes

# Answer
A few approaches.

Create two background sprites and modify their Z-order to move one on top of the other.

Create two background sprites and change their visibility flags as needed.

Create one background sprite and swap its displayframe between the different background images.
> 0 votes

---
Tags: android, cocos2d
---


# Question
Title: How to send multiple MVP matrices to a vertex shader in OpenGL ES 2.0
I'm working my way through optimizing the rendering of sprites in a 2D game using OpenGL ES and I've hit the limit of my knowledge when it comes to GLSL and vertex shaders.

I have two large float buffers containing my vertex coordinates and texture coordinates (eventually this will be one buffer) for multiple sprites in order to perform a single glDrawArrays call. This works but I've hit a snag when it comes to passing the transformation matrix into the vertex shader.

My shader code is:

```
uniform mat4 u_MVPMatrix;
attribute vec4 a_Position;
attribute vec2 a_TexCoordinate;
varying vec2 v_TexCoordinate;

void main()
{
    v_TexCoordinate = a_TexCoordinate;
    gl_Position = u_MVPMatrix * a_Position;
}

```

In Java (Android) I am using a FloatBuffer to store the vertex/texture data and this is provided to the shader like so:

```
mGlEs20.glVertexAttribPointer(mVertexHandle, Globals.GL_POSITION_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mVertexCoordinates);
mGlEs20.glVertexAttribPointer(mTextureCoordinateHandle, Globals.GL_TEXTURE_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mTextureCoordinates);

```

(The Globals.GL\_POSITION\_VERTEX\_COUNT etc are just integers with the value of 2 right now)

And I'm passing the MVP (Model/View/Projection) matrix buffer like this:

```
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mModelCoordinates);

```

(mModelCoordinates is a FloatBuffer containing 16-float sequences representing the MVP matrix for each sprite)

This renders my scene but all the sprites share the same transformation, so it's obviously only picking the first 16 elements from the buffer which makes sense since I am passing in "1" as the second parameter. The documentation for this method says:

> "This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices."

So I tried modifying the shader with a fixed size array large enough to accomodate most of my scenarios:

```
uniform mat4 u_MVPMatrix[1000];

```

But this lead to an error in the shader:

> cannot convert from 'uniform array of 4X4 matrix of float' to 'Position 4-component vector of float'

This just seems wrong anyway as it's not clear to me how the shader would know when to transition to the next matrix anyway.

Anyone have an idea how I can get my shader to pick up a different MVP matrix (i.e. the NEXT 16 floats) from my MVP buffer for every 4 vertices it encounters? (I am using GL\_TRIANGLE\_STRIP so each sprite has 4 vertices).

Thanks!

# Answer
You could add a vertex attribute to identify the index of the matrix to be used. Something like:

```
attribute int a_iMVP;
...
gl_Position = u_MVPMatrix[a_iMVP] * a_Position;

```

Of course, this will consume extra space in your vertex buffer and need to be generated by your application code. If your hardware supports instancing, this attribute could be in a separate, instanced vertex buffer, so you'd only need one value per 4 verts instead of a value for every vert.
> 3 votes

# Answer
If all your sprites share the same View and Projection matrices (you are doing 2D sprites and not 3D billboarding), calculate the final quads via CPU and update your vertex buffer with their positions. Here is an answer that explains how XNA does its SpriteBatch magic.
> 1 votes

---
Tags: opengl-es
---


# Question
Title: Transforming a primitive tetrahedron into a primitive icosahedron?
I've created a tetrahedron by creating a BoundingBox and building the faces of the tetrahedron within the bounding box as follows (see image as well):

```
VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[12];
BoundingBox box = new BoundingBox(new Vector3(-1f, 1f, 1f), new Vector3(1f, -1f, -1f));

vertices[0].Position = box.GetCorners()[0];
vertices[1].Position = box.GetCorners()[2];
vertices[2].Position = box.GetCorners()[7];

vertices[3].Position = box.GetCorners()[0];
vertices[4].Position = box.GetCorners()[5];
vertices[5].Position = box.GetCorners()[2];

vertices[6].Position = box.GetCorners()[5];
vertices[7].Position = box.GetCorners()[7];
vertices[8].Position = box.GetCorners()[2];

vertices[9].Position = box.GetCorners()[5];
vertices[10].Position = box.GetCorners()[0];
vertices[11].Position = box.GetCorners()[7];

```

What would I then have to do to transform this tetrahedron into an icosahedron? Similar to this image:

I understand the concept but applying it is another thing entirely for me.

And to clarify, I'm not wanting an animation, I simply want to create an icosahedron from the vertices of a tetrahedron.

**EDIT: So I now have an alternative way to create an icosahedron using golden rectangles. That's fine for the purposes of my particular project. However, I'd like to leave the question open for solutions to the original problem, i.e. mathematically converting a tetrahedron in Cartesian co-ords into an icosahedron (not vice-versa).**

# Answer
First, create three sets of 4 points, each set being a 3D golden rectangle in the X, Y or Z direction:

```
Vector3[] points = new Vector3[12];
float phi = 0.5 + 0.5 * sqrt(5.0);
for (int i = 0; i < 4; i++)
{
    float x = ((i & 1) != 0) ? 0.5 : -0.5;
    float y = ((i & 2) != 0) ? phi * 0.5 : phi * -0.5;
    points[3 * i] = Vector3(x, y, 0.0);
    points[3 * i + 1] = Vector3(0.0, x, y);
    points[3 * i + 2] = Vector3(y, 0.0, x);
}

```

Then create triangles to build the icosahedron:

```
static int[] trilist =
{
    0, 1, 2, 2, 4, 6, 3, 8, 1, 9, 4, 8,
    7, 0, 5, 7, 11, 3, 10, 5, 6, 10, 9, 11,
    0, 3, 1, 7, 3, 0, 1, 4, 2, 8, 4, 1,
    2, 5, 0, 6, 5, 2, 6, 9, 10, 4, 9, 6,
    7, 10, 11, 5, 10, 7, 8, 11, 9, 3, 11, 8
};

VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[60];
for (int i = 0; i < 60; i += 3)
{
    vertices[i].Position = points[trilist[i]];
    vertices[i + 1].Position = points[trilist[i + 1]];
    vertices[i + 2].Position = points[trilist[i + 2]];
}

```

### Area formula

From the Wikipedia article Icosahedron, we know that with an edge length of `a`, the radius of the circumscribed sphere is `a * sin(2 * pi / 5)`. Since we built golden rectangles, the radius is currently `0.5 * sqrt(1 + phi²)`, which can be expanded to `sqrt((5 + sqrt(5)) / 8)`, which is precisely `sin(2 * pi / 5)`! This means that our edge length is `1`.

From the Wikipedia article again, we know that the surface area is therefore `5 * sqrt(3)`.

So if you want a surface area `A`, you need to multiply all point coordinates with `sqrt(A / (5 * sqrt(3))`.

### Transformation from tetrahedron

In order to transform a tetrahedron into an icosahedron in a smooth way, each vertex needs to be duplicated 3 times. Conversely, in order to transform the icosahedron into a tetrahedron, groups of 3 vertices need to be merged into one vertex:

* Group 1 : vertices 0, 1, 2
* Group 2 : vertices 3, 7, 11
* Group 3 : vertices 6, 10, 5
* Group 4 : vertices 9, 4, 8

This is some code that should work. Just use `t` as a parameter between `0.0` and `1.0`:

```
static int[] mergelist[] =
{
    0, 1, 2,
    3, 7, 11,
    6, 10, 5,
    9, 4, 8,
};

float t = 0.5; /* 0.0 for tetrahedron, 1.0 for icosahedron */
float t1 = (1.0 + 2.0 * t) / 3.0;
float t2 = (1.0 - t) / 3.0;

Vector3[] newpoints = new Vector3[12];
for (int i = 0; i < 12; i += 3)
{
    int j = mergelist[i], k = mergelist[i + 1], l = mergelist[i + 2];
    newpoints[j] = t1 * points[j] + t2 * (points[k] + points[l]);
    newpoints[k] = t1 * points[k] + t2 * (points[l] + points[j]);
    newpoints[l] = t1 * points[l] + t2 * (points[j] + points[k]);
}

```

Then use the code above, building `vertices` using `newpoints` instead of `points`. The result can be seen in this YouTube video.
> 2 votes

# Answer
Rather than trying to transform your tetrahedron into an icosahedron, work backwards.

Construct your icosahedron, then pick four "opposite" faces of the icosahedron (like the blue or the red ones in your animated image).

The four faces you picked will be the red ones from the animation, which condense into one corner point of the tetrahedron each (green lines show which vertices move to which point on the tetrahedron):

(tetrahedron smaller for better visibility)

(actual sizes)

For the actual animation part, a simple way would be to just do a linear interpolation from those faces' vertices' positions in the icosahedron to the centerpoint of that face, which will become the corners of the tetrahedron.

Then simply animate in reverse to transform from the tetra- to the icosahedron.
> 3 votes

# Answer
First of all, you probably don't want to get your coordinates by 'converting' a tetrahedron; instead, just start with icosahedron coordinates. Fortunately, coordinates for the vertices of an icosahedron are actually pretty straightforward; they're just the corners of three 'golden rectangles' interlocked with each other: (±1, ±φ, 0), (0, ±1, ±φ), and (±φ, 0, ±1), where φ is the golden ratio (sqrt(5)+1)/2. Finding the 20 triangles that use those vertices is actually probably best done 'by hand' - put together three rectangles like that and look at how they connect and you'll get the idea pretty quickly.

On a side note, I would recommend using *vertex buffers* \- rather than having explicit vertices for every point of every triangle, instead have just a list of the 12 vertices and then index into the buffer for your triangles. In your tetrahedron example, this would be more like:

```
Vector Vertices[4] = {{-1, -1, -1}, {-1, 1, 1}, {1, -1, 1}, {1, 1, -1}};

Triangle[0].Vert[0] = 0; // (-1, -1, -1)
Triangle[0].Vert[1] = 1; // (-1, 1, 1)
Triangle[0].Vert[2] = 2; // (1, -1, 1)

Triangle[1].Vert[0] = 0; // (-1, -1, -1)
Triangle[1].Vert[1] = 2; // (1, -1, 1)
Triangle[1].Vert[2] = 3; // (1, 1, -1)
// [ ... ]

```

etc. When doing larger figures where each vertex will be part of several triangles, this saves both memory and time.
> 2 votes

---
Tags: xna, c#, geometry, transformation
---


title: GUI device for throwing a ball

text:
# Question
Title: GUI device for throwing a ball
The hero has a ball, which shall be thrown with *accuracy* in a court on iPhone/iPad. The player is seen from above, in a 2D view. In game play, the player reach is between 1/15 and 1/6 of the height of the iPhone screen. The player will run, and try to outmaneuver his opponent, and then throw the ball at a specific location, which is guarded by the opponent (which is also shown on the screen). The player is controlled by a joystick, and that works ok, but how shall I control the stick?

Maybe someone can propose a third control method?

I've tried the following two approaches:

**Joystick:**

* Hero has a reach of 1 meter, and this reach is marked with a semi-opaque circle around the player.
* The ball can be moved by a joystick. When the joystick is moved south, the ball is moved south within the reach circle. There is a direct coupling with the joystick and the position of the ball. I.e. when the joystick is moved max south, the ball is max south within the player reach.
* At each touch update the speed is calculated, and the Box2d ball position and ball speed are updated. NB, the ball will never be moved outside the reach as long as the player push the joystick.
* The ball is thrown by swiping the joystick to make the ball move, and then releasing the joystick. At release, the ball will get a smoothed speed of the joystick.

**Joystick Problem:**

* The throwing accuracy gets bad, because the joystick can not be that big, and a small movement results in quite a large movement of the ball.
* If the user does not release before the end of the joystick maximum end point, the ball will stop, and when the user releases the joystick the speed of the ball will be zero. Bad...

**Touch pad**

* A force is applied to the ball by a sweep on a touchpad.
* The ball is released when the sweep is ended, or when the ball is moved outside the player reach.
* As there is no one to one mapping between the swipe and the ball position, the precision can be improved. A large swipe can result in a small ball movement.

**Touch Pad Problem**

* A touchpad is less intuitive. Users do not seem to know what to do with the touch pad. Some tap the touchpad, and then the ball just falls to the ground.
* As there is no one-to-one mapping, the ball can be moved outside the reach, and then it will just fall to the ground. It's a bit hard to control the ball, especially if the player also moves.

# Answer
Based on your updates, I'd consider the following:

1) use a tap, and have the tactic to be to throw the ball to the location of the tap, using the movement of the character and the placement of the tap (the trajectory of the ball) to try to deke the defender

2) use a joystick for movement and use a swipe (/"fling") to throw, which will make accuracy much harder, but will also offer speed as well as vector, based on the swipe.

If you go that route, though, you need to:

a) provide instruction -- it's not intuitive to an end-user at all, so you need to provide visual queues/tutorials to get the player started (an important and often-overlooked part of modern game design)

b) be forgiving in aim/defense, and allow for people to cancel out of a throw.
> 0 votes

---
Tags: cocos2d-iphone, cocos2d, gui, controllers
---


title: Lighting with VBO

text:
# Question
Title: Lighting with VBO
# INTRO

I'm using a Java JOGL wrapper called processing.org and I have coded some environment on it and I'm quite proud of it even if it has some library stuff that I didn't know anything about it (==LIGHTS).

Now, for some geometry, I've decided to use a VBO. I had to pass in the hard way and recode all lights. But I can't achieve the same result.

With that environment if i use the standard lights i get this result:

This environment wrap the opengl functions and i don't manage to understand the pure OPENGL calls.

i know that the code for standard light in processing.org enviroment is:

```
public void lights() {
    enableLighting();

    // need to make sure colorMode is RGB 255 here
    int colorModeSaved = colorMode;
    colorMode = RGB;

    lightFalloff(1, 0, 0);
    lightSpecular(0, 0, 0);

    ambientLight(colorModeX * 0.5f, colorModeY * 0.5f, colorModeZ * 0.5f);
    directionalLight(colorModeX * 0.5f, colorModeY * 0.5f, colorModeZ * 0.5f, 0, 0, -1);

    colorMode = colorModeSaved;
}

```

# PROBLEM

I want to replicate this light system with pure openGL calls.

Now, i have done some trial with no succes.

ambient and spot lights:

adding smooth and flat:

# QUESTION

Now, i'd like for someone to help me in analysing the first picture and help me in understanding what kind (light or material or whatever) of OPENGL calls i can use to achieve a similar result.

# CODE

this is my code so far:

```
gl.glEnable(GL.GL_LIGHTING);
gl.glEnable(GL.GL_LIGHT0);
gl.glEnable(GL.GL_COLOR_MATERIAL);
gl.glShadeModel(GL.GL_SMOOTH);
gl.glShadeModel(GL.GL_FLAT);

Vec3D l = new Vec3D(0,0,-10);
gl.glColor3f(0.8f,0f,0f);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, new float[] { l.x, l.y, l.z, 0 }, 0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPOT_DIRECTION, new float[] { 1, 1, 1 }, 0);
//gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, new float[] { 1, 1, 1}, 0); // if i comment this line nothing change, why?

gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT,        new float[]{1f,0f,0f}, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPOT_DIRECTION, new float[]{1f,0f,0f}, 0);
//gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, new float[]{1f, 1f, 1f, 1.0f}, 0);  // if i comment this line nothing change, why?

```

# Answer
It seems to me that you're either passing smooth normals or have smooth shading enabled in the 2nd picture compared to the first one, but I can't really tell with just what you have posted.
> 1 votes

# Answer
Check your normals!

In the first image, each face has three vertices with the same normal as the face. These vertices are *not* shared between faces.

In your data, each vertex is shared by multiple faces. As such, it has a normal computed from the average of the normals of all the faces it's connected to.

You need to re-export your data, to get the normals you want. Either that, or re-compute normals per face. Just remember that you can't share vertices between faces.
> 1 votes

---
Tags: jogl, vertex-arrays, lighting
---


# Question
Title: where can i learn to make 3d games in java from scratch?
Just wondering if anyone knows of anything i can read or watch that explains 3D graphics. i do not want to use any game engine like jogl etc. but i am looking for a way i can learn in detail how 3D works. preferably in java. I have used some game engines but would prefer to learn to make for myself.

I would also like to do it without the java3d library.

I have also watched some tutorials on 3d games in java, but would like to learn in more detail.

Thanks.

# Answer
> 2 votes
There are Engines, and then there are Frameworks or Libraries. JOGL is a library, whereas something like Unity would be an engine. Whilst it's great to avoid the engine and try and do it from the ground up, you will NEED a library in order to work with 3D in any modicum of effectiveness.

You would be most suited looking at something like LWJGL, which is designed pretty much for exactly your situation, someone who wants to work in Java, 3D and not use an existing engine. There are myriad tutorials and resources available via simple searching for it.

---
Tags: java
---


# Question
Title: Mapping dynamic buffers in Direct3D11 in Windows Store apps
I'm trying to make instanced geometry in Direct3D11, and the `ID3D11DeviceContext1->Map()` call is failing with the very helpful error of "Invalid Parameter" when I'm attempting to update the instance buffer.

The buffer is declared as a member variable:

`Microsoft::WRL::ComPtr<ID3D11Buffer> m_instanceBuffer;`

Then I create it (which succeeds):

```
D3D11_BUFFER_DESC instanceDesc;
ZeroMemory(&instanceDesc, sizeof(D3D11_BUFFER_DESC));
instanceDesc.Usage = D3D11_USAGE_DYNAMIC;
instanceDesc.ByteWidth = sizeof(InstanceData) * MAX_INSTANCE_COUNT;
instanceDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
instanceDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
instanceDesc.MiscFlags = 0;
instanceDesc.StructureByteStride = 0;

DX::ThrowIfFailed(d3dDevice->CreateBuffer(&instanceDesc, NULL, &m_instanceBuffer));

```

However, when I try to map it:

```
D3D11_MAPPED_SUBRESOURCE inst;
DX::ThrowIfFailed(d3dContext->Map(m_instanceBuffer.Get(), 0, D3D11_MAP_WRITE, 0, &inst));

```

The map call fails with `E_INVALIDARG`. Nothing is `NULL` incorrectly, and this being one of my first D3D apps I'm currently stumped on what to do next to track it down. I'm thinking I must be creating the buffer incorrectly, but I can't see how. Any input would be appreciated.

# Answer
> 4 votes
@Nathan's debug layer tip pointed this out fast - so, turn on the debug layer when debugging D3D code.

The problem was that the `MapType` needed to be `D3D11_MAP_WRITE_DISCARD` (or `D3D11_MAP_WRITE_NO_OVERWRITE`, but that wasn't appropriate for me) because the buffer was created as `BUFFER_DYNAMIC`.

I'm sure that was documented somewhere, but I completely missed it.

---
Tags: c++, directx11, windows-8
---


# Question
Title: Sprite Animation Software That Works With Cocos2D
So the title basically says it all. I'm looking for software that would help me to create sprite animations that I could use with cocos2d by allowing me to pose a a sprite and the software create key-frames between the sprites( basic tweening ).

Any ideas?

# Answer
As I understand you need the Gamedev Animation Studio. I use it to animate sprites. This tool interpolate the animation between keyframes by various characteristics of sprite.
> 2 votes

# Answer
Have you checked out Spriter? It's currently in alpha, but their forums have plugins available for cocos2d.
> 0 votes

# Answer
Pivot is one of the sprite animation software. you can always use photoshop
> -1 votes

---
Tags: sprites, cocos2d
---


# Question
Title: Data structures for a 2D multi-layered and multi-region map?
I am working on a 2D world editor and a world format subsequently. If I were to handle the game "world" being created just as a layered set of structures, either in top or side views, it would be considerably simple to do most things.

But, since this editor is meant for 3rd parties, I have no clue how big worlds one will want to make and I need to keep in mind that eventually it will become simply too much to check, handling and comparing stuff that are happening completely away from the player position.

I know the solution for this is to subdivide my world into sub regions and stream them on the fly, loading and unloading resources and other data. This way I know a virtually infinite game area is achievable. But, while I know theoretically what to do, I really have a few questions I'd hoped to get answered for some hints about the topic.

1. The logic way to handle the regions is some kind of grid, would you pick evenly distributed blocks with equal sizes or would you let the user subdivide areas by taste with irregular sized rectangles?
2. In case of even grids, would you use some kind of block/chunk neighbouring system to check when the player transposes the limit or just put all those in a simple array?
3. Being a region a different data structure than its owner "game world", when streaming a region, would you deliver the objects to the parent structures and track them for unloading later, or retain the objects in each region for a more "hard-limit" approach?
4. Introducing the subdivision approach to the project, and already having a multi layered scene graph structure on place, how would i make it support the new concept? Would you have the parent node have the layers as children, and replicate in each layer node, a node per region? Or the opposite, parent node owns all the regions possible, and each region has multiple layers as children? Or would you just put the region logic outside the graph completely(compatible with the first suggestion in Q.3)
5. When I say virtually infinite worlds, I mean it of course under the contraints of the variable sizes and so on. Using float positions, a HUGE world can already be made. Do you think its sane to think beyond that? Because I think its ok to stick to this limit since it will never be reached so easily..
6. As for when to stream a region, I'm implementing it as a collection of watcher cameras, which the streaming system works with to know what to load/unload. The problem here is, i will be needing some kind of warps/teleports built in for my game, and there is a chance i will be teleporting a player to a unloaded region far away. How would you approach something like this? Is it sane to load any region to memory which can be teleported to by a warp within a radius from the player?

Sorry for the huge question, any answers are helpful!

# Answer
> 4 votes
First off - don't overengineer. Just build what you feel is necessary.

Large parts of your question seem to orbit around "how to handle huge worlds". From a quick search, I found several questions on gamedev.sx that may help you:

I'll briefly go through your points:

> The logic way to handle the regions is some kind of grid, would you pick evenly distributed blocks with equal sizes or would you let the user subdivide areas by taste with irregular sized rectangles?

KISS. If you have no reason not to do so, keep things simple - an even grid is easy to address.

> In case of even grids, would you use some kind of block/chunk neighbouring system to check when the player transposes the limit or just put all those in a simple array?

Simple array. It should be trivial to know which four "tiles" of the world are closest to the player.

> Being a region a different data structure than its owner "game world", when streaming a region, would you deliver the objects to the parent structures and track them for unloading later, or retain the objects in each region for a more "hard-limit" approach?

Assuming everything isn't unique in the world, I'd keep a cache of resources and would free them on a LRU basis after some predetermined limit was exceeded. It's likely the player will walk in circles and will see the same resources again soon, so no point in unloading stuff right after it's no longer in active use.

> Introducing the subdivision approach to the project, and already having a multi layered scene graph structure on place, how would i make it support the new concept? Would you have the parent node have the layers as children, and replicate in each layer node, a node per region? Or the opposite, parent node owns all the regions possible, and each region has multiple layers as children? Or would you just put the region logic outside the graph completely(compatible with the first suggestion in Q.3)

I'd keep each "subregion" as it's own "world".

> When I say virtually infinite worlds, I mean it of course under the contraints of the variable sizes and so on. Using float positions, a HUGE world can already be made. Do you think its sane to think beyond that? Because I think its ok to stick to this limit since it will never be reached so easily..

Actually, you can't make a huge world with floats. You'll hit float's limits fairly soon (same goes for doubles).

Since floats are most accurate around the origin, you need to have a "moving origin".. basically I'd have two coordinate systems: one "local", for a "tile", where everything are simple floats, and one "global", integer coordinates which are offsets of tiles. Then, let's say if one tile is (-1000,1000), the integer coordinates would be in steps of 2000.

> As for when to stream a region, I'm implementing it as a collection of watcher cameras, which the streaming system works with to know what to load/unload. The problem here is, i will be needing some kind of warps/teleports built in for my game, and there is a chance i will be teleporting a player to a unloaded region far away. How would you approach something like this? Is it sane to load any region to memory which can be teleported to by a warp within a radius from the player?

Fade out, fade in. Teleportation is a special event. Add some cool special effects to hide the fact you're preloading.

Or alternatively do special cases through scripting. When teleport object is loaded, it's loader script tells the resource manager that tile X is probably needed soon.

---
Tags: data-structure, world-editor, streaming
---


# Question
Title: Threads slowing down application and not working properly
I'm making a software renderer which does per-polygon rasterization using a floating point digital differential analyzer algorithm. My idea was to create two threads for rasterization and have them work like so: one thread draws each even scanline in a polygon and the other thread draws each odd scanline, and they both start working at the same time, but the main application waits for both of them to finish and then pauses them before continuing with other computations.

As this is the first time I'm making a threaded application, I'm not sure if the following method for thread synchronization is correct:

First of all, I use two global variables to control the two threads, if a global variable is set to 1, that means the thread can start working, otherwise it must not work. This is checked by the thread running an infinite loop and if it detects that the global variable has changed its value, it does its job and then sets the variable back to 0 again. The main program also uses an empty while to check when both variables become 0 after setting them to 1.

Second, each thread is assigned a global structure which contains information about the triangle that is about to be rasterized. The structures are filled in by the main program before setting the global variables to 1.

My dilemma is that, while this process works under some conditions, it slows down the program considerably, and also it fails to run properly when compiled for Release in Visual Studio, or when compiled with any sort of -O optimization with gcc (i.e. nothing on screen, even SEGFAULTs). The program isn't much faster by default without threads, which you can see for yourself by commenting out the #define THREADS directive, but if I apply optimizations, it becomes much faster (especially with gcc -Ofast -march=native).

N.B. It might not compile with gcc because of fscanf\_s calls, but you can replace those with the usual fscanf, if you wish to use gcc.

Because there is a lot of code, too much for here or pastebin, I created a git repository where you can view it.

My questions are:

1. Why does adding these two threads slow down my application?
2. Why doesn't it work when compiling for Release or with optimizations?
3. Can I speed up the application with threads?
4. If so, how?

Thanks in advance.

# Answer
> 4 votes
An infinite loop that makes no attempt to sleep or yield is going to relentlessly eat up your CPU. In other words:

```
while(t1a || t2a);

```

When both t1a and t2a are false, this will do a lot of work to achieve nothing. It will use as much CPU time as it can to check these two variables over and over again. Instead, you should do something more like:

```
while ( active ) {
    if ( ! t1a && ! t2a ) {
        // do work here
    }
    // sleep for a small amount of time
}

```

As for your other problems, I'm not really sure, but I bet if you make this change you'll be in a much better position to understand what's going wrong.

Also, I didn't look through your code a whole lot, but it sounds like you're also missing some locking mechanisms. Whenever two threads need to access to the same memory, they should use a locking mechanism such as a mutex to ensure that they do not do so at the same time.

# Answer
> 1 votes
I'll try to answer your questions but i didn't go extensively through your code so it's possible i may have missed something.

1) Adding threads has a cost. You must be sure that the cost of adding the threads is a good investment. In your case, I think you may be getting sucked into too much busy waiting from the main thread (and thus, getting cycles away from the threads) and maybe a bad parallelization scheme (tasks too small).

2) I'm really not sure abut this but based in my experience, when threaded things fail after you add optimizations is because there's some base you are not covering, like a race condition, some unitialized variable or any kind of code that is shaky and changes because of the optimizations. In your case, i think it's possible that the code "while(t1a || t2a);" is simply ommited causing all kinds of crazy things.

3) Without really understanding your code, my gut feeling is YES. (see below for some extra comments on this), but obviously you will have to do the math and the actual code to get the real answer.

4) Some ideas here:

* Busy waiting is generally BAD. Run away from it unless you have a really good reason.
* Try to split the work in such a way that the comunication between threads is minimal. If you can do n/2 sub-tasks in each thread, try to "submit" the work just once with the complete list of sub-tasks, instead of asking each thread once per each sub-task. The mechanism to talk between threads takes time (which is the overhead you have to overcome to make threads useful) and each time a thread has to wait for something you are simply wasting precious cpu cycles.
* This is not really for performance per se, simply good practice. Get in the habit of using the tools you should use to signal threads. Use condition variables if you need to signal a thread "something" happened (like the event of having work to do) and use mutexes where they should be used. These objects are heavier than simply setting a variable, but ENSURE CORRECTNESS which is no small feat. On the good side, the condition variables should allow you to use the machine's resources more effectively because you will only do work when it is needed, as opposed to hog resources and possibly slowing other processes :P.
* Finally, measure how much time your code is taking and do some excercises with higher amounts of data. It's possible that your code is working fine and you do have a noticeable improvement when the amount of data processed is bigger.

Hope this helps

# Answer
> 0 votes
Like others have mentioned, using threads adds cost. This is often more insidious than you'd expect, as you have to know a lot about the underlaying hardware to know what's actually going on.

This is especially true when several threads access a lot of the same data. Threads work the best when they have little or no overlapping data.

Cache lines make the "overlapping" harder to see - I'll trivialize, but let's say you have a cache that always reads 1kB of data. If your program accesses one byte, and it's not in the cache, the CPU actually has to fetch 1kB of data to the cache for you to get the one byte.

Now, let's say that you have two threads that are plotting pixels in, what looks to you, in different places in memory. Let's, for the sake of this example, say the pixels take one byte each.

If the pixels hit the same cache line, you're invalidating the cache all the time, and what in a single-threaded application took 1kB of data transfer per 1k of pixels plotted may end up taking 1kB per pixel plotted - ending up with 1MB of data transferred!

---
Tags: multithreading
---


title: Frame timing for GLFW versus GLUT

text:
# Question
Title: Frame timing for GLFW versus GLUT
I need a library which ensures me that the timing between frames are more constant as possible during an experiment of visual psychophics.

This is usually done synchronizing the refresh rate of the screen with the main loop.

For example if my monitor runs at 60Hz I would like to specify that frequency to my framework.

For example if my gameloop is the following

void gameloop() {

// do some computation

printDeltaT(); Flip buffers }

I would like to have printed a constant time interval. Is it possible with GLFW?

# Answer
Well, the amount of time that passes between frames is highly dependent on the hardware rendering your scene. If the machine just isn't strong enough, there's no way to enforce a fixed frame-rate. However, GLFW DOES allow for very precise time MEASUREMENT (and glut does not), and therefore you can use it to make sure your frame rate is not too FAST. Too slow is another concern entirely.

So on one machine of reasonable speed, **yes**.

Here's how GLFW does it under the covers, if you want to get straight to the timer and skip GLFW entirely.

And, if you're strictly talking about syncing the buffer swap to the monitor refresh rate, you can use `glfwSwapInterval(1);` to block buffer swapping until the monitor has done at least one vertical retrace since the last buffer swap. This basically caps your framerate at your monitor's refresh rate.
> 5 votes

# Answer
Unfortunately, desktop hardware is not designed for "real time" applications, where "real time" is defined as "thing X has to happen exactly at N".

As computers get faster, we're edging closer to that goal, but at the same time the devices try to do more and more things at the same time.

In other words - while your graphics hardware may be capable of rendering whatever you're doing at smooth 60hz, nothing stops the operating system from deciding, all of a sudden, that you have to start downloading patches to the instant messenger you've never even launched, which in turn requires the system to spin up the hard drive that was put to sleep some time ago, which again may cause some interrupt request noise and ends up causing you to miss a frame at some border case..

So what I'm trying to say is, this has little to do with GLUT or GLFW (although you should never use GLUT for anything serious), and the problem is of a bigger scale. Maybe if you build a bare-bones linux distribution that will never, ever do anything behind the scenes..

Or you can just live with the fact that you may experience some rare frame jitters.
> 3 votes

---
Tags: opengl, glut, timing, glfw
---


# Question
Title: Grouping surfaces in pygame to get an object with two movement points
I would like to create a simple tank using pygame. One would drive the tank by controlling he velocities of two caterpillar tracks. They should be the two single movement points of the vehicle.

I'm looking for directions in which pygame methods and objects to check or tutorials regarding the topic.

# Answer
Regarding vectors: this guy 'Phyces' made a few tutorials and he included a really useful 2D vector class. vec2d class \- you could use it to define your position and velocity of each element, and use its rotate() method. Bear in mind that when you blit the image you'll need to convert the position back to a tuple using the inttup() method. If you do use it, it can't hurt to do Phyces video tutorials, they're dead short and really clear - they helped me loads. He also shows you how to do rotated images.

Hope that Helps.

Also... with the two tracks: your velocity at each track is *v = w/r* (where w is the rotational velocity, r is the distance to the centre of the body) and the rotational velocity of the whole body will be *w1 + w2 = wT.* Bear in mind that if they are both facing forward, w1 will be opposite to w2 and if they are equal magnitude *wT = 0*. So:

* Calculate the rotational velocity at each track
* Add them together
* Increment your body angle (rotation) by the total rotational velocity
* Reset you track velocities so that they stay tangential

Something like this:

```
rotational_velocity = (v1.length/r - v2.length/r)*(180/pi) //to get into degrees from radians,

```

also this will only work if the tracks can't go backwards, otherwise you'll need to use a sine function.

```
current_angle = current_angle + rotational_velocity // this is the tanks angle

v1.rotate(current_angle) // make it all tangential again
v2.rotate(current_angle)

```

When you press the button to make a track go you may do something like this:

```
v1.length = 10
v1.angle = current_angle // assuming you use the vec2d class

```

Again, I hope that helps.
> 3 votes

# Answer
A Surface is just a graphic - it doesn't have a position on the screen or in the world and so the concept of grouping them doesn't really make any sense. However, Pygame does have Sprites which are basically in-game objects. You need to set their `image` member to the surface you want and their `rect` member to the shape of the surface. The internet says that this is a good tutorial for Pygame sprites, so it's worth a look.

However, Pygame uses a software renderer which isn't well suited to performing rotations. To display an image rotated you are expected to create a new rotated copy of the original surface and display that instead. (Via pygame.transform.) This is relatively slow and also tricky to get right (as the dimensions of the returned surfaces will change as you rotate). The speed issue can be solved by performing all your rotations in advance and saving the results. The dimensions issue is a bit trickier but basically involves you positioning sprites/surfaces based on their mid-point rather than their 0,0 corner.

Personally I would probably recommend a different library if rotations form a large part of your game. My preference is pyglet but I'm sure there are others.

As for the actual movement mechanic, if you're happy to either move in a straight line or to rotate around one point, then it's fairly simple. Normally you use 2D vectors for your object positions and movement, which can be translated for linear movement and rotated for turning, but pygame won't help you here. (I've always coded up my own vector classes in Python.) A real tank would probably allow for more variety in the movement by having the treads turn at different speeds, and resolving that correctly is beyond my knowledge (although I expect it could be done quite easily with a physics engine, eg. pymunk).
> 2 votes

---
Tags: 2d, rotation, pygame
---