# Question
Title: Custom Content Pipeline with Automatic Serialization Load Error
I'm running into this error:

> Error loading "desert". Cannot find type TiledLib.MapContent, TiledLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
>
> at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.InstantiateTypeReader(String readerTypeName, ContentReader contentReader, ContentTypeReader& reader) at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.GetTypeReader(String readerTypeName, ContentReader contentReader, List`1& newTypeReaders)
> at
>  Microsoft.Xna.Framework.Content.ContentTypeReaderManager.ReadTypeManifest(Int32
>  typeCount, ContentReader contentReader) at
>  Microsoft.Xna.Framework.Content.ContentReader.ReadHeader() at
>  Microsoft.Xna.Framework.Content.ContentReader.ReadAsset[T]() at
>  Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String
>  assetName, Action`1 recordDisposableObject) at Microsoft.Xna.Framework.Content.ContentManager.Load\[T\](String assetName) at TiledTest.Game1.LoadContent() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 51 at Microsoft.Xna.Framework.Game.Initialize() at TiledTest.Game1.Initialize() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 39 at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun) at Microsoft.Xna.Framework.Game.Run() at TiledTest.Program.Main(String\[\] args) in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Program.cs:line 15

When trying to run the game. This is a basic demo to try and utilize a separate project library called TiledLib. I have four projects overall:

1. TiledLib (C# Class Library)
2. TiledTest (Windows Game)
3. TiledTestContent (Content)
4. TMX CP Ext (Content Pipeline Extension Library)

TiledLib contains MapContent which is throwing the error, however I believe this may just be a generic error with a deeper root problem.

EMX CP Ext contains one file: MapProcessor.cs

```
    using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Content;
using TiledLib;

namespace TMX_CP_Ext
{
    // Each tile has a texture, source rect, and sprite effects.
    [ContentSerializerRuntimeType("TiledTest.Tile, TiledTest")]
    public class DemoMapTileContent
    {
        public ExternalReference<Texture2DContent> Texture;
        public Rectangle SourceRectangle;
        public SpriteEffects SpriteEffects;
    }

    // For each layer, we store the size of the layer and the tiles.
    [ContentSerializerRuntimeType("TiledTest.Layer, TiledTest")]
    public class DemoMapLayerContent
    {
        public int Width;
        public int Height;
        public DemoMapTileContent[] Tiles;
    }

    // For the map itself, we just store the size, tile size, and a list of layers.
    [ContentSerializerRuntimeType("TiledTest.Map, TiledTest")]
    public class DemoMapContent
    {
        public int TileWidth;
        public int TileHeight;
        public List<DemoMapLayerContent> Layers = new List<DemoMapLayerContent>();
    }

    [ContentProcessor(DisplayName = "TMX Processor - TiledLib")]
    public class MapProcessor : ContentProcessor<MapContent, DemoMapContent>
    {
        public override DemoMapContent Process(MapContent input, ContentProcessorContext context)
        {
            // build the textures
            TiledHelpers.BuildTileSetTextures(input, context);

            // generate source rectangles
            TiledHelpers.GenerateTileSourceRectangles(input);

            // now build our output, first by just copying over some data
            DemoMapContent output = new DemoMapContent
            {
                TileWidth = input.TileWidth,
                TileHeight = input.TileHeight
            };

            // iterate all the layers of the input
            foreach (LayerContent layer in input.Layers)
            {
                // we only care about tile layers in our demo
                TileLayerContent tlc = layer as TileLayerContent;
                if (tlc != null)
                {
                    // create the new layer
                    DemoMapLayerContent outLayer = new DemoMapLayerContent
                    {
                        Width = tlc.Width,
                        Height = tlc.Height,
                    };

                    // we need to build up our tile list now
                    outLayer.Tiles = new DemoMapTileContent[tlc.Data.Length];
                    for (int i = 0; i < tlc.Data.Length; i++)
                    {
                        // get the ID of the tile
                        uint tileID = tlc.Data[i];

                        // use that to get the actual index as well as the SpriteEffects
                        int tileIndex;
                        SpriteEffects spriteEffects;
                        TiledHelpers.DecodeTileID(tileID, out tileIndex, out spriteEffects);

                        // figure out which tile set has this tile index in it and grab
                        // the texture reference and source rectangle.
                        ExternalReference<Texture2DContent> textureContent = null;
                        Rectangle sourceRect = new Rectangle();

                        // iterate all the tile sets
                        foreach (var tileSet in input.TileSets)
                        {
                            // if our tile index is in this set
                            if (tileIndex - tileSet.FirstId < tileSet.Tiles.Count)
                            {
                                // store the texture content and source rectangle
                                textureContent = tileSet.Texture;
                                sourceRect = tileSet.Tiles[(int)(tileIndex - tileSet.FirstId)].Source;

                                // and break out of the foreach loop
                                break;
                            }
                        }

                        // now insert the tile into our output
                        outLayer.Tiles[i] = new DemoMapTileContent
                        {
                            Texture = textureContent,
                            SourceRectangle = sourceRect,
                            SpriteEffects = spriteEffects
                        };
                    }

                    // add the layer to our output
                    output.Layers.Add(outLayer);
                }
            }

            // return the output object. because we have ContentSerializerRuntimeType attributes on our
            // objects, we don't need a ContentTypeWriter and can just use the automatic serialization.
            return output;
        }
    }
}

```

TiledLib contains a large amount of files including MapContent.cs

```
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using Microsoft.Xna.Framework.Content.Pipeline;

namespace TiledLib
{
    public enum Orientation : byte
    {
        Orthogonal,
        Isometric,
    }

    public class MapContent
    {
        public string Filename;
        public string Directory;

        public string Version = string.Empty;
        public Orientation Orientation;
        public int Width;
        public int Height;
        public int TileWidth;
        public int TileHeight;
        public PropertyCollection Properties = new PropertyCollection();

        public List<TileSetContent> TileSets = new List<TileSetContent>();
        public List<LayerContent> Layers = new List<LayerContent>();

        public MapContent(XmlDocument document, ContentImporterContext context)
        {
            XmlNode mapNode = document["map"];

            Version = mapNode.Attributes["version"].Value;
            Orientation = (Orientation)Enum.Parse(typeof(Orientation), mapNode.Attributes["orientation"].Value, true);
            Width = int.Parse(mapNode.Attributes["width"].Value, CultureInfo.InvariantCulture);
            Height = int.Parse(mapNode.Attributes["height"].Value, CultureInfo.InvariantCulture);
            TileWidth = int.Parse(mapNode.Attributes["tilewidth"].Value, CultureInfo.InvariantCulture);
            TileHeight = int.Parse(mapNode.Attributes["tileheight"].Value, CultureInfo.InvariantCulture);

            XmlNode propertiesNode = document.SelectSingleNode("map/properties");
            if (propertiesNode != null)
            {
                Properties = new PropertyCollection(propertiesNode, context);
            }

            foreach (XmlNode tileSet in document.SelectNodes("map/tileset"))
            {
                if (tileSet.Attributes["source"] != null)
                {
                    TileSets.Add(new ExternalTileSetContent(tileSet, context));
                }
                else
                {
                    TileSets.Add(new TileSetContent(tileSet, context));
                }
            }

            foreach (XmlNode layerNode in document.SelectNodes("map/layer|map/objectgroup"))
            {
                LayerContent layerContent;

                if (layerNode.Name == "layer")
                {
                    layerContent = new TileLayerContent(layerNode, context);
                }
                else if (layerNode.Name == "objectgroup")
                {
                    layerContent = new MapObjectLayerContent(layerNode, context);
                }
                else
                {
                    throw new Exception("Unknown layer name: " + layerNode.Name);
                }

                // Layer names need to be unique for our lookup system, but Tiled
                // doesn't require unique names.
                string layerName = layerContent.Name;
                int duplicateCount = 2;

                // if a layer already has the same name...
                if (Layers.Find(l => l.Name == layerName) != null)
                {
                    // figure out a layer name that does work
                    do
                    {
                        layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount);
                        duplicateCount++;
                    } while (Layers.Find(l => l.Name == layerName) != null);

                    // log a warning for the user to see
                    context.Logger.LogWarning(string.Empty, new ContentIdentity(), "Renaming layer \"{1}\" to \"{2}\" to make a unique name.", layerContent.Type, layerContent.Name, layerName);

                    // save that name
                    layerContent.Name = layerName;
                }

                Layers.Add(layerContent);
            }
        }
    }
}

```

I'm lost as to why this is failing. Thoughts?

---

-- EDIT --

After playing with it a bit, I would think it has something to do with referencing the projects. I'm already referencing the TiledLib within my main windows project (TiledTest). However, this doesn't seem to make a difference. I can place the dll generated from the TiledLib project into the debug folder of TiledTest, and this causes it to generate a different error:

> Error loading "desert". Cannot find ContentTypeReader for Microsoft.Xna.Framework.Content.Pipeline.ExternalReference\`1\[Microsoft.Xna.Framework.Content.Pipeline.Graphics.Texture2DContent\].
>
> at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.GetTypeReader(Type targetType, ContentReader contentReader) at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.GetTypeReader(Type targetType) at Microsoft.Xna.Framework.Content.ReflectiveReaderMemberHelper..ctor(ContentTypeReaderManager manager, FieldInfo fieldInfo, PropertyInfo propertyInfo, Type memberType, Boolean canWrite) at Microsoft.Xna.Framework.Content.ReflectiveReaderMemberHelper.TryCreate(ContentTypeReaderManager manager, Type declaringType, FieldInfo fieldInfo) at Microsoft.Xna.Framework.Content.ReflectiveReader`1.Initialize(ContentTypeReaderManager
>  manager) at
>  Microsoft.Xna.Framework.Content.ContentTypeReaderManager.ReadTypeManifest(Int32
>  typeCount, ContentReader contentReader) at
>  Microsoft.Xna.Framework.Content.ContentReader.ReadHeader() at
>  Microsoft.Xna.Framework.Content.ContentReader.ReadAsset[T]() at
>  Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String
>  assetName, Action`1 recordDisposableObject) at Microsoft.Xna.Framework.Content.ContentManager.Load\[T\](String assetName) at TiledTest.Game1.LoadContent() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 51 at Microsoft.Xna.Framework.Game.Initialize() at TiledTest.Game1.Initialize() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 39 at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun) at Microsoft.Xna.Framework.Game.Run() at TiledTest.Program.Main(String\[\] args) in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Program.cs:line 15

This is all incredibly frustrating as the demo doesn't appear to have any special linking properties. The TiledLib I am utilizing is from Nick Gravelyn, and can be found here: https://bitbucket.org/nickgravelyn/tiledlib.

The demo it comes with works fine, and yet in recreating I always run into this error.

# Answer
> 1 votes
I had a similar problem. Apperantly it has to do with some libs still using the old names. You can tell by looking in your bin folders of all the tiled contentpipeline etc.

I solved the problem by doing the following:

* Change the Namespaces according to your new project name
* Change your application name in all csproj properties according to you new project name
* Rebuild solution (clean build)

---
Tags: xna, xna-4.0, tiles, tilemap, xna-content-pipeline
---


# Question
Title: Which sketch-to-3D-model software is available?
I picture this: I paint a 3dmodel from the front, side and top - more or less to scale.

Then I take a photo of it and give it to the software. The software then tries to figure out which part of it fits to which part on the other and after some guidance of me I have a maybe even textured 3D model in front of me.

For teddies there are good software pieces available but I am talking sceneries like surroundings(nature) or inside of buildings.

# Answer
Here are a bunch of "photo to 3d model" tools available:

inisght3D

3dsom

Photosculpt

Photo to 3D

Strata Foto 3D

Note that the first is open source, and the level of quality varies and depends a lot on your source photos. More specifically, none of these will do exactly what you're asking, but these are the closest things because what you're asking is impossible.
> 1 votes

---
Tags: 3d, models
---


# Question
Title: Memory clean up in scene management (AndEngine)
I have developed and launched a game called Bicycle Doodle GLD.

In this game, I load all the game resources at the initial loading scene. The game contains 24 levels, so only the resources that change for each level I don't load initially, but instead load at the level-select scene. Each level needs 5 to 15 terrain images that load during level selection time. There are the following scenes in the game: menu scene, level select scene, game play scene, and game over scene.

On each set of scene I call System.gc(), so memory clean up occur. My problem is that after playing a long time and changing scenes, the game suddenly closes without firing any message in debug.

I think memory becoming full is the reason. How do I fix this?

# Answer
> 3 votes
You need to profile your code and find what's taking up so much memory. Simply calling the garbage collection won't get rid of things that you've forgotten to stop using properly. Check out Traceview for a tool that comes with the SDK. Or search for your own Android profiler to find what's using your memory.

Once you have your memory usage statistics, you can find the parts of your code that use too much memory. Optimize those parts.

# Answer
> 2 votes
If you haven't already I would recommend looking at this video on memory management for Android apps. This gives a great overview of the Dalvik GC, and its basis in mark and sweep. It also shows some of the tools and abilities, even though its over a year old its a fantastic video.

Also, just calling `System.gc()` sends a *suggestion* to the Dalvik GC to try and release any marked memory for deletion. Of course at this point you may not have setup the rest of your program correctly to release resources, this is why as you continue to try and play it gets worse. In fact, the video specifically says you should avoid calling this method and just trust in the garbage collector, this is standard JAVA practice as well.

---
Tags: android, andengine
---


# Question
Title: Identifying quad patterns in a two-dimensional array
In the tech demo I'm trying to make, tetrominoe-style blocks will be placed by the player, at which point the game checks to see if they've made a quad with any existing shapes on the board (a 2D array). If so, the quad should be processed in some way.

I have a 2D array like so:

```
[ [0, 0, 0, 1, 1, 1],
  [0, 1, 1, 1, 1, 1],
  [1, 0, 0, 1, 1, 1],
  [1, 0, 0, 1, 0, 1] ]

```

And I need to identify 'quad' patterns such as that in the top-right corner, e.g.

```
[ [1, 1, 1],
  [1, 1, 1],
  [1, 1, 1] ]

```

I'm not sure of the best way to do this. I've had a look at some two-dimensional array pattern matching algorithms, which all seem to flatten the 2D array into 1D, then use a 1D text searching algorithm (e.g. KMP) to identify any matches. My problems with that idea are that **the quad can be any size, as long as it's rectangular and bigger than an arbitrary minimum** (in my case, 2 x 2).

I also thought about using some variant of the 4 way flood fill algorithm or connected-component labelling, for each position of the newly-place tetrominoe. But I'm not quite sure how to best follow the path out and establish the bounds of a quad (for example, capturing this:

```
[ [1, 1, 1],
  [1, 1, 1],
  [1, 1, 1] ]

```

out of this:

```
[ [1, 1, 1, 1],
  [1, 1, 1, 0],
  [1, 1, 1, 0] ]

```

My latest though is perhaps a floodfill to get all interconnected parts after a tetrominoe lands, then 'round off' the jagged edges, maybe by checking the number of neighbours of each block, if it's 1, remove it, repeating the process until all remaining blocks have 2 or more neighbours. But this seems like it could be slow.

Has anyone any experience of this problem, or any pointers about how best to accomplish this task? I'm sure there's a common or at least applicable algorithm, I just don't know it!

# Answer
I drew it.

# What everything means

* **Coloured backgrounds** are the layout of filled squares just after a block has been placed.
* **Red circles** are locations that could potentially be the top-left corner of a quad.
* **Red lines** are on squares around a potential corner that must be filled for the shape to be a quad.
* **Red crosses** are locations that were checked and found to be empty. (In the last two diagrams, I've connected them to the red circle from which the check was made.)

# What happened?

In the **first diagram (green)**, things worked out fantastically. The very first top-left corner we checked has filled squares on its bottom-right outline that form a `2x2` block. If we try to be even more ambitious and form a `3x3` block, we find that some of those (the red crosses) are not filled. So all we got is a `2x2`.

In the **second diagram (blue)**, things worked out easily also. Except this time, even the second bottom-right outline matched on all squares: We have a `3x3` block. Trying for a `4x4` fails, as not all squares are filled.

In the **third diagram (purple)**, we've got nothing. We ran out of filled squares to place the corner in before we found one that has a bottom-right outline.

In the **fourth diagram (yellow)**, things worked after some trying. The first three squares we tried to place corners in had no bottom-right outline. The fourth, however, did. This gives us a `2x2`. Trying to get a `3x3` fails as in the first diagram.

# How would you implement this?

If your corner is `grid[0][0]`, the `n`th bottom-right outline consists of squares where *one or both coordinates* are `n`.

This generalises to: If your corner is at `grid[x][y]`, then the bottom-right outline is a union of these sets of squares:

* `grid[x+n][yVariable]`, where `y <= yVariable < y+n` (the right side)
* `grid[xVariable][y+n]`, where `x <= xVariable < x+n` (the bottom side)
* and finally `grid[x+n][y+n]` (the bottom-right corner)

It should be easy to iterate through these. If you have a quad, the top-right and bottom-right corners' coordinates tell you where it is.

**That only works for squares though!**

# Generalising to rectangles

Those three bullet points above can also be checked for individually:

This of course means that from any state of checking, 3 (instead of 1) possible further states may evolve:

Each of these three states can each be further expanded into up to three states by a similar method.

Your code could *save the two other states for later* and process the first to exhaustion before continuing with the next. At the end, the quad with the largest area would be the output. (This is, in computer science terms, a depth-first traversal of a trinary tree.)
> 7 votes

# Answer
Just as a follow up - I eventually ended up coding a couple of solutions, one of which was basically a Javascript implementation of the Maximal Rectangle algorithm described in this article on Dr Dobbs. Seems like my issue was basically the problem this algorithm aims to solve in a nutshell!

I've written up a short blog piece on how I did it in Javascript and the resultant code, available on my blog over here.
> 0 votes

---
Tags: 2d, collision-detection, puzzle
---


title: Territory patrol planning

text:
# Question
Title: Territory patrol planning
I am developing a game/simulation where agents are fighting for land. I have the situation shown in the picture below:

These creatures are walking around and occupying pieces of land they step on if they are free. To make this more interesting, I want to introduce "patrolling" behaviour, such that agents are actually walking around their land to patrol from any intruders who may want to take it.

On the technical side, each square is represented as a `x,y` position as well as a dimension representing its side length. It also contains information on who occupies the square. All squares are stored in an `ArrayList`.

How can I introduce patrolling behaviour? What I want is for each agent to patrol a certain portion of the area (they divide amongst themselves which areas they will patrol). The main issue I've found are as follows:

* The area of land is very random, as seen in the picture. It is rather difficult to understand where the bounds are in each direction.
* How they should agents split the regions to patrol?
* Areas of land may be disjoint, since the opposing team may take territory from the middle.

I had an idea of taking the furthermost square in each direction, treating those as the boundaries of the area, and divide regions based on those boundaries, but this might include lots of irrelevant land.

How should I approach this problem?

# Answer
Fascinating question. I think one of the first issues you have to address is whether you want the patrolling behavior to be "optimum" patrolling or "lifelike" patrolling. I'm just making up these words, but what I mean is:

**Optimum**: The agents move about in a manner that perfectly distributes their coverage area for the system as a whole.

**Lifelike**: The agents move about and attempt to distribute themselves as equally as possible, but each only have access to data local to their perspective.

I'm going to focus on the second approach, which I think you can solve using weighted blending of various steering patterns from Craig Reynolds' Steering Behaviors For Autonomous Characters. The basic idea of steering behaviors is to use simple forces that combine to produce improvisational navigation around an environment. In your case I think you'd want to combine the following steering behaviors:

* *Avoidance* (outside territory) - The agents attempt to stay within their territory and avoid moving outside it. For some realism though, the influence of "stepping outside" the territory needn't be 100% here. A little bit of "cutting corners" to go outside the area would probably make for more realistic movement.
* *Wandering* \- The agents attempts to keep moving around and exploring. This one you're going to want to weigh heavily otherwise the agents are going to try to find an optimal separation point from eachother and then "stay put".
* *Separation* (other agents) - The agents attempt to keep a distance from other agents (so they cover maximum ground and don't clump up).
* *Seek* (invaders) - The agents attempt to close in on any invaders they detect.

I think you'd want to play around with the relative weighting dynamically. For example, if an agent detects an invader, the separation weighting should drop down. (In other words, they only need to spread out when they're hunting, not when they find someone.) I think if you played around with the weights for the above four patterns, you'd have something pretty close to what you're looking for.

There are quite a few resources online about how to implement "boids" that follow the behavior patterns described. I recommend the open-source implementation opensteer.
> 9 votes

# Answer
One aproach is to record, for each cell, when it was last visited by a "guard", and have the guards continually move to whichever neighboring cell that has been unvisited the longest.

Of course, this assumes that the territory is connected.

This is not a perfect solution, but easy to code, adaptive to changing circumstances, and efficient. I have successfully used this algorithm for scouting and harassment attacks in an rts ai I wrote a while back.
> 2 votes

---
Tags: java, ai, grid
---


title: XNA Game Timer Help

text:
# Question
Title: XNA Game Timer Help
How do I set a game timer in XNA? I need it to keep the game in sync no matter the lag or frame rate to prevent one moment to be normal but the next everything is sped up.

# Answer
> 4 votes
As Gustavo mentioned, you can use gameTime in Draw and Update. You may also write your own small timer class, which gets updated with the gameTime (and simply adds it up). This makes sense if you want to add some more logic to your timer class, like events or callbacks.

# Answer
> 0 votes
I was doing a quick Google Search and came across this question - I just figured I'd drop my code here. Hopefully this will be useful someone else wandering by:

```
using System;
using Microsoft.Xna.Framework;

namespace PuzzleGame.Utilities
{
    /// <summary>
    /// A <see cref="GameTimer"/> provides callbacks for when a certain amount of time has elapased.
    /// This is useful for things like time limited games, delayed menu transitions and the like.
    /// </summary>
    public class GameTimer
    {

        /// <summary>
        /// Initializes a new <see cref="GameTimer"/>
        /// </summary>
        /// <param name="totalSeconds">The amount of time it will take for this timer to fire off.</param>
        public GameTimer(double totalSeconds)
        {
            TotalSeconds = totalSeconds;
        }

        /// <summary>
        /// This event fires off when the <see cref="GameTimer"/> has completed.
        /// </summary>
        public EventHandler Completed;

        /// <summary>
        /// The amount of total seconds this timer takes to fire off.
        /// </summary>
        public double TotalSeconds { get; set; }

        /// <summary>
        /// The amount of progress [0 .. TotalSeconds] that the timer has made at the current polltime.
        /// </summary>
        public double TotalProgressSeconds { get; set; }

        /// <summary>
        /// Updates the timer with the given <see cref="GameTime"/> state.
        /// </summary>
        /// <param name="gameTime"></param>
        public void Update(GameTime gameTime)
        {
            TotalProgressSeconds += gameTime.ElapsedGameTime.TotalSeconds;
            if (TotalProgressSeconds >= TotalSeconds)
                Completed(null, null);
        }

    }

}

```

---
Tags: xna, c#, xna-4.0, game-mechanics
---


title: How do I store level-data in Android?

text:
# Question
Title: How do I store level-data in Android?
I'm building a game where enemies come in waves. I want to create a file where I can define data about the waves (# of enemies, spawn times, speeds, etc.). I come from a background in iOS and would normally use something like a plist. What would be the best way to do something like this in Java and Android?

# Answer
There's no single "best" way to do this, it depends on the needs of your game. Here are some options:

## Hard Coded

Both the easiest and probably least flexible approach. No reason you can't just make a static class with static fields for each of the levels. Actually, this isn't a bad way to prototype, so you can move it into some other approach later. If you're going to prototype this way, do yourself a favor and make the fields private (accessible through a get() method) so you can just refactor those methods into pulling from the proper source later.

## XML

This one's my vote. If you're going the XML route, there are a number of available libraries you can use to help parse the XML. (Here's one called XMLPullParser.) When you're storing flat files in android you'll have to decide whether to use internal or external storage.

* **Internal**: "You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed." (Source and more detail on how to implement here)
* **External**: "Every Android-compatible device supports a shared 'external storage' that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer." (Source and more info here.)

In your case, you probably want to use internal storage, but if you want to allow players to "mod" the game or create their own levels, you could store it externally.

A note about reading from hard files: You're going to need to do this asynchronously from your main thread. Read up on AsyncTask for implementation details.

## JSON

As an alternative to XML, you could store the objects as JSON objects. Storing as a JSON is very similar to what you're used to (i.e., storing in plist). Both describe storage of serialized objects.

Most of what I just said about XML above applies here as it's another flat file approach. For JSON the best tip I can give is check out GSON, it's super-handy.

> Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

## DATABASE

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It's built into every android device. The libraries you'll need are available in Android's SQLite Package. Google's developer docs can help you with this as well. A fantastic tutorial on this from vogella.com is available here.

## PULL FROM A SERVER

This may be overkill, but if you already have some online component to your game, you might consider pulling the levels down from the server so you can update them without any update on the client side. I recommend and use KryoNet for rolling one's own server in java. Course, this just backs up the question of how the levels are stored on the server side, but at that point we're not talking android specific anymore.
> 5 votes

# Answer
You most definitely want to use something like XML or JSON if a plist if what you're familiar with. Take a look at some of the available libraries you can use to parse either and store your data like that. A simple XML file might look like this:

```
<Data>
    <NumberOfEnemies>20</NumberOfEnemies>
    <SpawnSpeed>60</SpawnSpeed>
</Data>

```
> 2 votes

---
Tags: android, xml, data, file, storage
---


title: XNA cursor lag

text:
# Question
Title: XNA cursor lag
I'm trying to understand if this is avoidable, or it's something I just have to deal with when using XNA.

I made a new game project and loaded simple 16×16 cursor image to draw each frame at exact cursor coordinates, but even with `TargetElapsedTime` set to `1f/1000f` and `IsFixedTimeStep = false`, it seems as if the game does all calls one host frame late. Game cursor is always visible a few pixels behind the real one.

Can this be fixed somehow, or is there no way around it?

# Answer
> 2 votes
You cannot solve this problem, but you can work around it by hiding the Windows mouse cursor and drawing your own. Or replacing the Windows cursor with your own.

I explain the cause of the problem in detail in this answer. Basically Windows draws with the hardware cursor - which has an extremely low latency path from mouse-to-output. Any cursor you draw with XNA will have some latency behind the real cursor. The majority of this latency is caused by double-buffering of your graphics.

---
Tags: xna, lag
---


# Question
Title: Apparent tunneling with issue bounding box collision detection
I'm working on a Break Out game remake and I'm getting a weird bounding box collision detection behavior.

It seems like the ball is going under the paddle even if the hit is on top. Weird enough the ball doesn't go through the paddle but instead crawls within its height and then it bounces off.

My collision detection code is as follows:

```
bool collision =
            std::abs( m_x - actor.m_x ) * 2 < ( m_texture->Width() + actor.m_texture->Width() ) &&
                std::abs( m_y - actor.m_y ) * 2 < ( m_texture->Height() + actor.m_texture->Height() );

```

This is the collision behavior I'm getting for some hits:

# Answer
> 1 votes
Because your paddle has width and height it is likely that your ball manages to make it past the outside boundary of your paddle due to the update freqency and the speed of the ball. I would suggest instead of doing this type of collision detection that you instead predict where the ball will cross the boundary at its current tragectory and speed and determine if the paddle is going to be there or not.

Essentially, your first test should be wether the ball is going to go below the top Y of the paddle in the next update. If so then cast a ray from the ball to that line and determine the X location that it should hit. Then using the current tragectory of the paddle, determine if it will be there at that time or not. This is made simpler because your paddle(I assume) can only move horizontally? If not then it gets a bit more complex.

You will have to perform similar checks for hits on the sides of the paddle as well, just so you can accurately reflect it and so that it doesnt get trapped again.

---
Tags: collision-detection, aabb
---


# Question
Title: XNA shader compiler error in release mode
I'm having a hard time figuring out if I'm doing something wrong, or if there is a bug with Visual Studio.

I want to pass a float into my pixel shader, clamp it to a value, and then return it as part of the color. Here is my shader code:

```
float test;

float4 PixelShaderFunction(float2 texCoords:TEXCOORD0) : COLOR0
{
    float n = clamp(test, 0, 1);
    float4 color = float4(n, n, n, 1);

    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

Here is how I'm using the shader:

```
    protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            simpleEffect.Parameters["test"].SetValue(-1f);
            spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, simpleEffect);
            spriteBatch.Draw(pixelTexture, new Rectangle(10, 10, 100, 100), Color.Red);
            spriteBatch.End();

            base.Draw(gameTime);
        }

```

The shader compiles fine when Visual Studio is set to Debug mode, but when I set it to Release, it gives me the following error (Please excuse the `ShaderModel3Bug` solution name... I get the same error with both shader model 2 and 3):

```
Error   1   Errors compiling E:\_C#\ShaderModel3Bug\ShaderModel3Bug\ShaderModel3BugContent\simple.fx:
(15,23): ID3DXEffectCompiler::CompileEffect: There was an error compiling expression
ID3DXEffectCompiler: Compilation failed E:\_C#\ShaderModel3Bug\ShaderModel3Bug\ShaderModel3BugContent\simple.fx 15  23  ShaderModel3Bug

```

Line 15 of the shader is this:

```
PixelShader = compile ps_2_0 PixelShaderFunction();

```

I have tried compiling the shader directly using fxc.exe that comes with the June 2010 DirectX SDK. Using the command `fxc.exe /T fx_2_0 E:\_C#\ShaderModel3Bug\ShaderModel3Bug\ShaderModel3BugContent\simple.fx /Fc:output.fxc`, I get:

```
Microsoft (R) Direct3D Shader Compiler 9.29.952.3111
Copyright (C) Microsoft Corporation 2002-2009. All rights reserved.

compilation succeeded; see C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Utilities\bin\x64\output.fxc

```

So my question is, why can't Visual Studio compile the .fx file in Release mode? Am I doing something I shouldn't be doing?

### Update

Apparently XNA Game Studio doesn't use the latest version of fxc. I downloaded the March 2009 DirectX SDK, and the compilation fails with the same generic error message as Visual Studio:

```
C:\Program Files (x86)\Microsoft DirectX SDK (March 2009)\Utilities\bin\x64\ps.fx(16,23): ID3DXEffectCompiler::CompileEffect: There was an error compiling expression
ID3DXEffectCompiler: Compilation failed

compilation failed; no code produced

```

If I run the March 2009 version of fxc.exe with the /Op (disable preshaders) flag, it compiles successfully... I am still not sure what version of fxc xna uses, or what I need to do to get my shader to compile in release mode. Any help would be appreciated.

# Answer
> 3 votes
This looks like a bug in the shader compiler. XNA (as you have noted) uses an old version of the compiler. It's known to have bugs.

By the looks of it, the compiler is trying to hoist `clamp` into a preshader, and failing.

Probably the best solution here would be to manually hoist it yourself (this is what XNA's built-in effects do). The standard API for doing this is by overriding `Effect.OnApply`. Although this isn't trivial, as the content pipeline will normally give you an `Effect`, unless you mess around making a pipeline extension. Making your own wrapper class that does the clamping might be just as easy.

I recommend this blog post for some more details.

# Answer
> 1 votes
Is it legal to have a technique/pass with a pixel shader but no vertex shader? Perhaps that is intended to work in XNA, but it rings my alarm bells, so you might try adding a vertex shader (it would presumably just pass through the position and texcoords from input to output registers).

# Answer
> 1 votes
I ran into this problem again down the road, and wasn't able to modify the shader code in a way that would compile successfully under Release mode.

The basic problem is the shader compiler that XNA uses tries to generate "preshaders" when content is built in Release mode, and fails. The workaround I've found is to use a custom content processor, and always set the EffectProcessor object to use debug mode.

I followed the sample at MSDN about Creating a Custom Importer and Processor up to just before the "Implementing a Writer" section. (Creating the `CompiledPS` class is also unnecessary).

I had to make a few changes to the PSProcessor. Here's what it looks like:

```
[ContentProcessor(DisplayName = "Custom FX Processor")]
public class PSProcessor : ContentProcessor<PSSourceCode, CompiledEffectContent>
{
    public override CompiledEffectContent Process(PSSourceCode input, ContentProcessorContext context)
    {
        EffectContent content = new EffectContent();
        content.EffectCode = input.code;

        EffectProcessor compiler = new EffectProcessor();
        compiler.DebugMode = EffectProcessorDebugMode.Debug;
        CompiledEffectContent compiledEffect = compiler.Process(content, context);

        return compiledEffect;
    }
}

```

The workaround is `compiler.DebugMode = EffectProcessorDebugMode.Debug`. Once this is set, the shader compiler stops trying to generate preshaders in Release mode.

Also, instead of returning `CompiledPS` like in the sample, I just return the `CompiledEffectContent`. It took some experimenting to realize I should do this because of a very misleading note on the MSDN article (which says to return `Effect`).

Since this workaround disables 'optimizations' for the shader compiler, it might not be acceptable to everyone (luckily I'm just generating procedural textures at the beginning of a level). So, I'll leave the current answer marked.

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


title: How to cache a large object

text:
# Question
Title: How to cache a large object
I have an object made up of many vertices that changes very rare (for the most part of time, it looks the same) and I'm trying to figure out a way to avoid rendering all its vertices every frame. However, being a OpenGL beginner I have no idea how to do it. I was thinking I could render it to a texture and only show the texture every frame. But I don't know if it's possible or if there are better ways.

# Answer
> 7 votes
The technical term for rendering a model into a texture once and then just drawing that texture to the screen in place of the model is called the "imposter" technique. That is, the texture is an imposter for the model. In the old days, this was a common technique for filling out large crowds -- render textures of a few character models, and then draw lots of copies of that texture. And the game Trespasser went so far as to use it for most of its game objects.

In practice, there are a lot of problems with imposters, so it's unusual for them to be used in games these days (though they were quite common in the PS2 era). Being a static texture, they don't animate well (every copy of each imposter will be showing the same pose, for members of a crowd), they don't show correct perspective effects, etc.

It sounds like what you're really asking for is a way to avoid having to send your rarely-changing vertices to the graphics card every frame. To do that, you want to put the vertices into a Vertex Buffer Object (VBO, for short). Once you've done that, the vertices will remain in memory managed by the GPU driver, so that all you'll have to do is tell OpenGL to render using the vertices you've already stored in that VBO.

Exactly what functions you use to create and reference VBOs will vary a bit based on whether you're writing for an OpenGL 2.x or OpenGL \>=3.x context. But this is the general concept. :)

# Answer
> 1 votes
This is a common thing, generally you use either vertex arrays or VBO's (Vertex Buffer Objects) to render large objects (vertices numbering in the millions). What VBO's do is make use of the graphics processor by loading the vertices into high powered GPU memory.

The classic NeHe tutorials describe how to do this and there are many examples (of varying quality) of code around the web, check these other links out:

* Simple Tutorial on VBO's: This tutorial gives a good overview of the commands needed.
* This tutorial is somewhat dated but has good info. Especially if your graphics card is a little low down on the food chain.

# Answer
> 0 votes
If you have a stationary object and the camera doesn't move, you can render the object to an off-screen texture - a *frame buffer object (FBO)* \- and then you just have to blit that texture each frame.

In general you should assume that the contents of the frame-buffer before each frame are garbage, and always clear it. But in OpenGLES on many platforms you can control if the last frame remains in the buffer when you draw the next frame and this may be an alternative to using an explicit FBO.

***However***, if you have a scene too complex to draw each frame at a reasonable rate, and you ever need to actually redraw the scene completely (as simple as the camera moving, even if the objects in the scene do not) then you'll get choppy frame-rates.

I've used the build-scene-over-many-frames and change-level-of-detail-when-panning for things like fractal viewers where choppiness can be forgiven. In more mainstream use-cases, hmm.

---
Tags: opengl
---


title: Defect in polygon sorting

text:
# Question
Title: Defect in polygon sorting
I have a 2D game with sprites that come from texture atlases. I'm trying to resolve the sorting of my sprites for rendering.

I want two sprites to be ordered by their order of insertion, or z-order, when they overlap. Otherwise I'd want to sort by their texture index to keep sprites from the same texture together. I use the `std::sort` function for sorting a vector of queued sprites.

When queueing a sprite I transform its vertices to screen-space vertices on the CPU. The resulting polygon is used in the overlap test, which is based on this post on Stack Overflow about rectangle intersection:

```
bool Polygon::overlaps(const Polygon &rhs) const
{
    return overlapCheck(rhs, *this) && overlapCheck(rhs, rhs);
}

bool Polygon::overlapCheck(const Polygon &rhs, const Polygon &current) const
{
    bool result = true;

    for (int i = 0; i < NUM_VERTICES; ++i)
    {
        int i2 = (i + 1) % NUM_VERTICES;
        glm::vec2 p1 = current.positions[i];
        glm::vec2 p2 = current.positions[i2];

        glm::vec2 normal(p2.y - p1.y, p1.x - p2.x);

        float minA, maxA;
        overlapCheckEdges(*this, normal, minA, maxA);

        float minB, maxB;
        overlapCheckEdges(rhs, normal, minB, maxB);

        if ((maxA < minB) || (maxB < minA))
        {
            result = false;
            break;
        }
    }

    return result;
}

void Polygon::overlapCheckEdges(const Polygon &poly, const glm::vec2 &normal, float &min, float &max)
{
    bool haveMin = false;
    bool haveMax = false;

    for (PosIterator it = poly.positions.begin();
      it != poly.positions.end(); ++it)
    {
        float projection = (normal.x * it->x) + (normal.y * it->y);

        if (!haveMin || (projection < min))
        {
            min = projection;
            haveMin = true;
        }
        if (!haveMax || (projection > max))
        {
            max = projection;
            haveMax = true;
        }
    }
}

```

My sprite comparison method:

```
bool Polygon::operator < (const Polygon &rhs) const
{
    if (overlaps(rhs))
    {
        return zOrder < rhs.zOrder;
    }
    else
    {
        return textureIndex < rhs.textureIndex;
    }
}

```

The problem, of course, is that something's wrong with the sorting. I render my scene like this:

```
Transform t;
t.position.x = 33.0f;
t.position.y = 33.0f;

// "wall" and "slug" comes from texture atlas #2
// "altar" comes from texture atlas #1

// Queued sprites are translated to polygons based on given matrix
renderer.queueSprite("wall", projection.getMatrix() * t.getMatrix());

t.position.x = 0.0f;
t.position.y = 0.0f;

renderer.queueSprite("slug", projection.getMatrix() * t.getMatrix());

renderer.queueSprite("altar", projection.getMatrix() * t.getMatrix());

renderer.draw(); // Sprites are sorted then drawn

```

The sprites have sizes of 32x32 units. This is what I expect to get:

I get this instead:

The pink slug and the white altar are in the wrong order. Oddly enough, if I put the dark wall at (32, 32) instead of (33, 33) so that it's just touching the slug and altar, I get the right order.

I've also noticed that in the comparison method the altar is only ever compared with the wall. In a single sort I see this sequence of comparisons:

```
slug, wall
slug, wall
altar, wall

```

# Answer
I don't know if this is the actual cause of your problem, but your comparison function is invalid.

In most cases, including `std::sort` (which I assume you'd be using, though you didn't say), one should not assume that anything other than a strict weak ordering (that is, something that defines a *unique* (up to some equivalence class) rearrangement of the elements being sorted) can be used in a sorting algorithm.

According to Wikipedia, a strict weak ordering is a partial order “in which the relation ‘neither a \< b nor b \< a’ \[incomparability\] is transitive”. Your comparison function does not meet this criterion; for example, if three same-textured sprites A, B, C are positioned such that A and B overlap, but C is separated, then A and C are incomparable, as are C and B, but A and B are not, so incomparability is not transitive.

Another way to put it, also from Wikipedia, is:

> If x \< y, then for all z, either x \< z or z \< y or both.

That is, given any two objects, a third object is either before them, after them, or between (inclusive) them — it cannot be unspecified.

---

In general, I expect you will not be able to make a valid comparison function which *directly* conditions on sprites being overlapping, because overlapping is a non-transitive relation.

In order to dodge this, one solution would be, for example, to group together all sprites which overlap indirectly (i.e. transitive closure of overlapping); then sort the groups by the texture index of an arbitrary member of the group, and sort within the groups by z-order.

The grouping could be approximated cheaply: when a sprite starts to overlap another, merge the two sprites' groups, and when a sprite is not overlapping any others, put it in a new group by itself. You might even find tracking that information useful for collisions or other gameplay mechanics!
> 2 votes

# Answer
This sounds directly analogous to my question "Optimising the drawing of overlapping rectangles", where despite seeing benefits in sprite batching in my real game I had trouble inventing a micro-benchmark to illustrate it.

You say:

> I have a 2D game with sprites that come from texture atlases
>
> ...
>
> I want to sort by their texture index to keep sprites from the same texture together

This seems contradictory? If they are all in a texture atlas, you don't need to swap textures to draw them.

Generally, my advice is:

1. put all your sprite artwork into a single texture atlas, so you can draw all the sprites with a single draw-call
2. draw the scene with an orthogonal projection, but put the z into each sprite so that the GPU can do the depth sorting (fast GPUs just draw everything and let the depth buffer sort it out; weaker but cleverer GPUs do extra sorting steps which are going to be both correct and faster than whatever you mess around with on the CPU).
3. even if all your sprites are drawn individually with their own setting of texture and their own draw-call, even software renderers will easily keep up. I stopped needing to optimise this level of thing when we moved from 33Mhz phone GPUs interpreting Java! Oh I fondly remember the 33Mhz days. Top-down tile-based scenes are fast to draw even on the first pentiums.
> 1 votes

---
Tags: 2d, sprites
---


# Question
Title: How to transform a shadow map to camera view?
I'm making a rendering engine as a hobby to learn more about 3D. I have a deferred renderer with the G-buffer (color, normal and depth). I also have a lighting controller that uses only spotlights at the moment. For each light, I render the depth to a texture. This works nicely, but I can't wrap my head around how to map this depth map.

Basically what I would want is a view from the camera with the light's depth map mapped in the view. I've read a ton of tutorials but cannot seem to understand this process well enough.

(BTW, I'm aiming OpenGL 3.3, so no deprecated stuff in the answers. The web is full of those already :D)

# Answer
I haven't worked in OpenGL but the process should be the same. Actually it goes the other way around: you map a pixel in the view to the depth map. I try to describe this in small steps:

* Pass the pixel position from the vertex shader to the fragment shader.
* Give the light's camera and projection to the fragment shader.
* Do what you usually do in the vertex shader: multiply the pixel position with the (light) camera and the (light) projection.

Now you have the pixel's position in the light's view. To get the uv coordinates:

* Convert to the light views clipping space coordinates (x=\[-1, 1\], y=\[-1, 1\], z=\[0, 1\]) by dividing xyz components by w. (z isn't really needed though)
* To change x and y to uv coordinates (u=\[0, 1\], v=\[0, 1\]), multiply by 0.5 and add 0.5. This will, for example, turn -0.5 into 0.25 which is exactly what you want.

Use these uv coordinates to get the depth from the depth map texture.
> 2 votes

---
Tags: opengl, glsl, shadows, deferred-rendering, shadow-mapping
---


# Question
Title: Model View Controller linking dynamic model to view
I currently an implementing a game roughly using a model-view-controller setup. A single game controller instantiates a model and view. The model and view then instantiate child models and views, respectively passing references to the need models and view between them.

That works fine if the models and view are known at runtime (e.g. things that are guaranteed to exist such as the main character). My problem is when the model spawns game object models at certain times during gameplay (e.g, a randomly generated pickup). There needs to be a way for a view to also be created and the model passed as a reference to it. Of course, the model shouldn't have access to the view, but the view does have access to the model. What's a clean way to implement a system so that views can be dynamically generated and linked to their model counterparts?

One idea I had was the model can contain an array of "new" models that have not had views assigned to them already. When the view updates, it creates new views for each element in the array, assigns the models to themselves, and removes the element from the array. Thoughts? Thanks ahead of time.

# Answer
The model should indeed not have a direct reference to the view. However, the Observer Pattern can be applied here. The model has a collection of Observers. The view should implement the Observer interface. A view can add or remove it self from the model's observer collection. When a new model is created, the observers are notified and the new model can be given as a parameter.

In a way the model does have a reference to the view now, but it isn't aware of it. They are still loosely coupled.
> 2 votes

---
Tags: models, view, mvc
---


# Question
Title: Where can I host the compiled version of my game for free?
Can somebody recomend a free site for distributing and advertising my freeware (but *not* open source) Asteroids game in BINARY format?

# Answer
> 4 votes
Desura are fairly good for Indies - even free. They do have an approval process though, but it's more for the purpose of checking that you're uploading an actual game, and the one that you describe, and that it's not Copyright infringing, and that it works.

I haven't put any on there myself yet, so I can't testify as to how easy or well it works.

**Source**: http://www.desura.com/development

# Answer
> 3 votes
If it's for windows, you could host with either http://en.softonic.com/windows/games or http://www.bluesnap.com/ecommerce/sellers/digital-sales/sell-games

Both are solutions that will get you users and will also take care of payment.

# Answer
> 2 votes
It may not be exactly what you asked, but I think Gamejolt would work. You can upload desktop games there.

---
Tags: distribution, hosting
---


title: Alternative to soundeffect.play()?

text:
# Question
Title: Alternative to soundeffect.play()?
I have been using a profiler to optimize my game for the Xbox, my aim is as with any optimization to reduce excess CPU and memory usage. I have managed to cut down a lot of the processor time and memory used by my game. However i have a lot of bullets in my game that the player fires and every-time a bullet impacts with something the soundeffect.play() method is called to play the explosion. I would like to know if there is a more efficient way of playing the explosion soundeffect?

# Answer
You could possibly look into **`SoundEffectInstance`**. You can get one with `SoundEffect.CreateInstance` (and must `Dispose` of it when you are finished with it).

`SoundEffect.Play` internally creates `SoundEffectInstance` objects and plays them. It then adds them to an internal list so that, once that sound effect has finished playing, it is stopped and added back to a pool. The next time you call `SoundEffect.Play`, it will try and get a spare instance from the pool, before allocating another one.

By using `SoundEffectInstance` yourself, you can pre-allocate your desired number of instances of a sound, so you don't have the cost of allocation if the pool is empty. And you save the (small) overhead involved in tracking those internal "fire and forget" sound instances.

This can also allow you to limit the number of sounds playing at once (saving CPU). For example, if you create three instances of a sound (in a circular buffer), and your game has a situation where it wants to trigger that sound four times in a row - on the fourth trigger you could either cut off the oldest sound and restart it, or skip playing the new sound.
> 2 votes

---
Tags: xna, c#, optimization, sound
---


title: A* for non grid network

text:
# Question
Title: A* for non grid network
For my specific case, I am trying to find a path finding implementation similar to what described here.

I could see reference implementation for A\* and HPA\*, but I wonder how to extend A\* to simple roadmaps (say 20 nodes). I am not sure how to extend A\* to use non-grid network. Any examples would be useful.

Thanks.

# Answer
> 6 votes
A\* doesn't really care about the shape of the graph you're using.

Let's see the pseudocode for A\*, stolen from Wikipedia:

```
function A*(start,goal)
    closedset := the empty set    // The set of nodes already evaluated.
    openset := {start}    // The set of tentative nodes to be evaluated, initially containing the start node
    came_from := the empty map    // The map of navigated nodes.

    g_score[start] := 0    // Cost from start along best known path.
    // Estimated total cost from start to goal through y.
    f_score[start] := g_score[start] + heuristic_cost_estimate(start, goal)

    while openset is not empty
        current := the node in openset having the lowest f_score[] value
        if current = goal
            return reconstruct_path(came_from, goal)

        remove current from openset
        add current to closedset
        for each neighbor in neighbor_nodes(current)
            if neighbor in closedset
                continue
            tentative_g_score := g_score[current] + dist_between(current,neighbor)

            if neighbor not in openset or tentative_g_score < g_score[neighbor]
                came_from[neighbor] := current
                g_score[neighbor] := tentative_g_score
                f_score[neighbor] := g_score[neighbor] + heuristic_cost_estimate(neighbor, goal)
                if neighbor not in openset
                    add neighbor to openset

    return failure

function reconstruct_path(came_from, current_node)
    if came_from[current_node] in set
        p := reconstruct_path(came_from, came_from[current_node])
        return (p + current_node)
    else
        return current_node

```

There's nothing in there that specifies that the graph has to have a grid shape. However, there are two points of interest that you have to take into consideration when implementing A\*.

The first one is `neighbor_nodes()`. For a grid shaped graph, the neighbor nodes of a given node are the ones above, below, left and right (and maybe diagonals) of it. For a freeform graph, you have to provide your own implementation of `neighbor_nodes()`, but I don't think that's too much of a problem.

The second point of interest is `heuristic_cost_estimate()`. A\* relies on you being able to provide an estimation of the distance between an arbitrary node and the goal. For a grid graph, there are many heuristics, but euclidean distance and Manhattan distance are quite commonly used.

However, for an arbitrary shaped graph, you are going to have to provide your own heuristic. For abstract graphs, this may be a little bit difficult, but since your representation also seems to be somewhat geographical, you may be able to get away by using euclidean or Manhattan distance as if you were on a grid.

The advantage of the heuristic is that you can try out several different functions and see which one works the best for you.

Never forget though, that if your graphs are static (they don't change during runtime), you can have optimal solutions by precalculating distances for the entire graph using Dijkstra's or Floyd's algorithm.

---
Tags: mathematics, path-finding, graph
---


title: How do I build a 2D physics engine?

text:
# Question
Title: How do I build a 2D physics engine?
The most advanced games I've made are a 8-ball pool game made with the physics engine Box2dFlashAS3 and a platform game with levels.

When I did platform games, I've always wished to know how to make an engine, so that I could re-use it. When I see games that have slopes, curved slopes, perfect gravity and real-life physics, I've always wished I knew how to code the engine.

Please suggest techniques and articles for whatever relevant knowledge-base is necessary.

# Answer
> 16 votes
While I recommend *against* rolling your own physics engine for anything other than the experience of doing it (just realize you probably should throw it away when you're done -- it's really hard to get all the edgecases and numeric limit/stability issues sorted out, and your time may be much better used by contributing to an existing engine), here are a few resources:

Pool Hall Lessons: Fast, Accurate Collision Detection Between Circles or Spheres discusses circle/circle and sphere/sphere collision.

The N Tutorials are wonderful for a basic understanding of Separating Axis Theorem-based detection and response.

# Answer
> 9 votes
Erin Catto has all the GDC lectures about Box2D's implementation online. Box2D also has straightforward code to read, in my experience.

# Answer
> 6 votes
Here's how you might do it:

# Approximating movement

Every physics object needs these vectors:

* *Position*: Where the object is.
* *Speed*: How its position is changing.
* *Acceleration*: How its speed is changing.

So, intuitively, you need to do this sort of thing every frame to every physics object `a`:

```
a.speed    += a.acceleration
a.position += a.speed

```

**Pitfalls**: This is known as the Euler method of integration. This approximation is better for small speeds and accelerations and with small time-steps. In a game, this is normally true. But if an object moves really fast toward a thin wall or directly toward another moving object, it may skip collision with that object when its position is incremented by a large enough amount to cross it entirely. If you have fast-moving objects, you may need Continuous Collision Detection to get away with this.

# Collision

Collision can be approximated with this sort of sequence:

1. *Detection*: It is detected that two bodies intersect.
2. *Resolution*: The position of each body is changed so they no longer intersect.
3. *Physics*: The speed of each body is changed to account for momentum, friction and restitution (bounciness).

This is known as Discrete Collision Detection, as it happens at discrete points in time. Each step deserves attention:

## Step 1: Collision detection (Are things colliding?)

For *two circles*: Just check if their centres are more than the sum of their radii apart.

For *two rectangles*: Check if any of their corner coordinates are within the other rectangle.

For *anything involving more complex polygons*, you'll need the Separating-Axis-Theorem, which is a topic for another question.

**Pitfalls**: There are really many other collision types you might want to consider. Some are really complex: Convex polygons might intersect *multiple times*!

## Step 2: Collision resolution (Moving them apart.)

A simple method to resolve a collision is *translation by minimum penetration*, using values obtained from collision detection. This essentially involves moving the objects apart with the minimum possible distance of movement.

As an example, consider circle-circle collision where one of the circles is fixed in place. The minimum displacement vector has the same direction as the difference between their midpoint vectors. Its length is the difference between the sum of their radii and the distance between the centres.

This idea easily generalises to other shapes.

**Pitfalls**: If both colliding objects are moveable, you may have to move both of them by some fraction of the overall distance to get a believable approximation of their movement. They'll obviously have to move in different directions.

## Step 3: Collision physics (Other changes.)

The most obvious thing that tends to happen is that one or two of the objects changes direction i.e. rotates its speed vector. This is pretty easy to implement.

**Pitfalls**: Objects might be elastic, but they might not be, in which case the total energy in the system is reduced. You might need drag due to air resistance. Friction (particularly static friction) are notoriously complex to implement.

# Some conclusions

Simulation of reality is exponentially harder the more if it you want to simulate. You're walking into a minefield of countless edge cases, mindblowingly difficult formulae and ever-growing stacks of research papers.

If your needs are simple or you're eager to learn, try it.

If your needs are complex or you don't like maths, get a physics engine to gloss over the details for you. Box2D and Bullet are pretty popular in games.

# Answer
> 4 votes
I think this could be useful: http://gafferongames.com/game-physics/integration-basics/

# Answer
> 4 votes
Probably the most comprehensive tutorial style resource:
http://www.wildbunny.co.uk/blog/2011/04/06/physics-engines-for-dummies/
See also these related articles from the same blog:
http://www.wildbunny.co.uk/blog/2011/04/20/collision-detection-for-dummies/
http://www.wildbunny.co.uk/blog/2011/03/25/speculative-contacts-an-continuous-collision-engine-approach-part-1/

# Answer
> 2 votes
The best resource for learning game physics I have ever come across is due to Chris Hecker of "Spy Party" fame:

http://chrishecker.com/Rigid\_Body\_Dynamics

---
Tags: architecture, physics, physics-engine
---


# Question
Title: Slow Firefox Javascript Canvas Performance?
As a followup from a previous post, I have been trying to track down some slowdown I am having when drawing a scene using Javascript and the canvas element. I decided to narrow down my focus to a REALLY barebones animation that only clears the canvas and draws a single image, once per-frame. This of course runs silky smooth in Chrome, but it still stutters in Firefox. I added a simple FPS calculator, and indeed it appears that my page is typically getting an FPS in the 50's when running Firefox.

This doesn't seem right to me, I must be doing something wrong here. Can anybody see anything I might be doing that is causing this drop in FPS?

```
<!DOCTYPE HTML>
<html>
<head>
</head>
<body bgcolor=silver>
<canvas id="myCanvas" width="600" height="400"></canvas>

<img id="myHexagon" src="Images/Hexagon.png" style="display: none;">

<script>
window.requestAnimFrame = (function(callback) {
    return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
})();

var animX = 0;
var frameCounter = 0;
var fps = 0;
var time = new Date();

function animate() {

    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    context.clearRect(0, 0, canvas.width, canvas.height);

    animX += 1;
    if (animX == canvas.width)
    {
        animX = 0;
    }

    var image = document.getElementById("myHexagon");
    context.drawImage(image, animX, 128);

    context.lineWidth=1;
    context.fillStyle="#000000";
    context.lineStyle="#ffffff";
    context.font="18px sans-serif";
    context.fillText("fps: " + fps, 20, 20);

    ++frameCounter;
    var currentTime = new Date();
    var elapsedTimeMS = currentTime - time;
    if (elapsedTimeMS >= 1000)
    {
        fps = frameCounter;
        frameCounter = 0;
        time = currentTime;
    }

    // request new frame
    requestAnimFrame(function() {
        animate();
    });
}

window.onload = function() {
    animate();
};

</script>
</body>
</html>

```

**--EDIT--**

I did some additional experimentation, and now I'm not sure that this issue really has anything to do with canvas at all.

I added a "frame duration" counter in miliseconds, and neither Chrome nor Firefox ever go above 1 ms, so the code I am running inside animate is certainly not exceeding the 60 FPS frame time. My current theory is that the Firefox browser just isn't giving me a consistent animation frame that is locked to V-sync; I had read some old posts about Firefox being capped in the 50's, and maybe this is still true?

So I tried a new method to compensate for the problem. I started "pooling" my update time, and running an updatge step for each 16.6666 milisecond increment in the pool. Frankly, this looks almost MORE jittery, but I am guessing that it at least maintains a more consistent timeline for a game. Blech though :( Is this really the best way to go?

# Answer
From what I've found out while working with canvas, Firefox is indeed a bit slower than Chrome. The most important problem that I also experience and haven't found a way around is the stuttering (which can sometimes add up to one second)... but that most probably comes from their JS engine, not canvas. Either way, if it works well in Chrome without any special hacks, it's a bug that needs to be reported.
> 2 votes

# Answer
From my experience with Canvas in Firefox, I can tell that setting/changing the font of the canvas context seems to be a costly operation. I have no idea why, I can only assume it has to do with the fact that the font property is a complex string that has to be interpreted each time it's assigned. That being said, try to avoid changing the font as much as possible, especially when unnecessary.
> 2 votes

# Answer
First thing : if your screen has a 60 fps refresh rate, no Browser can go beyond that point. I own a 120 fps screen, on which Chrome give me those 120 fps, while FireFox stays around 50 fps.

Why ?
Because FireFox tops the fps on every computer :
https://developer.mozilla.org/en-US/docs/DOM/window.requestAnimationFrame

Btw : Your polyfill can be improved a bit :

```
var myRequestAnimationFrame =  window.requestAnimationFrame ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function(callback) {
                  window.setTimeout(callback, 10);
               };
 window.requestAnimationFrame=myRequestAnimationFrame;

```

So you avoid one useless function call (...), and since setTimout rounds the times you have to choose between 10,11,12, or 13. I used 10 because most likely a Browser not handling rAF will have a 10 ms accuracy timer (or worse).
Rq : I do not assign directly window.requestAnimationFrame= ... || ... || because there once was a bug with that.

Btw 2 :
I don't know if you did it just for this small demo, but you have several calls to the DOM within your Animation, which must quite slow down things, especially on FireFox. Put all objects within a var (or an within an object). And re-call animate directly with requestAnimFrame(animate)... And several other small things :-) :

```
var myRequestAnimationFrame =  window.requestAnimationFrame ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function(callback) {
                  window.setTimeout(callback, 10);
               };
window.requestAnimationFrame=myRequestAnimationFrame;

var animX = 0;
var frameCounter = 0;
var fps = 0;
var startTime = -1;
// cache all DOM references
var canvas = document.getElementById("myCanvas");
var canvasWidth=canvas.width;
var canvasHeight=canvas.height;
var context = canvas.getContext("2d");
var image = document.getElementById("myHexagon");
context.font="18px sans-serif";

function animate() {
    context.clearRect(0, 0, canvasWidth, canvasHeight);

    animX = (animX + 1) % canvasWidth;

    context.drawImage(image, animX, 128);

    context.lineWidth=1;
    context.fillStyle="#000000";
    context.lineStyle="#ffffff";
    context.fillText("fps: " + fps, 20, 20);

    frameCounter++;
    fps = (Date.now() -startTime) /frameCounter;
    // Date.now() is faster and does not create garbage.

    // request new frame
    requestAnimationFrame(animate);
}

window.onload = function() {
   startTime = Date.now();
   animate();
};

```

You also can have a noticeable gain in performance (30% if i remember well) by drawing the image to a new canvas, then using this canvas for the drawImage. I'll update this post if i find my lib which does that, but it's quite easy to figure out.
> 0 votes

---
Tags: javascript, performance, html-canvas
---


title: Swap Child and Child's Child

text:
# Question
Title: Swap Child and Child's Child
Is it possible to use swapChildren() with a *child* and a *child's child*? Every time I try, I get this error:

```
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

```

Why can I not compare a child with a child's child? How can I?

# Answer
> 4 votes
Note, that DisplayObjectContainer has 3 main methods: **addChild, removeChild and getChildAt**. All other mehtods (addChildAt, contains, getChildIndex, removeChildAt, setChildIndex, swapChildren, swapChildrenAt) are **redundant** (unnecessary) and can be implemented using 3 main methods above. Adobe added them for convenience, but it doesn't do quite what you're expecting.

Why don't you implement that "weird swapChildren" by yourself, using those 3 methods? Like so:

```
function weirdSwapChildren(childA:DisplayObject, childB:DisplayObject):void
{
    var p1:DisplayObjectContainer = childA.parent;
    var p2:DisplayObjectContainer = childB.parent;
    var i1:int = p1.getChildIndex(childA);
    var i2:int = p2.getChildIndex(childB);
    p1.removeChild(childA);
    p2.removeChild(childB);
    p1.addChildAt(childB, i1);
    p2.addChildAt(childA, i2);
}

```

# Answer
> 2 votes
From the documentation: swapChildren: Swaps the z-order (front-to-back order) of the two specified child objects.

A DisplayObject's z (or index) and it's position in the display object hierarchy are two different things. The z describes in what order the display objects are rendered within the container. A handy way of deciding what should be on top of what. swapChildren is designed for changing this property.

The DisplayObjects' position in the hierarchy also affects the rendering order but it's not the main thing. Children inherit the location, visibility, filters and a lot more.

Enabling one method to do both z swapping and changing the hierarchy is against good practice as they are two very different things. https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop

# Answer
> 0 votes
I did not until just this moment even know swapChildren() exists. Reading the description it seems pretty pointless to me. For what you want I would just use calls like object1.parent and parent.addChild(object2)

---
Tags: flash, actionscript-3
---


title: Cocos2d savegame cctmxtiledmap

text:
# Question
Title: Cocos2d savegame cctmxtiledmap
my game features several tilemaps that are initially loaded from a tmx file and modified during gameplay. How can I save the changed tilemaps in a save game? Will NSCoding do the trick here or is the CCTmxTiledMap object too complex for that? How would a sample implementation look for this problem?

# Answer
NSCoding could end up making your saved games very large.

I am working on a similar problem, not with tiles, but various sprites you can interact with placed around the map. These entities include switches, events, and items. I handle these different ways due to the nature of them.

The items are the easiest to handle. I create a unique id for the item based on the map name, and the position of the item. I can then record this unique id to a list in the permanent game state. I can then check this list on map load to see if the item should be present.

The events are a tiny bit trickier, because I want to be able to easily reference whether an event has occurred in other parts of my game code. So basically this occurs similar to the items, with the exception that I give the event an id of my choosing in the Tiled map editor. This way I can easily say, if event x occurred already, this other thing in my game will be enabled or disabled (without having to look up that event's map and position to figure out a generated unique id for it). This also helps if I decide to move the event's location or something later on.

The trickiest of all is the switches. These are like buttons that can be toggled on or off, so not only do I have to save them in the game state, but I have to save whether they are on or off. For this I can fairly easily use a dictionary to store both the switch's generated unique id (as the key) and the Boolean value as the object stored for that key. This way during map load, I can see if any switches should be different than their default state, and switch them to whatever they should be. Switches can have customized classes associated with them, so switching a switch on could change the state of several tiles on the map, or maybe it only changes an internal value. You can get very complex with this.
> 1 votes

# Answer
TMXGenerator creates and saves a tmx

maybe you could use it, or its code

https://github.com/cocos2d/cocos2d-iphone-extensions/tree/master/Extensions/TMXGenerator
> 0 votes

---
Tags: cocos2d-iphone, tilemap, savegame
---


# Question
Title: Max texture size Android : which settings for 2048x2048?
I want to use a texture atlas of 2048 x 2048 in my game, and I would like to warn the users with a "too low" device to not download the game.

With a texture atlas of this size, what requirements should I say, on ANDROID ?

This image (source : https://stackoverflow.com/questions/10392027/recommended-limit-for-memory-management-in-cocos2d ) shows the requirements for IPHONE, what about for ANDROID : 512Mo minimum, with a 1GHz, is a correct requirement ?

Thanks for your answer

# Answer
You'll be okay to ship your game to majority of your users with a configuration like that. Even the fairly old (nearly 3 years now) old Samsung Galaxy Captivate will run with a texture resolution of that size. You won't have too many issues supporting almost any device like that (I can't think of any off the top of my head. Okay, that's a lie... maybe the HTC Drean. However, that being said if you want to prevent random crashes and the like when a user OPENS your app - do yourself a favour and query for **GL\_MAX\_TEXTURE\_SIZE**. This will return the maximum texture dimension you can use and if it's less than 2048 you can throw a warning to your user stating gameplay probably won't work or you can load some alternative assets if that's possible for your game that might work for the game at a lower resolution, scale, or with some effects missing. The choice is yours!

**Edit:** We're in 2015 now; nearing 2016. You can safely assume most devices will support such an atlas.
> 14 votes

---
Tags: android, textures, texture-atlas
---


# Question
Title: As an Android dev, what should I keep in mind for porting to iPhone?
As an Android game developer, what should I keep in mind while developing my game if I ever wanted to cross-platform the game to the iPhone? Any strategies, tips, etc. on porting to both of these mobile platforms?

# Answer
**Write it in C/C++** -- this is the biggest thing you can do. Both platforms support C and C++, though in different ways. On Android, you'll be using the NDK. On the iPhone, it can be compiled along with the Objective-C code.

You'll need to invest some time building the scaffolding around your C/C++ code for each platform. You should be able to be fairly generic in this area, since it's really just connecting up the OS specific functionality into your game code. Don't skimp in this area unless you're only planning to do one cross-platform project or that you don't mind re-inventing the wheel for every project you do.

**Use OpenGL ES** -- both platforms have OpenGL ES support. Take advantage of it. This will minimize the amount of code that you need to re-write. You will still have some differences on each platform, but overall most of your code will work on both.

**Avoid platform/language specific APIs** -- this should go without saying, but it's easy to be sucked into using the Java collection classes while you are working in Java. Of course, if you followed the first rule above, you won't be doing much in Java. Same goes from the opposite way -- as nice as the Foundation classes are in iOS, if you want to port to another platform, avoid them.

As you can see, there is a lot of things to worry about by going cross-platform. If you are a small indie developer, it may not even be worth your time. You will have to evaluate if you really want to blaze your own trail so that you can target multiple platforms. It may be worth taking advantage of what each platform has to offer in order to have a faster development cycle.

Good Luck!
> 12 votes

# Answer
That will be a largely painful process going from Java \> Objective-C.

**Data Driven**
Build a game that is largely data driven. I think this speaks for itself, but this direction leads to less work you must completely re-implement.

**High and Tight**
Keep things very small and modularized. I say this because it will be much easier to port if you can easily take a component and implement just it, test and repeat.

**Contract Work**
Play your cards right and you might know someone who can take care of this for you. If you're best friends with an iPhone developer you might be able to buy him/her some dr. pepper to help migrate your code over.

**Use a Multi-Platform Engine**
If you've got a project in motion already then it doesn't make much sense. But if you're about to do a project, that you absolutely know will be ported to other platforms, then it might be worthwhile to take advantage of existing technology to help put your world together. Unity3D will be getting Android support with Unity 3.0.

**Conversion /shudder/ Tool**
And my least favorite recommendation is that you could use some sort of conversion tool to at least get your models converted from Java \> C... But... I don't endorse that.
> 5 votes

# Answer
If you're thinking of porting to the iPhone and your game is still in development, then switch to C++ if you haven't already. It will make your code significantly more portable when the time comes.
> 3 votes

# Answer
Going to add my two cents to this thread - consider writing your game in a cross platform language like many of the others have said here... but consider C#! It's a powerful language that is managed and provides a lot of great features that C++ doesn't that can assist in game development - and a great library known as MonoGame exists for it which is akin to XNA which runs on all sorts of platforms. As of Version 3.0, at the time of this writing, it's possible to write full fledged games and port to all mobile platforms with ease.
> 1 votes

---
Tags: iphone, android, cross-platform
---


# Question
Title: SDL_Image and typical SDL BMP loading fails completely
been messing with OpenGL and SDL for a pair of weeks.

The thing is quite weird. I have been loading a texture from a BMP and using a really easy shader to make it work, and so far it has worked very well.

Now, i've refractored my code and made a heightmap loader, with is pretty cool and works nice. I have a ResourceManager class which successfully loads shaders but fails at loading textures.

The structure of that class is simple:

* Constructor (empty)
* Destructor (empty)
* AddTexture (const char\* FileName, const char\* indexName)
* GetTexture (const char\* indexName)
* typedef map TextureMap
* typedef TextureMap::iterator TextureIt
* TextureMap Textures

I tried using SDL Load BMP function and SDL\_img Load IMG function. The first one makes this weird result:

Close-Up

When the real image is a simple BMP in 32bit format, as always:

Real Texture

And the second method, using SDL\_image, simply doesn't show the image.

The 'AddTexture' function:

```
bool TEXTURE::TextureManager::AddTexture(const char* fileName, const char* indexName)
{
    SDL_Surface* img = SDL_LoadBMP(fileName);
unsigned int id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img->w, img->h, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, img->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(img);
Textures[indexName] = id;
return true;
}

```

And the 'AddTexture' SDL\_image version:

```
GLuint id = 0;

SDL_Surface* Surface = IMG_Load(fileName);

glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);

int Mode = NULL;
if(Surface->format->BytesPerPixel == 4)
    Mode = GL_RGBA;
else
    Mode = GL_RGB;

glTexImage2D(GL_TEXTURE_2D, 0, Mode, Surface->w, Surface->h, 0, Mode, GL_UNSIGNED_BYTE, Surface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glBindTexture(GL_TEXTURE_2D, 0);

std::cout << "The ID of the tex is " << id << std::endl;

Textures[indexName] = id;

return true;

```

I create the texture here:

```
Res->TexManager->AddTextureAlt("res/sum.bmp", "Brick");

```

And the following code is used to bind the texture:

```
GLuint TEX = Res->TexManager->GetTexture("Brick");
glBindTexture(GL_TEXTURE_2D, TEX);

```

The normals and tex coords are alright, i've been using it all the time and it was displaying the tex and light perfectly well before.

I can't find the problem. I just can't. Is someone able to help a poor noob?

# Answer
Your problem is that there are almost an infinite number of different image formats which can be represented inside an SDL\_Surface, and you're telling OpenGL that this particular SDL\_Surface is an RGB image made of 5-6-5 bits each of red, green, and blue, when it probably isn't!

What you need to do is after loading the image, but before giving it to OpenGL, you need to copy the SDL\_Surface into another SDL\_Surface which you've created with a known image format, which matches the format you tell OpenGL.

Personally, I like converting to 8888 RGBA, because that supports everything and is simple and easy (565 has no bits for an alpha channel, for example). If you're strongly concerned about memory usage, you might want to modify this a bit to use some other format. But as a first stab at a solution and to illustrate the issue you're running into, this code works. :)

Here's my code to do this conversion, which is mostly adapted from a very old SDL wiki page which I can't find any more. It assumes that the file you've loaded is in a SDL\_Surface\* named 'source'. (My full code is available here, if you want more context than I've pasted into this answer).

```
SDL_Surface *image = SDL_CreateRGBSurface(
        SDL_SWSURFACE,
        w, h,
        32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
        0x000000FF,
        0x0000FF00,
        0x00FF0000,
        0xFF000000
#else
        0xFF000000,
        0x00FF0000,
        0x0000FF00,
        0x000000FF
#endif
        );

saved_flags = source->flags&(SDL_SRCALPHA|SDL_RLEACCELOK);
saved_alpha = source->format->alpha;
if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
    SDL_SetAlpha(source, 0, SDL_ALPHA_OPAQUE);
}

/* Copy the surface into the GL texture image */
area.x = 0;
area.y = 0;
area.w = source->w;
area.h = source->h;
SDL_BlitSurface(source, &area, image, &area);

/* Restore the alpha blending attributes */
if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
    SDL_SetAlpha(source, saved_flags, saved_alpha);
}
(... normal OpenGL texture creation code goes here)
glTexImage2D(GL_TEXTURE_2D,
    0,
    GL_RGBA,
    w, h,
    0,
    GL_RGBA,
    GL_UNSIGNED_INT_8_8_8_8_REV,
    image->pixels);

```
> 2 votes

---
Tags: opengl, textures, sdl
---


# Question
Title: How to get a texture from current point of view in OpenGL 2.0 ES?
Probably the title is confusing, but I didn't know how to ask better, sorry about that. What I would like to do is get a bitmap texture that represents exactly what's rendered at one point in time and save it as a file (I know how to save it, I need only to find out how get the bitmap data form OpenGL) Like a screen shoot, sort of.

# Answer
I think that changing the Render Target is what you're looking for. This is also known as "Render to texture".

When you draw stuff in GLES (or GL, or DirectX, or whatever you use), the place the stuff you draw to is called the "Render Target". Usually you render on a backbuffer to be drawn onto the screen, but graphic engines also allow you to draw on a custom render target you can then use as a texture for drawing other stuff.

Custom render textures are the key to enable interesting effects such as mirrors, shadow mapping, PiP, among many others.

Here's another explanation of render buffers, for XNA.

In particular, for GLES, you may want to look at `glGenRenderbuffers`, `glRenderbufferStorage`, `glBindRenderbuffer` and other associated functions.

Here's an example of how to do it in desktop OpenGL.
> 2 votes

# Answer
glReadPixels can read back pixel values from the framebuffer, which you can then save out to disk.

(Note that you don't want to use glReadPixels normally, as it makes your code stall while the GPU catches up, and reading pixels back from the GPU is usually a rather slow operation. But for the purposes of saving screenshots or debugging rendering issues, it's absolutely what you want to use. If the eventual goal is to feed rendered images back into the rendering system for use as a texture, then Panda's answer is the correct and performance-friendly way to do that. But if you need to get the pixel values back to the CPU so you can save them out, glReadPixels is really the only way to do that.)
> 2 votes

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


# Question
Title: Unlocking XNA game update rate and preventing unnecessary Draw calls and heavy logic Updates
I had some input problems which can be partially solved by unlocking game update rate. Now the input updates as fast as possible, but the game also calls the main `Draw` method a lot too. I believe there are some calls that may be omitted without causing any noticeable problems, and I'd like to know how I can do it.

I tried using code similar to frame rate counter code, but it just doesn't work. It either doesn't skip frames, or skips them all. Here it is:

```
double time = 0;
protected override void Draw(GameTime gameTime)
{
    double frameRate = 1.0 / 60;
    time += gameTime.ElapsedGameTime.TotalSeconds;
    if (time > frameRate)
    {
        time = time % frameRate;
    // the rest of the draw call

```

When the game window is active, only dark purple color is visible I guess that's application's default background color when nothing is being drawn. When the game window is not active, frame rate drops from infinity (though I get about 4000 fps) to around 50 (which is unusual, since the default frame rate is 60, but it's not an issue).

If I set `frameRate` value to lower than 1/50 (like 1/10) it becomes obvious that draw calls are skipped and the dark purple background is visible (and resources are being saved), but only when the window is inactive. So the game behaves as expected, but only when it is not in focus, which is not the way it is supposed to be played :)

How do I fix this?

I'd like to extend this to work on heavy logic updates, so they too are not done more than enough times per second. The game should only update input as fast as possible, and I believe, reducing the number of logic update and draw calls frees up resources for input update to use, increasing their frequency.

---

This is how I ended up doing this:

```
double interval = 1d / 60; // draw and do heavy updates only 60 frames per second
double time;

protected override void Update(GameTime gameTime)
{
    LightUpdate(gameTime);

    time += gameTime.ElapsedGameTime.TotalSeconds;

    if (time > interval)
        time = time % interval; // or while (time > interval) time -= interval;
    else
    {
        SuppressDraw();
        base.Update(gameTime);
        return;
    }

    HeavyUpdate(gameTime);
}

```

Saves frames, light update rate rose from 2k to **110k** @100Hz which is a tremendous success!

# Answer
> 6 votes
If you know in your Update method that you don't need or want to render anything simply call SupressDraw() on your game object (http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.suppressdraw.aspx). You don't need to add any additional logic into your Draw method to handle this, and your frame skipping logic can be moved into your Update call.

# Answer
> -3 votes
For one I would not be using doubles in a modulus operation because 1/60th can't be represented exactly in a double variable and neither will the time accumulation so you will be getting a fair bit of round off error and due to that, some interesting results.

What I would do, if you simply have to do this, is to calculate your 1/60th constant outside of this loop, assign your time variable to that value initially, and then decrement it by elapsedTime in each draw call. When the time variable is equal to or below zero then do your draw and then add the 1/60th time to it. You will still get a minor amount of round off/up error but that should balance out between draw calls.

---
Tags: xna, c#, frame-rate
---