# Question
Title: Unity - Avoid using Find method by caching UnityObjects - Code review
I'm trying to avoid using `GameObject.Find` during runtime to find particular GameObject components when wanting to instantiate them.

I have created a cache for the gameobjects from which I can either return the original instance or create a new instance.

Components which should only have one instance are returned by `GetOriginal<UnityObject>`

A new instance of an Original component is returned using `GetInstanceOf<UnityObject>`

```
public class GameObjectTools : MonoBehaviour
{
    static List<Object> gameObjectCache = new List<Object>();

    // This is called BEFORE Start() when the script is being loaded
    void Awake()
    {
        // Cache any GameObject classes that are required by other classes here
        gameObjectCache.Add(GameObject.Find("Timer").GetComponent<Timer>());
        gameObjectCache.Add(GameObject.Find("Object Rotator").GetComponent<ObjectRotator>());
        gameObjectCache.Add(GameObject.Find("Object Translator").GetComponent<ObjectTranslator>());
    }

    public static T GetOriginal<T>() where T : Object
    {
        int index = -1;
        int numObjects = gameObjectCache.Count;

        for (int i = 0; i < numObjects; ++i)
        {
            if (gameObjectCache[i].GetType() == typeof(T))
            {
                index = i;
                break;
            }
        }

        return index == -1 ? null : gameObjectCache[index] as T;
    }

    public static T GetInstanceOf<T>() where T : Object
    {
        var o = GetOriginal<T>();
        return o == null ? null : GameObject.Instantiate(o) as T;
    }
}

```

I'm slightly concerned that I am not approaching this problem in the right manner and was hoping for some feedback regarding my methodology.

Is there a more efficient or straightforward approach to achieve what I am trying to achieve here?

**EDIT**

```
public class Ball : MonoBehaviour
{
    int lifeSpan = 1000;

    void Update()
    {
        if (Timer.CurrentTime > lifeSpan)
            GameObject.Destroy(gameObject);
    }
}

public class GameObjectTools : MonoBehaviour
{
    public static Ball Ball;

    void Awake()
    {

        Ball = GameObject.Find("Ball").GetComponent<Ball>();
    }
}

```

If I call

```
var ball = GameObject.Instantiate(GameObjectTools.Ball) as GameObject;

```

anytime after the lifespan of the ball has expired then I will get a null reference error.

How then can I ensure that this doesn't happen while still being able to create new instances from a static cache?

# Answer
As long as you're hard coding things, you may as well put the types in there too.

```
public class GameObjectTools : MonoBehaviour
{
    static Timer timer;
    static ObjectRotator objectRotator;
    static ObjectTranslator objectTranslator;

    // This is called BEFORE Start() when the script is being loaded
    void Awake()
    {
        timer = GameObject.Find("Timer").GetComponent<Timer>();
        objectRotator = GameObject.Find("Object Rotator").GetComponent<ObjectRotator>();
        objectTranslator =
                  GameObject.Find("Object Translator").GetComponent<ObjectTranslator>();
    }

```

Then access them with:

```
GameObjectTools.timer.DoStuff();

```

This avoids the expensive reflection call `typeOf`. Which your code does multiple times per look up.

Additionally, make sure you're actually solving a problem. Your trying to avoid using `GameObject.Find`, but have you actually tested this to see if it's a significant problem with your game? Remember what they say about premature optimization.

Use some profiling to ensure that you're not wasting your efforts on something that's not going to improve performance much at all.
> 3 votes

# Answer
Just have your "single instance" type scripts take care of themselves:

```
Timer : MonoBehavior {
    static Timer instance;

    void Awake() {
        instance = FindObjectOfType(typeof(Timer))();
    }

    void i_TimeSomething() {
        //Do work
    }

    void static TimeSomething() {
        instance.i_TimeSomething();
    }
}

```

Now you can access them from anywhere with something like:

```
Timer.TimeSomething();

```

or

```
Timer.instance.OtherMethod();

```

---

I think, but I haven't tested it, you could create a base "single instance" class where you can have your other classes extend it, maybe something like:

```
SingleInstance : MonoBehavior {
    static SingleInstance instance;

    void Awake() {
        //not so sure about this
        instance = FindObjectOfType(this.GetType())();
    }
}

```

Then have your classes extend this:

```
Timer : SingleInstance {

    void i_TimeSomething() {
        //Do work
    }

    void static TimeSomething() {
        instance.i_TimeSomething();
    }
}

```

And access them the same way I described above.
> 1 votes

---
Tags: unity, architecture, methodology
---


# Question
Title: How can I support the creation and rendering of both interior and exterior environments?
Say I already have a renderer that can support outdoor terrain and environment rendering. How would I go about adding support for *interior* environments (for example, like World of Warcraft's dungeons) to my game?

I'm interested both in how I should fit the interiors into my content creation process (for example, I thought about leaving holes in the terrain mesh into which I can "paste" the interior dungeon mesh at runtime) and how to render them (it seems like I'd want a different rendering flow other than a blended texture rendering phase that terrain uses).

# Answer
I would recommend for seamless transitions you would need to create "portals" What I mean by this is you would need 3 parts

1)Exterior

2)Interior

3)Transition Zone

For Exteriors you would have your Global Lighting to taste as you like it. You would Only load Transition Zones in stages at this point as the player gets close or within visible range.

For Interiors you Would unload Exteriors and load the Interior components for that dungeon. Lighting would also be to taste here with Interior Lighting.

For Transition Zones you would blend across the Lighting schemes. It is important that the Transition Zone Obscures the Interior from the outside and the Exterior from the inside.

There are many ways to do this and you may need to set a LOD system up for interiors just like exteriors to ensure smoother transitions without hangtime or loading times.

This would effectively allow you to cut holes in the terrain.
> 1 votes

# Answer
As already suggested by @Philipp creating, storing and rendering are often handled very differently when in comes to indoor vs. outdoor. This is because the requirements and challenges are typically very differrent. Example:

Outdoor:

* huge viewing distance
* potentially unlimited polycount
* typically modelled using heightmaps or voxels
* typically rendered using level-of-detail polygonization

Indoor:

* moderate viewing distance
* natural line-of-sight blockers
* potentially lots of detail on characters and objects
* complex collision shapes
* typically rendered full detail skipping occluded geometry

So you see indoor and outdoor typically don't have much in common. That's why there are dungeon portals and explicit loading screens in games like World of Warcraft when switching from on to the other.

To get a better answer please explain the workings and shortcomings of your current renderer. You can also learn a lot about indoor rendering from the good old Quake toolchain.
> 0 votes

---
Tags: terrain-rendering
---


title: Unity Gui from text file templates

text:
# Question
Title: Unity Gui from text file templates
I've been banging my head against a wall this past while over how I might create menu's and menu components in unity from text file. I would normally just build my own extended panel/label classes etc in c# and then use the properties loaded from file on instances of those extended classes. I have a properties loader but I cant seem to get my head around making a gui class that's dynamic from reading unitys documentation. Has anybody ever tried this?

Here's an example of a menu definition file.

```
    <GUI_Menu: mainMenu >
    <Atributes>
        <> Type : Menu
        <> Position_X : 0
        <> Position_Y : 0
        <> Height : Vanilla_Property_Screen_Height
        <> Width : Vanilla_Property_Screen_Width
    </Atributes>
    <GUI_Panel: menu >
        <GUI_Button: play >
            <Atributes>
            <> Position_X : 50
            <> Position_Y : 50
            <> Type : Button
            <> Height : 50
            <> Width : 100
                <Description>
                    <> Key : desc_Play
                    <> Description_Address : Main\\Text\\Menu\\desc_Menu.xml
                </Description>
            </Atributes>
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: options >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: mods >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: texturePacks >
            //button action/button data/description
        </GUI_Button>
    </GUI_Panel>
</GUI_Menu>

<GUI_Menu: play >
    <GUI_Panel: load-New >
        <GUI_Button: loadSave >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: newGame >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: multiplayer >
            //button action/button data/description
        </GUI_Button>
        <GUI_Button: voxelEditor >
            //button action/button data/description
        </GUI_Button>
    </GUI_Panel>
</GUI_Menu>

```

EDIT: Note that it is important that the menus are loaded from a definition file that is easy to read and write by a human being as custom menu's and GUI's/components will be supported through modding.

# Answer
Firstly, you'll want to use some sort of serialization. I've found that the XmlSerializer class in the .NET framework is an excellent tool for this, that allows for relatively simple and powerful control over precisely what gets serialized, and how. Plus, XML is reasonably easy to debug, since the data is saved in plain english (assuming you set it up that way).

Unity's GUI system, as it is now, does not function on a basis of "components" or "objects." At least, not on the surface (any of the parts of the engine that users have access to). However, with the 4.6 update that is supposedly coming sometime this Summer, the in-game GUI will be changed pretty dramatically (more info on that here), so don't get too used to the way Unity's in-game GUI works, right now.

Basically, the entire thing functions on a select few callback methods/functions (depending on whether you're using C# or UnityScript/JS) that are executed by the engine, at certain points throughout the game's lifetime. For GUIs that are in-game, the vast majority of these calls will be to the OnGUI method/function, which is actually a shared nomenclature over much of Unity's systems (including EditorWindow, which is an editor class, which means it isn't run in-game).

Within the proper callback function, you can make calls to static methods in the GUI class, and the GUILayout class. There are a number of minor differences between these two classes, but the biggest difference is that the GUILayout class automatically manages the positioning of GUI elements, where with GUI, you have to define the Rects (rectangular area objects) in which the GUI elements are defined.

If you want to save parts of GUI elements, what you would want to do is to create a class that will represent how your GUI element will look and function by holding the data needed to make the method calls that would otherwise "manually" create that object, if they were written directly in the OnGUI method.

So, for example:

```
public class GUIButton
{
    string text;
    Rect position;
    delegate someMethod;
}

```

The delegate could be replaced, depending on your implementation, by making the class into an interface, but then the data would be more complex to integrate, and I can't even begin to fathom how one would serialize an anonymous class. Delegates are easily changed at runtime, as well, so you could easily change the functionality even within a single button object, without re-creating it, and removing the old one.

Beyond that, again, you'd need to handle serialization/deserialization, somehow, which is a bit of a task in itself. I'll link a few places you might want to go for more info here:

Unify Wiki Article- Saving and Loading Data: XmlSerializer

GUI Class Tutorial

GUILayout Class Tutorial

**EDIT** In the newest version of Unity (4.6), the GUI has been overhauled. While the legacy system is still in place, the new system is component-driven, and provides a significant boost to performance for complex GUIs, and is (in my opinion, at least) FAR easier to use. They have reportedly optimized this system to vastly reduce draw calls, among other things. You can find out more about the new system here:

Unity - What's New
> 1 votes

---
Tags: c#, unity, gui
---


title: XNA 3D cube rotation problem

text:
# Question
Title: XNA 3D cube rotation problem
I am new to game programming and still trying to clear up my basics. I am stuck with a problem and unable to resolve on my own knowledge. I am trying to rotate a 3d cube in MonoGame (Similar to XNA) Windows Phone 8 application. The rotation works fine but it has a problem. Following is the scenario

* Y axis (up/down) rotation works fine. I am able to rotate it as many times as possible and everything works fine.
* But let's say that the cube was in its default position. I rotate
my cube 180 degree on y-axis. Now when i rotate my cube on X axis. It rotates in opposite direction. Forexample if i try to move it towards positive x-axis it moves in negative x-axis.
* If i again move the cube 180 degree in y-axis, the x-axis
rotations works fine again.

public void Update(GameTime gameTime) { \_userInputHandler.HandleTouchEvents();

```
Matrix unrotatedView = Matrix.CreateLookAt(
    cameraPosition, ModelPosition, Vector3.Up);

viewMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(Angle.Y)) *     // right/left rotation
              Matrix.CreateRotationX(MathHelper.ToRadians(Angle.X)) *   // up/down rotation
              unrotatedView;

CameraCurPos = Cube.MatrixVectorMultiply(cameraPosition, viewMatrix);

projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 100.0f);

```

}

Here is the Input handle function

```
public void HandleTouchEvents()
        {
            TouchCollection tc = TouchPanel.GetState();

            if (tc.Count > 0)
            {
                TouchLocation current = tc[0];
                TouchLocation prev;
                if (current.TryGetPreviousLocation(out prev))
                {
                    Vector3 newAngle = _gameEngine.Angle;
                    //newAngle.X += MathHelper.ToRadians((current.Position.X - prev.Position.X) * TURN_SPEED); // pitch
                    //newAngle.Y += MathHelper.ToRadians((current.Position.Y - prev.Position.Y) * TURN_SPEED); // yaw
                    newAngle.X += MathHelper.ToRadians((current.Position.Y - prev.Position.Y) * TURN_SPEED); // pitch
                    newAngle.Y += MathHelper.ToRadians((current.Position.X - prev.Position.X) * TURN_SPEED); // yaw

                    _gameEngine.Angle = newAngle;

                }
}
}

```

I know the problem is simple but i am unable to resolve it. Thanks in advance.

# Answer
Being able to rotate your cube regardless of the axis has to do with the matrix manipulations you apply to the cube.

The best way I have found to keep track of your transformations is to keep a reference location that you create when the object is instantiated. Then you apply your rotations relative to that reference point. In XNA an easy way to do this is using the MathHelper.Clamp() function to keep rotations between 0-2pi.

That way, regardless of how many rotations you perform, you will end up at the correct spot every time. So let's say you are spinning to the left, instead of applying a transformation each frame, you apply refPosition\*1deg, then refPosition\*2deg etc.

If you're new to 3D transformations there is a ton of reference material to read up on, there is a good article here, and some googling will get you a ton of information.

I've also done similar projects, if you need me to pull up some code I can dig into my past projects
> 1 votes

---
Tags: xna, game-design, rotation, matrix, monogame
---


# Question
Title: Should Starting a Quick Game via Google Game Services be Iterated?
I have been following this tutorial for Google Play Game Services. I am a little unclear as to if the room matching algorithm should be looped or not. Can I just initialize this process once and let it time out? Or by iterating through it is it somehow rechecking it? If anyone had the approximate timeout that would be great as well.

The problem stems from the fact that even when both phones are signing into the Game Services (at virtually the same time, my friend and I logged in), the room is not registering multiple people. One time my friend's phone even entered the game map, showing that he somehow was able to progress from the room initialization process.

Relevant screen update methods which I am starting this matchmaking process:

```
@Override
public void update(float deltaTime)
{
    game.options.updateTiles();

    if(!isInitiated)
    {
        startQuickGame();
    }
}

private void startQuickGame()
{
    // auto-match criteria to invite one random automatch opponent.
    // You can also specify more opponents (up to 3).
    if(game.mGoogleClient.isConnected() && !isInitiated)
    {
        Bundle am = RoomConfig.createAutoMatchCriteria(1, 3, 0);

        // build the room config:
        RoomConfig.Builder roomConfigBuilder = RoomConfig.builder(Network.getInstance());
        roomConfigBuilder.setMessageReceivedListener(Network.getInstance());
        roomConfigBuilder.setRoomStatusUpdateListener(Network.getInstance());
        roomConfigBuilder.setAutoMatchCriteria(am);
        RoomConfig roomConfig = roomConfigBuilder.build();

        // create room:
        Games.RealTimeMultiplayer.create(game.mGoogleClient, roomConfig);

        // go to game screen
        this.mRoom = Network.getInstance().getRoom();
        if(this.mRoom != null && this.mRoom.getParticipants().size() >= 2)
        {
        game.setScreen(new MultiGameScreen(game, this.mRoom));
        isInitiated = true;
        }
    }
    else
    {
        game.mGoogleClient.connect();
    }
}

```

# Answer
I'm just guessing here going by the documentation, but it seems like you should only create the room once, set isInitiated to true, then wait for participants using the connecting players code found here: https://developers.google.com/games/services/android/realtimeMultiplayer#connecting\_players

By overriding the `RoomStatusUpdateListener.onPeersConnected` method, you can keep a count of the number of players and only move to the game screen when you've reached the minimum required players.

The `startQuickGame` method currently appears to be creating a `Room` each update. I believe you want to create the room once, then keep a reference to this room and wait for players.

From this question on stackoverflow, it appears the `Room` will not time out by default.
> 1 votes

---
Tags: android, google-play-services
---


title: Lighting computation viewing direction

text:
# Question
Title: Lighting computation viewing direction
This is something that's really cooking my noodle. When I'm computing the light response for a material in my fragment shader, I'm using the standard 3 normalized vectors, in eye space: fragment normal, light direction, eye direction.

However, because the 3 vectors are in eye space, I've seen the eye direction represented as the following, because the camera is looking down -z:

```
vec3(0, 0, 1)
```

While the light direction is:

```
normalized(light_eyespace_position - fragment_eyespace_position)
```

This makes sense at first glance, but the more I think about it, I'm trying to figure out why the eye direction isn't computed similarly to the lighting direction:

```
normalized(-fragment_eyespace_position)
```

In other words, why does the vector from the light to the surface dependent on fragment position, but the vector from the camera to the surface is independent on the fragment?

The only thing I can work out is that using vec3(0, 0, 1) is correct only for ortho cameras, while normalized(-fragment\_eyespace\_position) is correct for perspective cameras. Is this correct? Can anyone shed some light on this?

# Answer
> why does the vector from the light to the surface dependent on fragment position, but the vector from the camera to the surface is independent on the fragment?

The point is, because of the lighting equation. What you need is the vector from the light to the vertex, in other words the light direction relative to the vertex position. This is needed in order to take the dot product between the normal vector and the L vector. This is called the diffuse term and is calculated

> float diffuseTerm = (N.L); Where N is the normal vector. L is the light direction. In case of directional light (infinitly far) L will be constant for all the vertices. If the light is not L will be calculated relative to each vertex.

Regarding the camera vector you are in the eye space, which means the camera position is (0,0,0) you can actually think of this

> normalized(-fragment\_eyespace\_position)

As this

> normalized( (0,0,0)-fragment\_eyespace\_position)

Because in eye space the camera is actually (0,0,0)
> 3 votes

---
Tags: shaders, camera, lighting
---


# Question
Title: Can a behavior tree represent the same logic as a finite state machine?
So I was just learning about Behaviour trees and I thought they're really cool. So I decided to use them in my games. But what I don't quite understand is:

Short: Can everything done in an FSM, be done in a BT?

Long: So one of the games I'm involved in has some RE (classical resident evil) mechanics. In RE, interaction with triggers could change. For ex see this video, take 2:40 as an example (it's the tiger statue puzzle from RE1) - basically, if you interact with it the first time, it says "It's a tiger statue, it appears to have holes in its eyes". If then you use the Blue gem on it, it rotates to the left (or right) revealing an item behind it, if you pickup the item you go back to the initial state. Use the red gem and it would rotate the other direction revealing another item, pickup it and you're back again. This is obviously an FSM. Here's how it looks:

So how can this tiger statue puzzle FSM be done in a BT? (if at all) - Is this more suited for an FSM? or a BT would be nice to use here as well?

Thanks for all tips/any help.

EDIT: Gamedev.net crosslink.

# Answer
> 3 votes
For reference: I found a thread where somebody wants to adapt FSM behaviour into an BT as well, that contains some hints and a simple example in the first posts of how to do it.

But I don't think you want to use it for things like this statue. Like you see in your given example and the graph you draw to show it: It is extremly simple to design interactions and puzzles in those graphs. You directly map the possible actions of the player to the outcome and you dont have any unnecessary information.

Behaviour trees do not simplify this design or implementation process. Don't get me wrong, BTs can be great to design and quickly prototype complex AI behaviour, but this is no Artificial Intelligence, it is just a game object reacting to simple distinct player actions.

Stay with your FSM for tasks like that!

---
Tags: ai, game-mechanics, behavior, fsm
---


# Question
Title: Does every Windows Phone 8 device have one of a fixed set of resolutions?
Does every Windows Phone have one of the following 4 resolutions? 800x480, 1280x768, 1280x720, 1920x1080 pixels

Or is it possible that some devices only have a resolution of 1280x719 or 1279x720 pixel?

I use this code to determine the resolution of the device:

```
Resolution = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

```

But if I use the 720p and 1080p emulators, then I have the following results:

```
Resolution = Width:1279 Height:720

```

Why is the resolution width 1279 pixel and not 1280 pixel wide?

I get the same results with this code:

```
width = GraphicsDevice.PresentationParameters.BackBufferWidth;
height = GraphicsDevice.PresentationParameters.BackBufferHeight;

```

Is there a difference between GraphicsDevice.PresentationParameters.BackBufferWidth and GraphicsDevice.Viewport.Width? Which one should I use to determine the resolution of a Windows Phone device?

# Answer
> 1 votes
A good place to go for these sorts of questions is the technical requirements specification of your platform, if it exists. Fortunately for Windows Phone 8, it does.

From the section on multi-resolution applications, you can see that 480x800, 768x1280, 720x1280 and 1080x1920 resolutions are the only ones supported (for WP8, update 3, as of this writing). That means you should support all of them, although an individual phone may only support a subset of them.

Thus, no Windows Phone 8 device should have a resolution of 1280x719 or 1279x720. Your code to detect the resolution is actually detecting the viewport width and height, which may in theory be different than the actual resolution for various reasons. The documented method to test the resolution is via `App.Current.Host.Content.ScaleFactor`, as in this code from the MSDN:

```
public enum Resolutions { WVGA, WXGA, HD };

public static class ResolutionHelper
{
   private static bool IsWvga
   {
      get
      {
         return App.Current.Host.Content.ScaleFactor == 100;
      }
   }

   private static bool IsWxga
   {
      get
      {
         return App.Current.Host.Content.ScaleFactor == 160;
      }
   }

   private static bool IsHD
   {
      get
      {
         return App.Current.Host.Content.ScaleFactor == 150;
      }
   }

   public static Resolutions CurrentResolution
   {
      get
      {
         if (IsWvga) return Resolutions.WVGA;
         else if (IsWxga) return Resolutions.WXGA;
         else if (IsHD) return Resolutions.HD;
         else throw new InvalidOperationException("Unknown resolution");
      }
   }
}

```

That said, you *may* want to continue detecting the viewport size instead of the actual resolution, depending on your actual subsequent usage; one reason the viewport can be smaller is if the OS reserves some portion of the screen for any reason, and you may want your code to react accordingly to that. Or you may not. Thus, it's important to be aware of the potential differences in either value and choose the one appropriate for the scenario.

---
Tags: xna, c#, monogame, windows-phone-8
---


# Question
Title: How do I run a callback when all objects have stopped moving?
I'm using Bullet and want to take some action once all objects in a dynamic world have reached 0 velocity (or at least a value that's very close).

I was trying to iterate over all of them all the time and when a counter equals `getNumCollisionObjects()` then do that action. But it's a complex procedure and I'm beginning to think it's unnecessary.

Is there a better way, perhaps by comparing two frames or a Bullet built-in?

# Answer
You can call isActive() on each btCollisionObject. It just returns a boolean, so it's easy to work with.

Alternatively, you can call getActivationState() which returns an int representing one of these values, but you shouldn't need to.

To optimize, if you really need to, I'd just add all collision objects to a list. Loop through this list every frame, removing each inactive object you come across until you find a single active one, then break out of the loop. Or just loop through all objects every frame. Premature optimization is usually not worth it.
> 1 votes

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


# Question
Title: How do I avoid an infinite loop when testing D3D9 occlusion queries in SlimDX?
I'm creating a Managed DirectX 9 application using SlimDX. I'm trying to utilize occlusion queries in order to cull non-visible geometry found in the scene. The problem I'm having relates to SlimDX's implementation of IDirect3DQuery9::GetData().

SlimDX, in managed code, has a function to check the status of a query. This function(SlimDX.Direct3D9.Query.CheckStatus(bool flush)) returns true if the query results are available, and false if the data is not yet available. The problem is, the unmanaged counterpart of CheckStatus(), IDirect3DQuery9::GetData(), will not only return true or false but also an HRESULT that indicates that the device was lost while waiting for the query result to become available. Because the call to CheckStatus() lies within a 'while' loop, the application hangs in an infinite loop. Also, another problem occurs that causes the graphics device driver to crash. The computer must be restarted altogether in order to restore the system. Here is my implementation of an occlusion query:

```
using Device = SlimDX.Direct3D9.Device;
using Query = SlimDX.Direct3D9.Query;
using QueryType = SlimDX.Direct3D9.QueryType;
using Issue = SlimDX.Direct3D9.Issue;

// device and query
Device pd3dDevice = GetDevice();
Query occlusionQuery = new Query(pd3dDevice, QueryType.Occlusion);

...
// issue begin
occlusionQuery.Issue(Issue.Begin);

// draw scene item
...

// issue end
occlusionQuery.Issue(Issue.End);

// wait for query results to be ready
while (!occlusionQuery.CheckStatus(true)) { }

// get query data
uint ucPixelsRendered = occlusionQuery.GetData<uint>(false);

```

The implementation eventually hangs or the device will be lost during the CheckStatus loop and the graphics device driver will crash requiring a restart of the computer...

I have successfully implemented timing queries(disjoint, frequency, and timestamps) without any problems.

How do I correctly implement an occlusion query in SlimDX?

# Answer
> 0 votes
SlimDX's `CheckStatus` wraps the native `GetData` as follows (see the implementation here)

* If the result is `S_OK`, return `true`.
* If the result is `S_FALSE`, return `false`.
* Otherwise, invoke the HR recording macro (`RECORD_D3D9`) which ultimately translates to a call `Result::Record` to record and throw the exception corresponding to the HR.

Unless you have used the `Configuration` class to disable throwing exceptions on failed HRESULTs, a lost-device result code from the native function will cause an exception, which will jump out of the while loop.

You can use the `Configuration` class to add or remove result watches (allowing you to configure the behavior on a per-`HRESULT` basis to either do nothing, break into a debugger, or throw. You can also clear all outstanding watches. Make sure you have adjusted the settings on the `Configuration` class according to your needs.

---

Given this, and your reports of a driver crash, I suspect the infinite loop is related to the driver instability and not the other way around. There isn't enough information in your question to diagnose what could be causing the driver problem, but it should not be problematic to call `GetData` repeatedly even if it returned a failed `HRESULT`, so I don't think your `CheckStatus` loop is a problem.

---
Tags: c#, directx9, slimdx, occlusion
---


# Question
Title: Why isn't my background drawing to the screen?
Ok, So I have a game I have been working on for a few months now and I am now stumped beyond belief. My friend who has spent days working on this background gave it to me and I put it in my game. On the phone the background draws fine, on the PC the background draws fine but my tablet refuses to draw the background and I have no idea why. The game was pretty much built for tablet and I really need an answer because I want to release this to google play soon to make it worth while for the friends who put the effort into this game. Do any of you have any idea why this isn't working? The file for the background is pretty big is that the reason (2500x2500)?

Here is the code to the drawing method

```
    //Render Function When in Play Mode
private void renderPlayMode(){

    //Draw background
    background.render(mainBatch);

    foreground.render(mainBatch);

}

```

The background.render and the foreground.render are the two functions that cause the game to go black on the tablet. I really need an answer, please!

**EDIT**

Ok, so the code above is the code that screws up the tablet and makes the screen black. Because the foreground.render is the last thing that is drawn it makes the entire screen black and if I comment out that line the background.render just makes the entire background black and no drawing.

# Answer
> 2 votes
I had a similar issue on Android with LibGDX a few month ago. Not sure if it is related though, but that's obviously something one should be aware of.

**A common issue :**

On low cost devices or old devices, when the size of the original texture file was superior to 2048\*2048px, the texture won't load. And on the worst devices i have seen, 1024\*1024px textures was the limit.

This limit depends on your hardware, and (if i'm correct) on the openGL version.

You can get the max texture size for your device with this piece of code :

```
IntBuffer buf = BufferUtils.newIntBuffer(16);
Gdx.gl.glGetIntegerv(Gdx.gl.GL_MAX_TEXTURE_SIZE, buf);
int maxSize = buf.get();
Gdx.app.log("GL", "Max openGL texture size : " + String.valueOf(maxSize));

```

By running this code, i know that my PC can load 16K (16384\*16384px) textures, my Samsung GS4 can load 4K (4096\*4096px) textures, and my LG Optimus Black from 2011, can only load 2K (2048\*2048px) textures.

**Solutions :**

1. Only use 1024\*1024px texture that are probably supported by any device running the android system. (Bad solution)

**or**
2. Distribute your graphics assets in differents resolution categories (ld, md, hd, uhd for example), if you want to be able to target low cost devices while rendering perfect hd graphics on the high-end ones. (Best solution, that needs some work)

**or**
3. Using 2048\*2048px may be a good compromise, that allows you to render perfectly on GS4, GS5, Z2 ... etc (but on not the Nexus 10, that could benefit from 2560\*1600px textures), while being able to also load textures on most devices. But expect complaints from users. (Lazy solution)

---
Tags: java, android, libgdx
---


title: 2D Enemy AI reacting to sound

text:
# Question
Title: 2D Enemy AI reacting to sound
I'm currently working on a 2D top-down survival game and I'm trying to figure out a good method for enemies to detect player sounds. For instance - if the player fires his gun it should play a sound (already implemented) and then enemies near the player should 'hear' the sound and react to it.

The obvious solution is to simply check a radius around the sound origin for enemies and flag them as having heard the sound. The issue here is that I have many buildings and walls and other objects that would normally interfere with sound. If I simply do a radius check then enemies will hear the player through walls and bulkheads.

The next obvious solution is to use raycasting. I cast a ray to every enemy within a radius of the origin of the sound and if the ray hasn't hit anything then the enemy can hear the sound. This method works, but I'm looking for something more natural.

What I'm hoping for is a method of having sound rays penetrate walls and lose intensity depending on the object. I'm using Farseer Physics and am currently working towards this implementation but there's one catch that I haven't figured out. **If an enemy is around a corner then the ray will pass through the wall and lower intensity even though the enemy SHOULD be able to hear the sound loud and clear.** I know this has to do with sounds bouncing off of other walls and echoing but I have no idea how to implement that without raycasting like crazy.

My question then becomes: **Does anyone have a semi-realistic method of producing a sound in a 2D world, and having enemies react to it through, and around walls?**

# Answer
This is a line-of-sight problem in disguise, and if your walls are vector based you can apply mechanics typically used for realistic lighting to it. If not, you can vectorize them and apply the same algorithms.

You have sound *sources* and *listeners*, and you can think of *walls* as casting "sound shadows."

**For refractive sound (around corners, down halls)**

Sweep a ray from the *sound source* to each *wall vertex* and *listener* in order to find out if any *listeners* are between the sound source and *occluding walls*. For walls that are partially occluded, repeat the process starting from the ray's angle of incidence to the wall intersection and proceeding clockwise or counter-clockwise (depending on the direction you swept the original ray).

This way, the nearest walls to the source will limit the sound from passing through. You can use the partial wall behaviour above to gather listeners where sound still passes through but at a reduced volume.

See "Red Blob Games - 2d Visibility" for examples of how these algorithms can be visualized.

**Design considerations**

As a matter of design advice, players will bring their own expectations into the game about how sound should behave so it will be important to highlight these mechanics. Otherwise they may feel as though some sounds should have been blocked, or that there was no way they could know that a sound would echo all the way down a hall.

A bonus to approaching it this way is you also get a clean way of displaying how sound travels, either to show the player or for testing. Just create a mask from the swept areas and display it like a light source or animation, like a series of expanding rings.
> 6 votes

# Answer
Although I think I would go for patfinding to listeners if possible myself another idea would be to flood fill the are with sound sort of like a breadth first search or similar to dijkstra's with cheapest node next. Depending on your world this might or might not be computationally expensive. Maybe your audiogrid would not have to be as fine grained as everything else?
> 0 votes

---
Tags: 2d, physics, ai, sound
---


title: Google Play Billing

text:
# Question
Title: Google Play Billing
Do Google Play Game Service charge for request/time? Like Parse.com, they have something like 1000000 reg/day is free and will charge the developer for anything more than that. What is Google Play's part for that? I could not find any of the documentation on that part online.

# Answer
After sign up the Google Play Game Developer program and playing around for a while. I believe it is not entirely free per say.

In Google API console, there is a section that you can check your APIs that link to your game/app that created in Google Play Game Console(This is the different console from the former). There you can check the APIs' quota and limit. However, it is rather high. For Google Play Game Service, it is 50 millions requests per day, which, if your game can reach that, I believe you won't mind paying.
> 2 votes

# Answer
Google Play Gaming Services are free and doesn't have any limit for any number of concurrent users. The aim of the service is to provide tools at par with Apple's GameCenter. Since GameCenter is free, GPG service is free too.

PS: Doesn't this question belong on SO? Just asking.
> 0 votes

---
Tags: documentation, google-play-services
---


# Question
Title: How are game menus logically structured?
I've been struggling with making a game menu system in Unity for some time now. I spent time developing a way to help myself understand how game menus are connected together. Right now, I'm calling it the Screen-Menu relationship.

In this relationship, Screens (e.g. Main-Menu, Game-Over and Inventory screens) hold access to Menus (e.g. Options Menu, Level-Select menu). These Menus are accessed via MenuButtons (e.g. Options menu button via the Pause Screen).

Is this a valid way of thinking about how game menus are structured? How should I be thinking about it?

# Answer
As someone who's just spent over a month creating an inventory system, perhaps my menu system can give you some ideas.

At its base, you have categories. Within each category, you can have multiple menu items -- items the player can select to view details about, and perhaps perform an action with.

Categories can have parent categories, too.

Consider the following screenshots. Player's character has approached a merchant NPC and is wanting to buy something.

My interface above is made using GUITextures and GUITexts. The logic is stored in classes and lists. I also use this interface system for my main menu and various options.

A pseudo breakdown of the different classes involved might look like this:

```
MenuCategory:
    title (String)
    breadcrumbTitle (String)
    titleIcon (Texture)
    menuItems (List of MenuItem)
    selectedMenuItem (MenuItem)
    parentCategory (MenuCategory)

MenuItem:
    title (String)
    subtitle (String)
    description (String)
    descriptionTexture (Texture)
    action (MenuItemAction)
    actionText (String)
    childCategoryToActivate (MenuCategory)
    correspondingGameObject (GameObject)

enum MenuItemAction:
    ActivateChildCategory
    ActivateParentCategory
    PurchaseItem
    SellItem

```

The above makes up the logic of the menu system. The trick is to then have your GUI:

1. Interpret the details of the current `MenuCategory`.
2. Display each `MenuItem` contained in `menuCategory.menuItems`.
3. Highlight the current `selectedMenuItem`.
4. Display the details/description of the `selectedMenuItem`. Perhaps interpret its `correspondingGameObject` to choose what to display (maybe it's a weapon, or a potion, or something else).
5. Display the available action based on what `selectedMenuItem.action` is set to.
6. Process user input, whether to set `selectedMenuItem` to a different `MenuItem`, or execute the current item's `MenuItemAction`.

The GUITextures don't change much -- it's the GUITexts that get edited depending on what the player has selected.

Now, this merchant NPC's top-level category is just one of several top-level categories. Your game's main menu could be a top-level category, with child categories like options, save game files, etc. A high score category could be its own top-level category, or could be a child category of something else.

Just a matter of having, say, a menu controller class that is in charge of knowing when to display what, and ensuring menus don't overlap with each other; I have a few other "menu" systems that don't follow the above structure, so a controller class handles what to show. End of the day, it's really up to you, as there's no right or wrong way of doing it.

Hope this helps!
> 5 votes

---
Tags: unity, architecture, inventory, menu
---


title: Accelerated Motion

text:
# Question
Title: Accelerated Motion
I'm making a menu for my game with SDL, when you click on an option a sub menu slides down and is shown, just sliding down is really boring, so I want it to accelerate(like if gravity was pulling it) and bounce when it reaches the end. I don't care if it is physically accurate so I don't need exact 9.8m/s^2 acceleration, the acceleration I'm using is 1pixel/milisecond^2, now I don't really care about the final speed but I do need that it is always the same and that the animation takes always the same time, but my code doesn't, I perform a check on the speed at the end of the animation but It is not always the same, it is close though but just not the same, how can I make this last always exactly the same time and finish with the same speed?

```
float start_time = SDL_GetTicks();
float previous_time = start_time;
int speed = 500;    //500px/ms^2
int position = -569;

while(!return_button_clicked)
{
    float current_time = SDL_GetTicks();
    float elapsed_time = current_time - previous_time;
    previous_time = current_time;

    if(position < 0)   //if position the animation hasn't finished yet
    {
        speed += 1 * elapsed_time;     //I know the 1 is unnecessary
        position += speed * elapsed_time / 1000;
        if(position > 0)
        {
            position = 0;
        }
        RenderTheMenuInItsCurrentPosition();
        if(position == 0)    //If it is at the bottom
        {
            while(speed > 0) //bounce back
            {
                current_time = SDL_GetTicks();
                elapsed_time = current_time - previous_time;
                previous_time = current_time;

                speed -= 10 * elapsed_time;    //10 because I want the bouncing to be faster.
                position -= speed * elapsed_time / 1000;
                if(speed < 0)
                {
                    speed = 0;
                }
                RenderTheMenuInItsCurrentPosition();
            }
            while(position < 0) //fall again
            {
                current_time = SDL_GetTicks();
                elapsed_time = current_time - previous_time;
                previous_time = current_time;

                speed += 10 * elapsed_time;    //10 because I want the bouncing to be faster.
                position -= speed * elapsed_time / 1000;
                if(position > 0)
                {
                    position = 0;
                    printf("final speed is: %d\n", speed); //if position is 0 the animation has finished(almost) so tell me the speed
                    printf("Time taken is: %d\n", SDL_GetTicks - start_speed);    //Tell me the time elapsed since the beginning.
                }
                RenderTheMenuInItsCurrentPosition();
            }
        }
    }

    checkForButtonsClicked();

    if(!return_button_clicked)//if the user requested to go back, go back
    {
        while(position > -568)
        {
        /*Here, sometimes a negative speed is reached before
        getting to the desired position
        causing the menu to go in the
        opposite direction, this doesn't
        happen all the time but it is
        unpredictable (to me at least),
       so it means that it doesn't accelerate
       and decelerate at the same pace always
       also that's why it doesn't throw
       the same speed value all the time.*/
            speed -= 1 * elapsed_time;
            position -= speed * elapsed_time / 1000;
            RenderTheMenuInItsCurrentPosition();
        }
    }
}

```

# Answer
> 2 votes
Sounds like a job for an easing function! These are widely used to program animations, they are easy and flexible to use. An easing function usually takes an input between 0 and 1 (representing the progress of your animation, which plays from 0 to 1), and the output is also a number somewhere between 0 and 1, which you can use to multiply your position, or colour, or whatever it is you're animating.

Say you want to animate the movement of a variable `y` from `y0` to `y1`, from `start_time` to `end_time`. You'll use an easing function like this:

```
time_interval = end_time - start_time;
y_interval = y1 - y0;
y = easing_function((time - start_time) / time_interval) * y_interval + y0;

```

From your description, it sounds like the `easeOutBounce` function will suit. Its output accelerates from start to end, but then bounces three times.

There is a C implementation of the easing functions here: https://github.com/warrenm/AHEasing

You can use it as-is, or if you want to make your own custom function (such as a bounce that bounces less, or quicker), take a look at the code - it's fairly easy to understand.

---
Tags: physics, movement, sdl, c
---


# Question
Title: Drawing and scrolling very large zoomed tilemaps
I've been working on my game editor and doing some performance tests. In the meantime I realized that my editors performance goes significant down if I draw a large map and zoom it.

100% zoom = 112 tiles on the screen

50% zoom = 364 tiles on the screen

25% zoom = 1350 tiles on the screen

12.5% zoom = 5247 tiles on the screen

5247 is a much of it. But that are only these tiles which are need to draw.

```
for (var layerX = minTileX; layerX < maxTileX; layerX++)
for (var layerY = minTileY; layerY < maxTileY; layerY++)

```

I decided to render areas of the map to rendertargets and draw only these. The framerate goes up. But if I want to scroll it goes down again, because it have to recreate and render all rendertargets.

Maybe I could draw the whole map on rendertargets (256\*256 pixel per rendertarget =\> 63 rendertargets on a 500\*500 large tilemap with 32px tiles)? But I dont think thats is the right way to do it.

# Answer
Here are a few strategies you could try:

* Precalculate scaled-down versions of your tiles. When you use the full-scale tiles as source and let your engine scale them down everytime it draws them, it needs to perform the interpolation algorithm again and again. But when you precalculate a version of each tile in each zoom-level when you load it, blitting the image stays a trivial copy-operation even when you zoom in- or out (in the context of 3d engines, this is referred to as mip mapping).
* Don't redraw your whole map again and again every frame. Keep the last frame in memory and only redraw those parts which actually changed. You can use dirty rectangles for this. When something happens which requires a graphic update, you calculate a rectangle which covers all tiles affected by that event. When two such rectangles intersect, you replace them with a new rectangle which covers both. When you draw the next frame, you only need to loop over those rectangles which are marked dirty. When the map scrolls, draw the last frame with an offset of a few pixels and only draw those parts which newly appeared on the screen.
* Make sure you use a graphic API which uses hardware-acceleration. This can make a lot of difference, even for 2d engines. You didn't say anything about which API you use to draw your maps. It might be possible that you are using one which isn't designed for performance.
> 7 votes

---
Tags: xna, rendering, performance, tilemap
---


# Question
Title: What is an optimum failure rate that will keep people coming back to my game?
I'm guessing some research has been done into this but I can't find much information. The question might be a bit too vague in itself as it depends on so many other factors.

I'm developing a puzzle game that I want to be challenging, but not so challenging that users don't bother coming back to try again if they fail. I'm assuming the shorter the game length to more willing a user will be to try again.

For example, if a level takes an hour with a 95% failure rate, I suspect that many users wouldn't bother trying again after a couple of failures. But if a game takes 30 seconds then they'll probably keep trying again until they succeed.

I'm wondering if anyone has, or can point me in the direction of information that offers guidance on this aspect of game development.

# Answer
> 83 votes
There are probably exceptions to this, but as a thinking-aid, I theorise that *failure severity*, *decision rate* and *responsibility* should correlate. When one increases, players expect (and tolerate) higher levels of the other two.

Some examples (high to low intensity):

*Super Meat Boy* and *N* have *high severity* (much of the environment kills you on contact, forcing a level restart), but they curb frustration by allowing a *high decision rate* (short, minute-long levels, immediate respawn) and making the *player fully responsible* for failures (determinism, visual and auditory cues on death, predictable AI, highly polished controls).

*FTL* has much longer play times (up to a few hours total, with save points at will) and retrying is hence a larger undertaking. However, the average move won't doom you (your spaceship has a health bar, you can replace lost crew) and player responsibility for failure is likewise lower (large random factor).

At the low-intensity end of the spectrum are games like Monopoly or poker. Players make fairly infrequent decisions in long sittings, there are large random and human factors involved and most choices have a small influence.

Note that *speed* has no part in this. I'd argue chess is a high-intensity game, despite being slow: It has a high decision rate (both players are constantly making observations and decisions even during each others' turns), high severity (a badly considered move may decide the game at any point) and high responsibility (determinism, simple controls, lots of thinking time).

---

Indeed there are differences in player demographics in what intensity they prefer: NES players were pretty darn tolerant.

When a game like *I Wanna Be The Guy* introduces itself as "nail-rippingly difficult" or when you download Dwarf Fortress and realise the ridiculous level of detail, all of that filters the audience and primes difficulty expectations high, all before actually playing.

# Answer
> 39 votes
People come back to a game if they're entertained by it. That's what you need to do, in short. Entertain players. Failure itself does not cause people to run away. A boring game causes people to run away. Rather than concentrating on mathematically predicting how many people will fail a particular level, concentrate on finding ways to make it so they're motivated to jump back into the action after failure.

**Motivation is probably the most important aspect**. A motivated player will spend days trying to tackle the same level, if that's what's needed to win. Make sure you're showing the player how close to the goal he is when dying, and how awesome the rewards will be. If there's no motivation to win, the player is likely to abandon your game when he starts dying. A game that does not motivate the player is not entertaining to play. Puzzle games motivate their players with unlockable powerups that clear the board yielding bonus points and whatnot. Shooters motivate the players with new levels, new weapons and new enemies. RPGs motivate players with more awesome enemies, level ups and loot. A good motivator is a list of achievements that the player can earn. Make the achievements be numerous and only a select few very hard to earn. There's nothing more motivating to unlock all achievements than seeing you've already unlocked 98% of them.

Another very important thing is to make it extremely easy for the player to get back in the action after his failure. **The higher he has to climb after falling, the more probable it is he'll give up and do something else instead**. This can be achieved in multiple ways. Short levels, allowing quicksaves at any point in time, many checkpoints, turning back time to repair your mistake etc.

**Balance the difficulty properly**. Difficulty spikes are unexpected and ugly to deal with. Make that difficulty slope as smooth as possible. Make sure the difficulty comes **only from the game's mechanics**, not from the interface with the player. If a game is difficult to control, the frustrated player will surely abandon it.

For some types of games you can go with some meta game mechanics to increase the player's motivation and keep him playing:

Socialization is an important aspect to the casual crowd. Get your game to use stuff like Facebook posting, and let the player boast about his victories. Let him see other people playing better, and he might just want to play more in order to take them down from the top positions.

If you're seeing hype building around your game, make sure people are focusing on the core aspects of your game. You know Dark Souls is hard as hell because that's **what everyone says about it**. You know everyone failed most of the time while playing it, because people take pride in finally beating the game and tell the story. Surely joining the crowd and doing better than your fellow players is motivating in this case.

# Answer
> 9 votes
There are multiple factors to consider (as always). As you posted a link to your game, I also want to talk about the specific implications for your special case.

## 1. Player responsibility

This was already explained quite nicely by @Anko. If the player feels like he is actually responsible for his failure and has a chance to improve via the knowledge he gained by failing, he is more tempted to do so.

With games that contain somewhat randomly generated content like The Binding of Isaac and probably your puzzle game, that is quite a hard goal to accomplish on a higher difficulty. On most of such games, you can fail very hard or win very high without actually playing better or worse. You could of course go with hand-crafted levels, or use the method I'll explain in #3.

## 2. Instant restart

Not necessarilly a huge point, but definitely important: Enable players to restart *instantly*. If they feel like they messed up or did indeed fail a level they need to be able to restart in a moments notice so that neither gameplay is interrupted nor thought is distracted. With all skill-based games, you are learning by doing, and the less time you spend doing in a session, the less you learn in a session.

Additionally, interruptions can be frustrating. Especially with the short attention span your game gets on a mobile platform, make every second count. A very good example is Super Hexagon where you can restart so instantly, it doesn't even always feel like failure. As a counter-example, Space Run has a 5-10 second cutscene and requires you to redo your ship configuration on every restart, which is very critical as it is a difficult, failure-base game.

## 3. "I nearly did it!"

As an addition to player responsibility: you can fool the player, which isn't necessarily a bad thing.

You would need a somewhat dynamic difficulty level which makes the game a bit harder or a bit easier depending on how the player does at the moment. This can emulate the feeling of being in control, but you have to be careful to not overdo it. In your case, if you detect the player is running behind, give him a few more words so he can catch up to the goal and barely make or not make it.

This way, if he fails, he will be more compelled to try again, *or* (and this is where the success of Candy Crush lies), make him buy a few extra moves or extra time to complete the level. Extra Credits has an excellent video on the topic. This would of course be an excellent hook for monetization.

## 4. Rewards

Only indirectly related to difficulty, let players unlock achievements or trophies, show them cool animations for good combos, make them feel like they're working towards a goal even if the odds aren't quite in their favour right now. Most First-Person-Shooters use this principle these days and they have good reason to do so, as they operate in a high-frustration/high-reward field.

---

There they are, my two cents on the topic. Keep in mind that you may want to question my reasoning to let your own thoughts and ideas emerge.

# Answer
> 8 votes
A very important aspect of a game is what Warren Robinett called "controlled randomness". If you don't want a level to have a particular fixed solution, ensure that the level of difficulty will not be unreasonably affected by the random number generator. The game should be designed so that a someone who plays perfectly would have a 100% chance of completing every level regardless of whether the random number generator was "favorable" or "unfavorable", but a certain amount of skill would be necessary to have a significant chance of winning no matter how "favorable" the random number generation happened to be.

A major source of frustration with some games is the fact that there can be times when e.g. a player cannot possibly win unless the random generator produces a particular sort of tile, and it's not uncommon for the player to run out of moves before such a tile appears. If the design of the puzzle is such that e.g. the player will have 50 moves, but a key piece won't arrive until move #46, and thus a player must figure out how to use the first 45 moves to set things up to allow a five-move win once that piece arrives, then *tell the player that*. Make it clear that the failure of the needed piece to appear within the first 45 moves is not a result of "bad luck", but rather represents the essence of the puzzle. A player who thinks the piece in question is simply "rare" might go out of his way to ensure that he's always in a position where he would be able to use it if it arrives, even though such a strategy couldn't possibly win if the piece doesn't arrive before turn #46. By contrast, if the player is informed that the piece will arrive precisely on turn #46, then the player will have a much better idea of what's necessary and be able to work much more productively to accomplish it.

# Answer
> 3 votes
Causing people to fail levels just so you can have them come back and try again is a recipe for getting frustrated users who not only don't come back but leave negative reviews about your game.
It's been tried, it's been done, it's ugly. Games where people get hit by random events that kill them off without any reason flowing from gameplay are NOT crowd pleasers.
Rather you should make your levels hard enough that they can be completed by a player with a decent but not stellar level of skill, and have them develop that skill by making levels progressively harder as they travel through your game. First levels should thus effectively be a tutorial.
Levels should also not be so long that people get bored and give up, thinking you're just making things impossibly hard because you can't be bothered to create a well leveled game experience.

---
Tags: game-design, difficulty
---


# Question
Title: exporting bind and keyframe bone poses from blender to use in OpenGL
**EDIT:** I decided to reformulate the question in much simpler terms to see if someone can give me a hand with this.

Basically, I'm exporting meshes, skeletons and actions from blender into an engine of sorts that I'm working on. But I'm getting the animations wrong. I can tell the basic motion paths are being followed but there's always an axis of translation or rotation which is wrong. I think the problem is most likely not in my engine code (OpenGL-based) but rather in either my misunderstanding of some part of the theory behind skeletal animation / skinning or the way I am exporting the appropriate joint matrices from blender in my exporter script.

I'll explain the theory, the engine animation system and my blender export script, hoping someone might catch the error in either or all of these.

**The theory: (I'm using column-major ordering since that's what I use in the engine cause it's OpenGL-based)**

* Assume I have a mesh made up of a single vertex v, along with a transformation matrix M which takes the vertex v from the mesh's local space to world space. That is, if I was to render the mesh without a skeleton, the final position would be gl\_Position = ProjectionMatrix * M * v.
* Now assume I have a skeleton with a single joint j in bind / rest pose. j is actually another matrix. A transform from j's local space to its parent space which I'll denote Bj. if j was part of a joint hierarchy in the skeleton, Bj would take from j space to j-1 space (that is to its parent space). However, in this example j is the only joint, so Bj takes from j space to world space, like M does for v.
* Now further assume I have a a set of frames, each with a second transform Cj, which works the same as Bj only that for a different, arbitrary spatial configuration of join j. Cj still takes vertices from j space to world space but j is rotated and/or translated and/or scaled.

Given the above, in order to skin vertex v at keyframe n. I need to:

1. take v from world space to joint j space
2. modify j (while v stays fixed in j space and is thus taken along in the transformation)
3. take v back from the modified j space to world space

So the mathematical implementation of the above would be: **v' = Cj * Bj^-1 * v**. Actually, I have one doubt here.. I said the mesh to which v belongs has a transform M which takes from model space to world space. And I've also read in a couple textbooks that it needs to be transformed from **model** space to joint space. But I also said in 1 that v needs to be transformed from world to joint space. So basically I'm not sure if I need to do **v' = Cj * Bj^-1 * v** or **v' = Cj * Bj^-1 * M * v**. Right now my implementation multiples v' by M and not v. But I've tried changing this and it just screws things up in a different way cause there's something else wrong.

* Finally, If we wanted to skin a vertex to a joint j1 which in turn is a child of a joint j0, Bj1 would be Bj0 * Bj1 and Cj1 would be Cj0 * Cj1. But Since skinning is defined as **v' = Cj * Bj^-1 * v** , Bj1^-1 would be the reverse concatenation of the inverses making up the original product. That is, **v' = Cj0 * Cj1 * Bj1^-1 * Bj0^-1 * v**

**Now on to the implementation (Blender side):**

Assume the following mesh made up of 1 cube, whose vertices are bound to a single joint in a single-joint skeleton:

Assume also there's a 60-frame, 3-keyframe animation at 60 fps. The animation essentially is:

* keyframe 0: the joint is in bind / rest pose (the way you see it in the image).
* keyframe 30: the joint translates up (+z in blender) some amount and at the same time rotates pi/4 rad clockwise.
* keyframe 59: the joint goes back to the same configuration it was in keyframe 0.

My first source of confusion on the blender side is its coordinate system (as opposed to OpenGL's default) and the different matrices accessible through the python api.

Right now, this is what my export script does about translating **blender's coordinate system to OpenGL's standard system:**

```
    # World transform: Blender -> OpenGL
    worldTransform = Matrix().Identity(4)
    worldTransform *= Matrix.Scale(-1, 4, (0,0,1))
    worldTransform *= Matrix.Rotation(radians(90), 4, "X")

    # Mesh (local) transform matrix
    file.write('Mesh Transform:\n')
    localTransform = mesh.matrix_local.copy()
    localTransform = worldTransform * localTransform
    for col in localTransform.col:
        file.write('{:9f} {:9f} {:9f} {:9f}\n'.format(col[0], col[1], col[2], col[3]))
    file.write('\n')

```

So if you will, my "world" matrix is basically the act of changing blenders coordinate system to the default GL one with +y up, +x right and -z into the viewing volume. Then I also premultiply (in the sense that it's done by the time we reach the engine, not in the sense of post or pre in terms of matrix multiplication order) the mesh matrix M so that I don't need to multiply it again once per draw call in the engine.

**About the possible matrices to extract from Blender joints (bones in Blender parlance), I'm doing the following:**

* **For joint bind poses:**

```
def DFSJointTraversal(file, skeleton, jointList):

for joint in jointList:
    bindPoseJoint = skeleton.data.bones[joint.name]
    bindPoseTransform = bindPoseJoint.matrix_local.inverted()

    file.write('Joint ' + joint.name + ' Transform {\n')
    translationV = bindPoseTransform.to_translation()
    rotationQ = bindPoseTransform.to_3x3().to_quaternion()
    scaleV = bindPoseTransform.to_scale()
    file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2]))
    file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0]))
    file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2]))

    DFSJointTraversal(file, skeleton, joint.children)
    file.write('}\n')

```

Note that I'm actually grabbing the inverse of what I think is the bind pose transform Bj. This is so I don't need to invert it in the engine. Also note I went for matrix\_local, assuming this is Bj. The other option is plain "matrix", which as far as I can tell is the same only that not homogeneous.

* **For joint current / keyframe poses:**

```
for kfIndex in keyframes:
    bpy.context.scene.frame_set(kfIndex)
    file.write('keyframe: {:d}\n'.format(int(kfIndex)))
    for i in range(0, len(skeleton.data.bones)):
        file.write('joint: {:d}\n'.format(i))

        currentPoseJoint = skeleton.pose.bones[i]
        currentPoseTransform = currentPoseJoint.matrix

        translationV = currentPoseTransform.to_translation()
        rotationQ = currentPoseTransform.to_3x3().to_quaternion()
        scaleV = currentPoseTransform.to_scale()
        file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2]))
        file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0]))
        file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2]))

        file.write('\n')

```

Note that here I go for skeleton.pose.bones instead of data.bones and that I have a choice of 3 matrices: matrix, matrix\_basis and matrix\_channel. From the descriptions in the python API docs I'm not super clear which one I should choose, though I think it's the plain matrix. Also note I do not invert the matrix in this case.

**The implementation (Engine / OpenGL side):**

**My animation subsystem** does the following on each update (I'm omitting parts of the update loop where it's figured out which objects need update and time is hardcoded here for simplicity):

```
static double time = 0;
            time =  fmod((time + elapsedTime),1.);
            uint16_t LERPKeyframeNumber = 60 * time;
            uint16_t lkeyframeNumber = 0;
            uint16_t lkeyframeIndex = 0;
            uint16_t rkeyframeNumber = 0;
            uint16_t rkeyframeIndex = 0;

            for (int i = 0; i < aClip.keyframesCount; i++) {
                uint16_t keyframeNumber = aClip.keyframes[i].number;
                if (keyframeNumber <= LERPKeyframeNumber) {
                    lkeyframeIndex = i;
                    lkeyframeNumber = keyframeNumber;
                }
                else {
                    rkeyframeIndex = i;
                    rkeyframeNumber = keyframeNumber;
                    break;
                }
            }

            double lTime = lkeyframeNumber / 60.;
            double rTime = rkeyframeNumber / 60.;
            double blendFactor = (time - lTime) / (rTime - lTime);

            GLKMatrix4 bindPosePalette[aSkeleton.jointsCount];
            GLKMatrix4 currentPosePalette[aSkeleton.jointsCount];

            for (int i = 0; i < aSkeleton.jointsCount; i++) {
                F3DETQSType& lPose = aClip.keyframes[lkeyframeIndex].skeletonPose.joints[i];
                F3DETQSType& rPose = aClip.keyframes[rkeyframeIndex].skeletonPose.joints[i];

                GLKVector3 LERPTranslation = GLKVector3Lerp(lPose.t, rPose.t, blendFactor);
                GLKQuaternion SLERPRotation = GLKQuaternionSlerp(lPose.q, rPose.q, blendFactor);
                GLKVector3 LERPScaling = GLKVector3Lerp(lPose.s, rPose.s, blendFactor);

                GLKMatrix4 currentTransform = GLKMatrix4MakeWithQuaternion(SLERPRotation);
                currentTransform =  GLKMatrix4TranslateWithVector3(currentTransform, LERPTranslation);
                currentTransform =  GLKMatrix4ScaleWithVector3(currentTransform, LERPScaling);

                GLKMatrix4 inverseBindTransform = GLKMatrix4MakeWithQuaternion(aSkeleton.joints[i].inverseBindTransform.q);
                inverseBindTransform =  GLKMatrix4TranslateWithVector3(inverseBindTransform, aSkeleton.joints[i].inverseBindTransform.t);
                inverseBindTransform =  GLKMatrix4ScaleWithVector3(inverseBindTransform, aSkeleton.joints[i].inverseBindTransform.s);

                if (aSkeleton.joints[i].parentIndex == -1) {
                    bindPosePalette[i] = inverseBindTransform;
                    currentPosePalette[i] = currentTransform;
                }

                else {
                    bindPosePalette[i] = GLKMatrix4Multiply(inverseBindTransform, bindPosePalette[aSkeleton.joints[i].parentIndex]);
                    currentPosePalette[i] = GLKMatrix4Multiply(currentPosePalette[aSkeleton.joints[i].parentIndex], currentTransform);
                }

                aSkeleton.skinningPalette[i] = GLKMatrix4Multiply(currentPosePalette[i], bindPosePalette[i]);
            }

```

**Finally, this is my vertex shader:**

```
#version 100

uniform mat4 modelMatrix;
uniform mat3 normalMatrix;
uniform mat4 projectionMatrix;
uniform mat4 skinningPalette[6];
uniform lowp float skinningEnabled;

attribute vec4 position;
attribute vec3 normal;
attribute vec2 tCoordinates;
attribute vec4 jointsWeights;
attribute vec4 jointsIndices;

varying highp vec2 tCoordinatesVarying;
varying highp float lIntensity;

void main()
{
    tCoordinatesVarying = tCoordinates;

    vec4 skinnedVertexPosition = vec4(0.);
    for (int i = 0; i < 4; i++) {
        skinnedVertexPosition += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * position;
    }

    vec4 skinnedNormal = vec4(0.);
    for (int i = 0; i < 4; i++) {
        skinnedNormal += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * vec4(normal, 0.);
    }

    vec4 finalPosition = mix(position, skinnedVertexPosition, skinningEnabled);
    vec4 finalNormal = mix(vec4(normal, 0.), skinnedNormal, skinningEnabled);

    vec3 eyeNormal = normalize(normalMatrix * finalNormal.xyz);
    vec3 lightPosition = vec3(0., 0., 2.);
    lIntensity = max(0.0, dot(eyeNormal, normalize(lightPosition)));

    gl_Position = projectionMatrix * modelMatrix * finalPosition;
}

```

The result is that the animation displays wrong in terms of orientation. That is, instead of bobbing up and down it bobs in and out (along what I think is the Z axis according to my transform in the export clip). And the rotation angle is counterclockwise instead of clockwise.

If I try with a more than one joint, then it's almost as if the second joint rotates in it's own different coordinate space and does not follow 100% its parent's transform. Which I assume it should from my animation subsystem which I assume in turn follows the theory I explained for the case of more than one joint.

Any thoughts?

# Answer
> 1 votes
Have you fixed the issue already?
http://blenderartists.org/forum/showthread.php?209221-calculate-bone-location-rotation-from-fcurve-animation-data
Hope this URL would do the help, I am inspired by it and have a basic understand of the way
matrix\_local of posebone and matrix\_world of armature works in Blender.
I also want to export the translation, rotation made in keyframes to be used by OpenGL in Android,
only failed in the animation display. I am still working it out.
Hope to hear good news from you.

---
Tags: opengl, opengl-es, blender, opengl-es2, skeletal-animation
---


# Question
Title: How to find the total bounds rectangle around a list of rectangles
How can I find the total bounds rectangle around a list of rectangles?

Rectangle object: a simple data structure of 4 floats (w,h,x,y). I have an array of 2 or more rectangles and want to create a rectangle that surrounds all of them:

The result rectangle, calculated from rectangles A and B: Rectangle T : ( Ht, Wt, Xt , Yt)

# Answer
> 4 votes
First, for every rectangle convert the values for `x`, `y`, `width` and `height` into `xMin`, `yMin`, `xMax` and `yMax` like so:

```
xMin = x
yMin = y
xMax = x + width
yMax = y + height

```

Then the `xMin` value of your surrounding rectangle is the minimum of all those `xMin` values. Similarly the `xMax` value of your surrounding rectangle is the maximum of all those `xMax` values. Same for `yMin` and `yMax`.

Now you can convert these values back like so:

```
x = xMin
y = yMin
width = xMax - xMin
height = yMax - yMin

```

This will be your surrounding rectangle.

# Answer
> 0 votes
When the mass of the list is first created, loop through them all and find the relevant values. Store these max values somewhere, and every time a new rectangle is added to the list, check if it any of it's components is larger/smaller than the stored rectangle. If so, replace it. When removing you might have to run through the entire list again and check the new bounds. However, you only have to do that when you remove a rectangle, which shouldn't be too often I'd assume.

This is the way I'd probably do it at first. If it's too slow for your needs, you might have to look into more complex data structures.

# Answer
> 0 votes
Create a new class, say RectangleCollection, that holds :
\- a list of rectangles ( or BBox -bounding box-).
\- a bounding rectangle such as any rect of the list is within this rect.

On creation of such an object, both the list and the bounding rect are empty.
When inserting the first rectangle, the bounding rect will be this only rect.
When inserting other rects, the bounding rect will be extended on its left/right/top/bottom if need be to still contain the new one.
When removing a rect, if the removed rect is fully within the bounding rect, nothing to do. if the removed rect is on an edge of the bouding rect, you have to compute again the bounding rect by computing min/max/min/max of x/x/y/y to get left/right/top/bottom, then compute left/top/width/height of the bounding rect.

---
Tags: mathematics, geometry
---


# Question
Title: How can I move bodies in Farseer, using touch input?
The player should be able to move a Farseer body with it's fingers. How can I do that? What is the best way to create a Farseer body for the player's finger so that the player can move other Farseer bodies with it? I don't know how to do that.

If the player pushes a body(for example windmill sail) hard with it's finger, then the body should move/rotate faster.

**UPDATE:**

I want to move the body RectangleA1 with my finger/cursor. But something isn't working. If I press somewhere on the screen and move the cursor/finger a little bit around, then I get very often an error message in this line:

```
world.Step(Math.Min(elapsed, (1f / 60f)));

```

An exception of type 'System.NullReferenceException' occurred in FarseerForWindowsPhone.DLL but was not handled in user code

Additional information: Object reference not set to an instance of an object.

What is wrong? Why am I getting this error message?

My code:

```
    World world;
    Body RectangleA1, RectangleA2;
    Texture2D RectangleA1Sprite, RectangleA2Sprite;
    Body body;
    Fixture fixture;
    bool MouseJointAktiv = false;
    FarseerPhysics.Dynamics.Joints.FixedMouseJoint MouseJoint;
    private static float _displayUnitsToSimUnitsRatio = 100f;

    public static Vector2 ToDisplayUnits(Vector2 simUnits)
    {
        return simUnits * _displayUnitsToSimUnitsRatio;
    }

    RectangleA1 = BodyFactory.CreateRectangle(world, 1.50f, 0.50f, 1.0f);
    RectangleA1.BodyType = BodyType.Dynamic;
    RectangleA1.Mass = 20;
    RectangleA1.Position = new Vector2(4f, 1f);
    RectangleA1.Rotation = 0f;
    RectangleA1.CollisionCategories = Category.Cat5;

    RectangleA2 = BodyFactory.CreateRectangle(world, 3.50f, 0.50f, 1.0f);
    RectangleA2.BodyType = BodyType.Static;
    RectangleA2.Mass = 40;
    RectangleA2.Position = new Vector2(4f, 3f);
    RectangleA2.Rotation = 0f;
    RectangleA2.CollisionCategories = Category.Cat10;

    protected override void Update(GameTime gameTime)
    {
      float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
      world.Step(Math.Min(elapsed, (1f / 60f)));

      TouchCollection touchCollection = TouchPanel.GetState();
      foreach (TouchLocation tl in touchCollection)
      {
        if ((tl.State == TouchLocationState.Pressed))
        {
          fixture = world.TestPoint(ConvertUnits.ToSimUnits(new Vector2(tl.Position.X, tl.Position.Y)));
          if (fixture != null)
          {
            body = fixture.Body;
            MouseJoint = new FarseerPhysics.Dynamics.Joints.FixedMouseJoint(body, new Vector2(tl.Position.X, tl.Position.Y));
            MouseJoint.MaxForce = 1000 * body.Mass;
            world.AddJoint(MouseJoint);
            body.Awake = true;
            }
          }

          if ((tl.State == TouchLocationState.Moved))
          {
            if (MouseJointAktiv == true)
              MouseJoint.WorldAnchorB = ConvertUnits.ToSimUnits(new Vector2(tl.Position.X, tl.Position.Y));
          }

          if ((tl.State == TouchLocationState.Released))
          {
            world.RemoveJoint(MouseJoint);
            MouseJoint = null;
            MouseJointAktiv = false;
          }
        }

        base.Update(gameTime);
    }

```

# Answer
> 1 votes
Documentation, again. This time for `FixedMouseJoint`:

> A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces.
>
> NOTE: this joint is not documented in the manual because it was developed to be used in the testbed. If you want to learn how to use the mouse joint, look at the testbed.

In other words, a `FixedMouseJoint` attaches an arbitrary point in the world (this is what the "`Fixed`" versions of the joints do), to a point on a body. It is used extensively in the Farseer samples.

(There is no body associated with the user's finger.)

---

Given a `Vector2 position` giving the Farseer world-space position of the user's finger (or mouse cursor), you can create a `FixedMouseJoint` like so:

```
Fixture fixture = world.TestPoint(position); // what was touched?
if(fixture != null)
{
    Body body = fixture.Body;
    mouseJoint = new FixedMouseJoint(body, position);
    mouseJoint.MaxForce = 1000 * body.Mass; // <- tune this for your game
    world.AddJoint(mouseJoint);
    body.Awake = true;
}

```

As usual, when the touch/mouse button comes up, destroy the joint with:

```
world.RemoveJoint(mouseJoint);
mouseJoint = null;

```

Every frame that the joint is active, update the anchor position like so:

```
mouseJoint.WorldAnchorB = position;

```

---

Use a single `RevoluteJoint` for your windmill, using a single body (with multiple fixtures) for your sails.

If the windmill sails are not slowing down as you would like, consider adding a `FrictionJoint` with the same anchor position on each body as the revolute joint.

(If your windmill sails are free-standing (not attached to another body), you could use the `Fixed` versions of these joints.)

---
Tags: c#, farseer-physics-engine, windows-phone-8
---


# Question
Title: How can I reliably implement GPU skinning in Android?
I'm trying to get character skinning working on Android.

The idea is quite vanilla: I have my skinning matrices, and along with each vertex, I send up to four matrix indices and four corresponding weights. I sum them in the vertex shader, and apply them to each vertex.

This is what I'm doing in the vertex shader in the iOS version of my game (don't mind the normals):

```
attribute vec4 in_pos;
attribute vec4 in_normal;
attribute vec2 in_texture_coords;
attribute vec4 in_bone_index;
attribute vec4 in_bone_weight;

varying vec2 fs_texture_coords;

uniform mat4 world_view_projection;
uniform mat4 bones[@bind_matrix_count];

void main()
{
    // Skinning
    vec4 transformed_pos =
        ((in_pos * bones[int(in_bone_index.x)]) * in_bone_weight.x) +
        ((in_pos * bones[int(in_bone_index.y)]) * in_bone_weight.y) +
        ((in_pos * bones[int(in_bone_index.z)]) * in_bone_weight.z) +
        ((in_pos * bones[int(in_bone_index.w)]) * in_bone_weight.w);

    gl_Position = world_view_projection * transformed_pos;
    fs_texture_coords = in_texture_coords;
}

```

And it works pretty well. However, with the same code in Android, in some devices (notably the Nexus 7 2013), you can't access `uniform`s with non-constant indices. In other terms, you can't do this:

```
bones[int(in_bone_index.w)]

```

because `bones[some_non_constant]` is always evaluated as `bones[0]`, which is not amusing at all. The worst thing is that the shader compiler happily compiles this.

This guy seemed to have exactly the same problem. He solved it by accessing the uniforms as vectors instead of matrices. I did the same, and in fact it worked!

```
attribute vec4 in_pos;
attribute vec4 in_normal;
attribute vec2 in_texture_coords;
attribute vec4 in_bone_index;
attribute vec4 in_bone_weight;

varying vec2 fs_texture_coords;

uniform mat4 world_view_projection;
uniform vec4 bones[@bind_matrix_count * 4]; // four vec4's for each matrix

void main()
{
    // Skinning
    mat4 skin_0 = mat4(
        bones[4 * int(in_bone_index.x) + 0],
        bones[4 * int(in_bone_index.x) + 1],
        bones[4 * int(in_bone_index.x) + 2],
        bones[4 * int(in_bone_index.x) + 3]);
    mat4 skin_1 = mat4(
        bones[4 * int(in_bone_index.y) + 0],
        bones[4 * int(in_bone_index.y) + 1],
        bones[4 * int(in_bone_index.y) + 2],
        bones[4 * int(in_bone_index.y) + 3]);
    mat4 skin_2 = mat4(
        bones[4 * int(in_bone_index.z) + 0],
        bones[4 * int(in_bone_index.z) + 1],
        bones[4 * int(in_bone_index.z) + 2],
        bones[4 * int(in_bone_index.z) + 3]);
    mat4 skin_3 = mat4(
        bones[4 * int(in_bone_index.w) + 0],
        bones[4 * int(in_bone_index.w) + 1],
        bones[4 * int(in_bone_index.w) + 2],
        bones[4 * int(in_bone_index.w) + 3]);
    vec4 transformed_pos =
        ((in_pos * skin_0) * in_bone_weight.x) +
        ((in_pos * skin_1) * in_bone_weight.y) +
        ((in_pos * skin_2) * in_bone_weight.z) +
        ((in_pos * skin_3) * in_bone_weight.w);

    gl_Position = world_view_projection * transformed_pos;
    fs_texture_coords = in_texture_coords;
}

```

But I think this worked as chance. `uniform`s are not meant to be randomly accessed, so I fear this "technique" will not work in every device.

This guy is passing his matrices as textures, which is a pretty cool idea. I made a 4x32 OES\_texture\_float texture, where each texel is a matrix row, and each texture row is an entire matrix. I access it like this:

```
attribute vec4 in_pos;
attribute vec4 in_normal;
attribute vec2 in_texture_coords;
attribute vec4 in_bone_index;
attribute vec4 in_bone_weight;

varying vec2 fs_texture_coords;

uniform mat4 world_view_projection; // A texture!
uniform sampler2D bones;

void main()
{
    // Skinning
    mat4 bone0 = mat4(
        texture2D(bones, vec2(0.00, in_bone_index.x / 32.0)),
        texture2D(bones, vec2(0.25, in_bone_index.x / 32.0)),
        texture2D(bones, vec2(0.50, in_bone_index.x / 32.0)),
        texture2D(bones, vec2(0.75, in_bone_index.x / 32.0)));
    mat4 bone1 = mat4(
        texture2D(bones, vec2(0.00, in_bone_index.y / 32.0)),
        texture2D(bones, vec2(0.25, in_bone_index.y / 32.0)),
        texture2D(bones, vec2(0.50, in_bone_index.y / 32.0)),
        texture2D(bones, vec2(0.75, in_bone_index.y / 32.0)));
    mat4 bone2 = mat4(
        texture2D(bones, vec2(0.00, in_bone_index.z / 32.0)),
        texture2D(bones, vec2(0.25, in_bone_index.z / 32.0)),
        texture2D(bones, vec2(0.50, in_bone_index.z / 32.0)),
        texture2D(bones, vec2(0.75, in_bone_index.z / 32.0)));
    mat4 bone3 = mat4(
        texture2D(bones, vec2(0.00, in_bone_index.w / 32.0)),
        texture2D(bones, vec2(0.25, in_bone_index.w / 32.0)),
        texture2D(bones, vec2(0.50, in_bone_index.w / 32.0)),
        texture2D(bones, vec2(0.75, in_bone_index.w / 32.0)));
    vec4 transformed_pos =
        ((in_pos * bone0) * in_bone_weight.x) +
        ((in_pos * bone1) * in_bone_weight.y) +
        ((in_pos * bone2) * in_bone_weight.z) +
        ((in_pos * bone3) * in_bone_weight.w);

    gl_Position = world_view_projection * transformed_pos;
    fs_texture_coords = in_texture_coords;
}

```

In fact, this worked pretty nice... Until I tried it on my Galaxy Note 2. This time the compiler complained that I can't use `texture2D` on the vertex shader!

So what I'm doing is checking whether the GPU supports texture accesses on the vertex shader and if it supports OES\_texture\_float. If it does, I'm using the texture approach. If it doesn't, I'm using the vector approach.

However, the texture approach is not available on all platforms, and the vector approach is kinda working by chance. I would like to know if there is a way to pass my skinning matrices to the vertex shader, which reliably works on all devices.

I can have minimum reasonable OS requirements, like Android 4.1+, but I would like to have a solution that works on all devices which meet those requirements.

# Answer
This is non-conforming behaviour by the Nexus 7 (Adreno GPU). You say "uniforms are not meant to be randomly accessed", but according to Appendix A of the spec:

> **Uniforms (excluding samplers)**
>
> In the vertex shader, support for all forms of array indexing is mandated. In the fragment shader, support for indexing is only mandated for constant-index-expressions.

It sounds from the discussion here that this bug applies only to uniform matrix arrays, so the work-around using vectors is likely to work reliably and be portable to other GPUs (I know random uniform indexing works at least on Mali and PowerVR GPUs).
> 4 votes

---
Tags: android, glsl, opengl-es2, skinning
---


# Question
Title: What are some ways to store level data in a game like Gunpoint?
Gunpoint is a 2D stealth game available here. I was wondering how you might go about storing level data for a game like this. I'm mostly concerned about how the collision detection is saved. There are several types of things which need to be stored; solid objects (walls, floors/roofs), breakable objects (glass), and editable objects (doors, light switches). A tile based approach may work, but I think that getting small details like light switches in there would get hairy quick.

<sub>(source: steamstatic.com)</sub>

# Answer
You are approaching this from the wrong angle completely.

There are a few ways around this but first you need to decide if your tiles and your collision can have differing states. Eg: can a particular wall be passed through on one level/location and not in another. If so we can use method 1.

Firstly you need to index your tiles regardless of which method you use eg. wall\_tile\_01 may be an image but you need to know it by number.

```
empty_space = 0
wall_tile_01 = 1
wall_tile_02 = 2
etc

```

This makes things easier to track and manage machine/code side. so by assigning a list of id's you can now divide your level up into 2D arrays filled with bytes or shorts. (it is unlikely you will have more than 65,535 unique tile images)

The best way I found is to divide your world into a series of grids firstly your tile grid and secondly your region grid. Each region has a 2d index like (0,0) or (0,1) or (1,0) etc Each index refers to a tile grid.

A tile grid would have to be a fixed size eg: 10 tiles by 10 tiles so 10x10 would give you 100 tiles per region.

If depth is needed you can have each region refer to multiple layers so you may have a background layer, middle-ground layer and a foreground layer.

in method 1)

We are assuming that the tiles have no direct relationship to collision so an additional layer would be added for collision. If you have different collision shapes then use the indexing method on collider shapes (none = 0, box = 1, slope\_01 = 2, blah blah blah)

now you can store each your tile layers and collision layers as .bmp or .png 10px\*10px images for each region and I'll explain how this works at the bottom. examples of this would be images with names like

```
level_01_BG_0-0.bmp
level_01_MG_0-0.bmp
level_01_FG_0-0.bmp
level_01_collision_0-0.bmp

level_01_BG_0-1.bmp
level_01_MG_0-1.bmp
level_01_FG_0-1.bmp
level_01_collision_0-1.bmp

```

For method 2)

We are assuming that tiles on a particular layer have a direct relationship to collision.

That is we assume that any tile that isn't a) assigned index 0 b) using another non collidable index you defined, on a particular layer is collidable which is much easier and allows you to use pixel perfect collision on that layer and that layer only. Now saving the levels and collision are the same as above but would look a bit more like this.

```
level_01_BG_0-0.bmp
level_01_MG-collision_0-0.bmp
level_01_FG_0-0.bmp

level_01_BG_0-1.bmp
level_01_MG_collision_0-1.bmp
level_01_FG_0-1.bmp

```

Now for the bit about saving these levels and how it works. Remember the indexing I spoke about? That also serves a purpose for saving. By converting your tile arrays to images you can then load the images as tile arrays. If you have less than 255 tiles you can do a simple byte array which can be directly translated to an image channel so if a pixel is empty at index 0,0 of your tile array the the top left pixel of the image you create is RGB value 0,0,0 and if it is wall\_tile\_01 then the RGB value is 0,0,1.

now if you have more that 255 unique tiles you need to use more color channels and a short array. You also need to translate your shorts into groups of bytes. Essentially though if index 0,0 has the tile value 256 then the RBG value is 0,1,0 and if it is 257 then the RBG vaule is 0,1,1.

```
258 = 0,1,2
259 = 0,1,3
260 = 0,1,4

```

this kind of conversion is just a matter of maths though.

Hope this helps.

Note: You should use unsigned bytes or shorts for your tile arrays as this makes managing the data easier and makes conversion to image easier.
> 3 votes

# Answer
For a game *like* this, options are nearly limitless, and the full process of inventing such a system would be beyond the scope of this site's Q&A format.

However, Gunpoint in particular was made with GameMaker (see the "engine" info detail), an engine which handles all those details for you. The level data structures, the collision detection, the collision response, and everything else, was all in-engine features.

So perhaps that is your concise answer. How do you make a game like this that does all these things? Use an existing engine.
> 2 votes

---
Tags: 2d, data-structure, level-design
---