title: Floodfill algorithm for GO

text:
# Question
Title: Floodfill algorithm for GO
The floodfill algorithm is used in the bucket tool in MS paint and photoshop, but it can also be used for GO and minesweeper.

http://en.wikipedia.org/wiki/Flood\_fill

In go you can capture groups of stones, this website portrays it with two stones. http://www.connectedglobe.com/mindy/cap6.html

This is my floodfill method in Java, it is not capturing a group of stones and I have no idea why because to me it makes sense.

```
public void floodfill(int turn, int col, int row){
    for(int a = col; a<19; a++){
        for(int b = row; b<19; b++){
            if(turn == black){
                if(stones[col][row] == white){
                    stones[col][row] = 0;
                    floodfill(black, col-1, row);
                    floodfill(black, col+1, row);
                    floodfill(black, col, row-1);
                    floodfill(black, col, row+1);
                }
            }
        }
    }
}

```

It searches up, down, left, right for all the stones on the board. If the stones are white it captures them by making them 0, which represents empty.

# Answer
It seems like you are intending to do this. The flood fill shouldn't have `for` loops in it.

```
public void floodfill(int turn, int col, int row){
    if(turn == black){
        if(stones[col][row] == white){
            stones[col][row] = 0;
            floodfill(black, col-1, row);
            floodfill(black, col+1, row);
            floodfill(black, col, row-1);
            floodfill(black, col, row+1);
        }
    }
}

public void floodfillAll(int turn){
    for(int a = 0; a<19; a++){
        for(int b = 0; b<19; b++){
            floodfill(turn,a,b);
        }
    }
}

```

Which is kind of silly. Since the flood fill should fill everything anyway. Just use the first part.
> 4 votes

# Answer
You didn't say *in what way* it's not working (is it crashing, or taking forever?). You ought to do that.

However, it strikes me as immediately absurd that your *recursive* flood fill has a loop. You could either write a loop to fill everything (which wouldn't be a flood fill), or you could write a recursive flood fill:

```
public void floodfill(int turn, int col, int row){
    if(turn == white) return;
    // also add: if 'col' and 'row' aren't in the valid range, return
    // otherwise you'll get index out of bounds errors because you will
    // eventually call to flood column -1.
    if(stones[col][row] == black) return;
    stones[col][row] = 0; // does black = 0? Saying black would be more readable
    floodfill(black, col-1, row);
    floodfill(black, col+1, row);
    floodfill(black, col, row-1);
    floodfill(black, col, row+1);
}

```

If you want to loop through every tile, you don't need a recursive flood fill. If you want to do a recursive flood fill, you don't need to loop through every tile.

Every time your old method was called it was spanning through every tile above it in the x/y direction, then calling a tile before it, which would then call every tile after it and a tile before it. I imagine your 'flood fill' would never have ended.
> 6 votes

---
Tags: java
---


# Question
Title: What is the most efficient way to convert to binary and back in C#?
I'm trying to write a general purpose socket server for a game I'm working on. I know I could very well use already built servers like SmartFox and Photon, but I wan't to go through the pain of creating one myself for learning purposes.

I've come up with a BSON inspired protocol to convert the the basic data types, their arrays, and a special GSObject to binary and arrange them in a way so that it can be put back together into object form on the client end. At the core, the conversion methods utilize the .Net BitConverter class to convert the basic data types to binary. Anyways, the problem is performance, if I loop 50,000 times and convert my GSObject to binary each time it takes about 5500ms (the resulting byte\[\] is just 192 bytes per conversion). I think think this would be way too slow for an MMO that sends 5-10 position updates per second with a 1000 concurrent users. Yes, I know it's unlikely that a game will have a 1000 users on at the same time, but like I said earlier this is supposed to be a learning process for me, I want to go out of my way and build something that scales well and can handle at least a few thousand users.

So yea, if anyone's aware of other conversion techniques or sees where I'm loosing performance I would appreciate the help.

**GSBitConverter.cs**

This is the main conversion class, it adds extension methods to main datatypes to convert to the binary format. It uses the BitConverter class to convert the base types. I've shown only the code to convert integer and integer arrays, but the rest of the method are pretty much replicas of those two, they just overload the type.

```
public static class GSBitConverter
{
    public static byte[] ToGSBinary(this short value)
    {
        return BitConverter.GetBytes(value);
    }

    public static byte[] ToGSBinary(this IEnumerable<short> value)
    {
        List<byte> bytes = new List<byte>();
        short length = (short)value.Count();

        bytes.AddRange(length.ToGSBinary());
        for (int i = 0; i < length; i++)
            bytes.AddRange(value.ElementAt(i).ToGSBinary());

        return bytes.ToArray();
    }

    public static byte[] ToGSBinary(this bool value);
    public static byte[] ToGSBinary(this IEnumerable<bool> value);

    public static byte[] ToGSBinary(this IEnumerable<byte> value);

    public static byte[] ToGSBinary(this int value);
    public static byte[] ToGSBinary(this IEnumerable<int> value);

    public static byte[] ToGSBinary(this long value);
    public static byte[] ToGSBinary(this IEnumerable<long> value);

    public static byte[] ToGSBinary(this float value);
    public static byte[] ToGSBinary(this IEnumerable<float> value);

    public static byte[] ToGSBinary(this double value);
    public static byte[] ToGSBinary(this IEnumerable<double> value);

    public static byte[] ToGSBinary(this string value);
    public static byte[] ToGSBinary(this IEnumerable<string> value);

    public static string GetHexDump(this IEnumerable<byte> value);
}

```

**Program.cs** Here's the the object that I'm converting to binary in a loop.

```
class Program
{
    static void Main(string[] args)
    {
        GSObject obj = new GSObject();
        obj.AttachShort("smallInt", 15);
        obj.AttachInt("medInt", 120700);
        obj.AttachLong("bigInt", 10900800700);
        obj.AttachDouble("doubleVal", Math.PI);
        obj.AttachStringArray("muppetNames", new string[] { "Kermit", "Fozzy", "Piggy", "Animal", "Gonzo" });

        GSObject apple = new GSObject();
        apple.AttachString("name", "Apple");
        apple.AttachString("color", "red");
        apple.AttachBool("inStock", true);
        apple.AttachFloat("price", (float)1.5);

        GSObject lemon = new GSObject();
        apple.AttachString("name", "Lemon");
        apple.AttachString("color", "yellow");
        apple.AttachBool("inStock", false);
        apple.AttachFloat("price", (float)0.8);

        GSObject apricoat = new GSObject();
        apple.AttachString("name", "Apricoat");
        apple.AttachString("color", "orange");
        apple.AttachBool("inStock", true);
        apple.AttachFloat("price", (float)1.9);

        GSObject kiwi = new GSObject();
        apple.AttachString("name", "Kiwi");
        apple.AttachString("color", "green");
        apple.AttachBool("inStock", true);
        apple.AttachFloat("price", (float)2.3);

        GSArray fruits = new GSArray();
        fruits.AddGSObject(apple);
        fruits.AddGSObject(lemon);
        fruits.AddGSObject(apricoat);
        fruits.AddGSObject(kiwi);

        obj.AttachGSArray("fruits", fruits);

        Stopwatch w1 = Stopwatch.StartNew();
        for (int i = 0; i < 50000; i++)
        {
            byte[] b = obj.ToGSBinary();
        }
        w1.Stop();

        Console.WriteLine(BitConverter.IsLittleEndian ? "Little Endian" : "Big Endian");
        Console.WriteLine(w1.ElapsedMilliseconds + "ms");

    }

```

Here's the code for some of my other classes that are used in the code above. Most of it is repetitive.

GSObject

GSArray

GSWrappedObject

# Answer
> 7 votes
Without having read through all your code (or, indeed, being very familiar with .NET) and thus not knowing how appropriate this suggestion is:

Make a wrapper around a class like `MemoryStream`, and add methods to objects that need to be serialized/deserialized. *Don't* just make a class that's an arbitrary bag of data. If you have a `Widget` class, it might read and write something like this:

```
public void WriteToBinary(StreamWrapper stream)
{
    stream.WriteString(name);
    stream.WriteString(color);
    stream.WriteBool(inStock);
    stream.WriteFloat(price);
}

public void ReadFromBinary(StreamWrapper stream)
{
    name = stream.ReadString();
    color = stream.ReadString();
    inStock = stream.ReadBool();
    price = stream.ReadFloat();
}

```

This means never creating a temporary `byte[]` array that will always be thrown away. It also can lead to smaller messages, because you don't need to encode the name of every single property: the order of reading/writing can disambiguate.

# Answer
> 1 votes
I would use something like **ProtoBuf** with RPC support.

---
Tags: c#, mmo, scalability, binary
---


title: box2d resize bodies arround point

text:
# Question
Title: box2d resize bodies arround point
I have a compound object, consisting of a b2Body, vector-graphics and a list polygons which describe the b2body's shapes. This object has its own transformation matrix to centralize the storage of transformations. So far everything is working quiet fine, even scaling works, but not if i scale around a point.

In the initialization phase of the object it is scaled around a point. This happens in this order:

1. transform the main matrix
2. transform the vector graphics and the polygons
3. recreate the b2Body

After this function ran, the shapes and all the graphics are exactly where they should be, BUT: after the first steps of the b2World the graphical stuff moves away from the body. When I ran the debugger I found out that the position of the body is 0/0

the red dot shows the center of scaling. the first image shows the basic setup and the second the final position of the graphics. This distance stays constant for the rest of the simulation.

If I set the position via

```
myBody.SetPosition( sx, sy );

```

the whole scenario just plays a bit more distant for the origin. Any Idea how to fix this?

EDIT::

I came deeper down to the problem and it lies in the fact that i must not scale the transform matrix for the b2body shapes around the center, but set the b2body's position back to the point after scaling. But how can I calculate that point?

EDIT 2 ::

I came ever deeper down to it, even solved it, but this is a slow solution and i hope that there is somebody who understands what formula I need.

assuming to have a set polygons relative to an origin as basis shapes for a b2body:

scaling the whole object around a certain point is done in the following steps:

1. i scale everything around the center except the polygons
2. i create a clone of the polygons matrix
3. i scale this clone around the point
4. i calculate dx, dy as difference of clone.tx - original.tx and clone.ty - original.ty
5. i scale the original polygon matrix NOT around the point
6. i recreate the body
7. i create the fixture
8. i set the position of the body to dx and dy

done!

So what i an interested in is a formula for dx and dy without cloning matrices, scaling the clone around a point, getting dx and dy and finally scale the vertex matrix.

# Answer
I finally write this post because I just got right now! All the differences between the shapes, the body, the save geometry and the graphical assets could not be wiped out with one transform matrix.

The final Idea which works just great was to use two matrices for the compound Object, one for translation and rotation and another for scaling. So in fact this first Matrix is actualized by the body in the following way:

```
function update(){
    var pos = this._body.GetTransform();
    var s = WorldController.scale;
    this._transform.set(
        pos.R.col1.x,
        pos.R.col1.y,
        pos.R.col2.x,
        pos.R.col2.y,
        pos.position.x * s,
        pos.position.y * s
    );
    draw.call( this );
}

```

and in the scale functions this happens:

```
function scale( sx, sy, center ){
    var s = WorldController.scale;
    this._body.SetActive( false );
    var c = center || null;
    if( c == null ){
        var local = this._body.GetLocalCenter();
        c = new paper.Point(
            local.x * s,
            local.y * s );
    }

    var x = sx || 1;
    var y = sy || sx;

    this._scale.scale( x, y, c );
    cleanFixtureList.call( this );

    makeFixture.call( this );

    this.queue( start );

}

```

and finally when drawing the objects this function comes into play:

```
function draw(){
    var t = this._transform;

    var test = t.clone().concatenate( this._scale.clone() );

    this._ahtml.draw( test );

    this._group._matrix.set(
        t._a, t._c, t._b, t._d, t._tx, t._ty );
    this._group._matrix.concatenate( this._scale.clone() )
}

```

this is working quiet good and is even faster than my first solutions. I know that there are still some redundant clone() calls and there might be another, better solution with only one matrix, but keeping in mind that box2d does not provide scaling, this adds it in a certain way.

How to finally resize the b2Body, i found here

Greetings, philipp
> 1 votes

---
Tags: box2d
---


title: XNA stopped compiling my model x files

text:
# Question
Title: XNA stopped compiling my model x files
So I've a 3d game project I'm working on and I'm using 2 model files (SkyBlock.x and AimedBlock.x).

So until now everything was all good and my models files were compiled all okay and I was able to use them within my game. With the latest changes (which I don't know what caused it really) - XNA stopped compiling my model files and instead only outputs files;

* AimedBlockxnb - 1kb
* SkyDome.xnb - 1kb
* SkyDomeTexture.xnb - 1389 kb
* SkyDomeTexture\_0.xnb - 419 kb

So I created a test XNA game project and moved all my asset's to new solution content project's and tried compiling them and saw that they're all good.

* AimedBlockxnb - 2kb
* SkyDome.xnb - 13kb
* SkyDomeTexture.xnb - 4097 kb
* SkyDomeTexture\_0.xnb - 683 kb

So I guess my main project sucks there but I couldn't came with a solution. I even tried overwriting my game's content project with new game's content project (which was all okay) but it didn't work.

Anybody had similar issues?

# Answer
> 1 votes
When you place content in your XNA project, in the **Properties** window you can pick the **Build Action** as well as how the file should be handled (**Content Importer** and **Content Processor**).

In your case, I expect those three properties were changed, but the defaults clearly work for you. The default for the Build Action is **Compile**, and the defaults for the Content Importer and Processor depend on the file format.

---
Tags: xna, models, xna-content-pipeline
---


# Question
Title: Do I need to implement IPv6 support for my game?
I'm going to implement network features for the game I'm currently working on, now I'm wondering if I need to implement IPv6 support or just having support for IPv4 is enough?

# Answer
Your question, as specified, is far too broad to be answered. The answer depends on knowing what you're actually *doing* with networking.

For example, if all of your networking is done over HTTP and similar protocols, then IPv6 support is sufficiently simple that it's not really a problem. You could probably slap it together in half a day or so. In this case, there's really no reason not to.

However, if you're doing peer-to-peer networking over UDP, where you're trying to squeeze every bit into each packet, then IPv6 is not a minor thing. It has a larger packet header than IPv4, out of necessity. So that means less room per-packet for your data. That can mean that you need to employ greater compression or re-evaluate how much data you send or whatever.

I will say this: you should leave the option available. Look at the design of your networking system and make sure that you're not doing something that will, from an architecture perspective, make IPv6 implementation harder than it needs to be.

IP addresses should be within a type that *could* store an IPv6 address, for example. Your interface to the socket layer should be abstract enough that the basic act of sending packets (if your app does that) will be the same over IPv6 as over IPv4.

IPv6 is coming, and if you're going to actually release a game with networking, at least having a *plan* to support it is a good idea.
> 13 votes

# Answer
Short answer for this particlual case would be "No". Long answer would be "Is it likely to determine your game's success or failure"? At the time then IPv6 support will be a must you can update it quite easily, isn't it?

If it's just a matter of personal interest you can absolutely try to implement IPv6 support. But, for me, it's better to spend that time on actually making game better.

P.S. I'm almost sure that most big major game manufacturers already include IPv6 support for their games, but that's another story.
> 2 votes

---
Tags: networking
---


# Question
Title: How to properly implement alpha blending in a complex 3D scene?
I know this question might sound a bit easy to answer but It's driving me crazy. There are too many possible situations that a good alpha blending mechanism should handle, and for each Algorithm I can think of there is something missing.

These are the methods I've though about so far:

* First of I though about object sorting by depth, this one simply fails because Objects are not simple shapes, they might have curves and might loop inside each other. So I can't always tell which one is closer to camera.
* Then I thought about sorting triangles but this one also might fail, thought I'm not sure how to implement it there is a rare case that might again cause a problem, in which two triangle pass through each other. Again no one can tell which one is nearer.
* The next thing was using depth buffer, at least the main reason we have depth buffer is because of the problems with sorting that I mentioned but now we get another problem. Since objects might be transparent, in a single pixel there might be **more** than one object visible. So for which object should I store pixel depth?
* I then thought maybe I can only store the most front object depth, and using that determine how should I blend next draw calls at that pixel. But again there was a problem, think about two semi transparent planes with a solid plane in middle of them. I was going to render the solid plane at the end, one can see the most distant plane. Note that I was going to merge every two planes until there is only one color left for that pixel. Obviously I can use sorting methods too because of the same reasons I've explained above.
* Finally the only thing I imagine being able to work is to render all objects into different render targets and then sort those layers and display the final output. But this time I don't know how can I implement this algorithm.

# Answer
**Short Answer**

Look into **depth peeling**. From my research it seems to be the best alternative, although computationally expensive because it requires multiple rendering passes. Here's another more recent and **faster implementation**, also by NVIDIA.

**Long Answer**

That is a *tough* question. Most books I've read skim over the subject and leave it at:

> Start by rendering all of the opaque objects and then blend the transparent objects on top of them in back-to-front order.

Easier said than done though, because the obvious approach of sorting objects by their centroids does *not* guarantee the correct sort order.

It's exactly the same problem why the painter's algorithm does not work for the general case and a depth buffer is needed.

With that said, one of the books I have mentions a few solutions:

* **Depth Peeling** \- a multi-pass solution which overcomes the depth buffer limitation by giving us the nth nearest fragments, not just the closest one. The biggest advantage is that you can render the transparent objects in any order, and there's no need to sort. It can be expensive because of the multiple passes but the link I gave at the top seems to improve performance.
* **Stencil Routed K-Buffer** \- Use stencil routing to capture multiples layers of fragments per pixel per geometry pass. The main disadvantage is that fragments need to be sorted in a post-processing pass.

It also mentions an hardware solution to the problem, but I don't think it's actually available:

* **F-Buffer** \- A Rasterization-Order FIFO Buffer for Multi-Pass Rendering. Nonetheless a good read and the introduction also talks a bit about the transparency sort order problem and the current solutions.

Other workarounds that don't provide perfect results but are better than nothing:

* After rendering all opaque objects, keep using Z-buffer testing for transparent objects but **disable Z-buffer writing**. You might get some artifacts from incorrect sorting but at least all transparent objects will be visible.

And quoting the F-buffer whitepaper above:

> The simplest solution is to render each partially transparent polygon completely independently (i.e. render all of its passes before proceeding to the next polygon). This solution is usually prohibitively expensive due to the state-change cost which is incurred. Alternatively, the application or shading library can group polygons to ensure that only non-overlapping polygons are rendered together. In most cases this solution is not attractive either, because it requires the software to perform screen-space analysis of polygons.
> 11 votes

# Answer
The correct answer is #1: sort all of your things by depth and render them (obviously turn off depth writing, but not testing). What is a "thing"?

Each "thing" must be a convex object; it cannot self-overlap. If you have an object that is concave, it must therefore be broken up into convex pieces.

This is **the** standard way of rendering a transparent scene. Does it solve interpenetrating cases? No. Does it solve cases where you have 3 objects where no depth order can be determined? No. Does it solve cases where you have a long object that overlaps with a small one that is closer in its center depth? No.

But it works *well enough*. Games do not use depth peeling. They do not use stencil routed k-buffers. They do not use F-buffers. Why? Because these things are incredibly slow.

You may get artifacts with the standard method. But at least your game runs reasonably fast.

If you're willing to restrict yourself to DX11 or better hardware, there are ways to implement blending with proper sorting. They're slower, but not nearly as slow as the previous techniques. And unlike depth peeling which can introduce artifacts, this one is sample-accurate. Plus, the performance of the algorithm is generally per-fragment (and to some degree per overlap within each fragment). So if you didn't draw a lot of transparent stuff, the performance is minimal.

I don't know if the technique has a spiffy name, but one implementation for pre-GL4.2 can be found here. A D3D11 version can be found here (Powerpoint, PPSX, Libre-compatible).
> 11 votes

---
Tags: 3d, blending
---


# Question
Title: Non-random enemy movement implementation
I would like to implement enemy movement on a X-Y grid. Would it be a good idea to have a predefined table with an initial X-Y position and a predefined "surveillance path"? Each enemy will follow its path until it detects a player, at this point it will start chasing the player using a chasing algorithm. According to a friend of mine this implementation is good because the design of a good path will provide to the user a sort of reality sensation.

# Answer
> 2 votes
It all depends on the kind of gameplay you want to achieve.

If you want a game that's all about finding the best strategy to finish a level, then this deterministic approach can fit very well, as accomplishing the same actions will always lead to the same results. Random behaviors could just be an annoyance for the player.

But if you want an action-oriented shooting game, you might want to introduce some randomness to give your game more replay value. If your game is all about aiming well and shooting fast, it can get boring to get the exact same enemy configuration for each play-through.

---
Tags: mmo, movement
---


title: DirectCompute information

text:
# Question
Title: DirectCompute information
I've been trying to make use of the GPU as part of a project of mine. I've looked into both CUDA and OpenCL, but the lack of information showing you how to introduce these into a project is shocking. Even their dedicated forum groups are dead. So now, I'm looking into DirectCompute.

From what I can tell, it's simply a new type of shader file that makes use of HLSL. My question is this, does my program (aside from being DirectX 10 / 11 ) need its structure changed?

I mean, is it simply a case of creating the CS file, setting in the project like I would any other shader, and watch the magic happen?

Any information on this would be appreciated.

# Answer
> 1 votes
Yes, you initialize it like every other shader type using it's specific CreateComputeShader call with the device handle. And you bind it and it's required resources just like every other shader type being executed.

Now the important thing is to understand the threading model. You need to establish how you want to distribute your computation across threads. And then how many threads you want per a thread group and then finally how many thread groups to dispatch with the device context on the CPU.

The number of threads per a thread group is declared in the shader file. It's also important to note that you logically distribute the thread groups and threads across a three dimensional array. So if I were to dispatch (2, 8, 1) thread groups where the shader declares each thread group as (1, 8, 1) threads. This would execute 128 instances of the kernel.

Some other important things to note, buffers that are going to be written to within the compute shader must be bound as unordered access views to the pipeline while read only buffers can be bound as a resource views. There are also some nifty new buffer features. An important one to note are the Append/Consume buffers. These allow you to pop and push data to and from a buffer with out having to worry about synchronization with other threads.

For general synchronization, compute shaders offer some atomic functions and what are called memory barriers. Memory barriers are essentially synchronization mechanisms for shared memory among thread groups.

Also some peformance tips, minimize context switching of the pipeline from computational use to standard rendering use. Also avoid having to read data from the GPU as much as possible. Locking and reading buffers from the CPU is expensive.

# Answer
> 1 votes
The overall structure of the program will be similar to that of a graphics application. You'll need to initialize Direct3D the same way and load / set up all your shaders/buffers/textures the same way. You'll call the Dispatch method to kick off a compute shader job, instead of one of the Draw methods.

# Answer
> 0 votes
These videos will help you get started using DirectCompute I suggest you don't skip the first couple of videos as they cover important concepts about the GPU and the threading model as pointed out by KlashnikovKid and Nathan Reed.

---
Tags: directx, gpgpu
---


# Question
Title: What are the valid DepthBuffer Texture formats in DirectX 11? And which are also valid for a staging resource?
I am trying to read the contents of the depth buffer into main memory so that my CPU side code can do Some Stuff™ with it.

I am attempting to do this by creating a staging resource which can be read by the CPU, which I will copy the contents of the depth buffer into before reading it. I keep encountering errors however, because of, I believe, incompatibilities between the resource format and the view formats.

Threads like these lead me to believe it is possible in DX11 to access the depth buffer as a resource, and that I can create a resource with a typeless format and have it interpreted in the view as another, but I cannot get it to work.

**What are the valid formats for the resource to be used as the depth buffer?** **Which of these are also valid for a CPU accessible staging resource?**

# Answer
The valid formats for typeless Direct3D11 depth buffer are:

```
DepthStencilBuffer: DXGI_FORMAT_R16_TYPELESS (instead of typical DXGI_FORMAT_D16_UNORM)
DepthStencilBufferView: DXGI_FORMAT_R16_FLOAT

DepthStencilBuffer: DXGI_FORMAT_R32_TYPELESS (instead of typical DXGI_FORMAT_D32_FLOAT)
DepthStencilBufferView: DXGI_FORMAT_R32_FLOAT

DepthStencilBuffer: DXGI_FORMAT_R24G8_TYPELESS (instead of typical DXGI_FORMAT_D24_UNORM_S8_UINT)
DepthStencilBufferView: DXGI_FORMAT_R24_UNORM_X8_TYPELESS

DepthStencilBuffer: DXGI_FORMAT_R32G8X24_TYPELESS (instead of typical DXGI_FORMAT_D32_FLOAT_S8X24_UINT)
DepthStencilBufferView: DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS

```

Using this format when declaring a depth stencil buffer, you should be able to copy the depth buffer to another R16\_FLOAT/R32\_FLOAT...etc. texture.

On a side note, it is often not recommended to read back data on the CPU because of the latency that will be introduced. Current techniques - on Windows Direct3D11 - tend to perform typical CPU computation on the GPU with DirectCompute.
> 5 votes

---
Tags: directx11, depth-buffer, sharpdx
---


title: What are game save files?

text:
# Question
Title: What are game save files?
I've reached the saving part of my game, as in, you press save and it writes to a text file, but I've noticed that most games and programs out there use custom save formats, like Dwarf Fortress DAT files. What are these? are these just text files formatted for the program, or are they a lower level thing?

# Answer
> 6 votes
Many games use a proprietary format for saving data, which they serialize in either plain text or binary form. The format of that data is entirely up to the game, as is the extension the author chooses to use (if one is chosen at all).

That said, all the extensions you've listed probably aren't saved game data at all, because they all have canonical uses elsewhere. PPT and PPTX are usually PointPoint slide decks, JPG and JPEG are image files, and KEY, while less of a de-facto standard, sounds more like a file used to store license key information or something rather than game data.

---
Tags: savegame
---


# Question
Title: How can I generate a texture that looks like left-over tea leaves?
We are working on a project for iPhone and Windows Phone 7 where we'd like to be able to generate tea leaves at the bottom of a cup. It doesn't have to look photo-realistic, and actually cartoon-y is ok.

What sort of techniques should we research to accomplish this? Are there any libraries (preferably in C, but we can translate) that would be helpful?

Here are some samples pulled from a Google Image search

# Answer
How I'd probably do it so I could maintain some art control and not potentially spend a long time trying to tweak a procedural method to get it just right...

First, manually create a number of sprites of tea leaf clumps as your art "pool" - not each as an entire cup's worth of tea leaves, but more like a smaller grouping. Say, 20 of them or so?

Then place a random number of them at random coordinates on the "cup" base. Give each a random rotation and scale plus random horizontal and/or vertical mirroring. This ought to create a good result.

This approach will give you the artistic freedom in creating the individual clumps to have the look you want, while allowing for a huge variety of results (assuming sufficient sprites to choose from).

Additionally, with this (and any random method including Perlin noise based), you could actually seed the random number generator at the start of the process with a known seed to make reproducible results. If you save the seed, you are able to exactly recreate the same pattern again by reseeding just before the sequence starts. You could even do fun things like have someone type in their name, turn the letters into a number (sum ASCII, etc.), then use that as the seed as some kind of "this tea leaf pattern customized for YOU!" thing.

Here's some pseudocode for what I mean, if that helps...

```
var sprites = [...]; // Array of tea leaf sprites

var n_leaves = rand(5)+5; // Random number of leaves from 5-9
for (i=0; i<n_leaves; i++) {
    var sprite_index = rand(sprites.length);  // Random sprite index
    var r = rand(CUP_DIAMETER);          // Random radius for point on disk calc
    var theta = rand(2*PI);              // Random theta (rotation) for point on disk
    var sprite_x = sqrt(r) * cos(theta); // Sprite X
    var sprite_y = sqrt(r) * sin(theta); // Sprite Y
    var sprite_rotation = rand(2*PI);    // Sprite rotation
    var sprite_scale = rand(1) + 0.5;    // Sprite scale from 0.5 to 1.5
    var sprite_h_mirror = (rand(1) < 0.5 ? true : false); // If true, mirror horizontally
    var sprite_v_mirror = (rand(1) < 0.5 ? true : false);   // If true, mirror vertically
    draw_sprite(sprite_index, sprite_x, sprite_y, sprite_rotation, sprite_h_mirror, sprite_v_mirror);
}

```

Check out http://mathworld.wolfram.com/DiskPointPicking.html for a great discussion about how to pick a random point in a disk and why I am using that whole sqrt/sin/cos thing.
> 15 votes

# Answer
Try perlin noise with a binary cutoff value of 0.8 or so?

Uploaded example image to https://i.stack.imgur.com/nepNF.jpg . The first is the second image with a threshold applied. The second is basic perlin noise, for which you can find multiple good references such as http://en.wikipedia.org/wiki/Perlin\_noise and http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter26.html .

You can play a bit with the number and scale of octaves in the perlin noise to vary how smooth the output will look, as well as the threshold to determine how much (on average - as it's noise) tea leaves there will be.
> 7 votes

---
Tags: textures, c
---


title: Bone creation in XNA Content Pipeline

text:
# Question
Title: Bone creation in XNA Content Pipeline
I'm trying to manually create a `ModelContent` instance that includes custom Bone data in a custom `ContentProcessor` in the XNA Content Pipeline. I can't seem to create or assign manually created bone data due to either private constructors or read-only collections (at every turn).

The code I have right now that creates a single triangle `ModelContent` that I'd like to create a bone for is:

```
MeshContent mc = new MeshContent();
mc.Positions.Add(new Vector3(-10, 0, 0));
mc.Positions.Add(new Vector3(0, 10, 0));
mc.Positions.Add(new Vector3(10, 0, 0));

GeometryContent gc = new GeometryContent();
gc.Indices.AddRange(new int[] { 0, 1, 2 });
gc.Vertices.AddRange(new int[] { 0, 1, 2 });
mc.Geometry.Add(gc);

// Create normals
MeshHelper.CalculateNormals(mc, true);

// finally, convert it to a model
ModelContent model = context.Convert<MeshContent, ModelContent>(mc, "ModelProcessor");

```

The documentation on XNA is amazingly sparse. I've been referencing the class diagrams created by DigitalRune and Sean Hargreaves blog, but I haven't found anything on creating bone content.

Once the `ModelContent` is created, it's not possible to add bones because the `Bones` collection is read-only. And it seems the only way to create the `ModelContent` instance is to call the standard `ModelProcessor` via `ContentProcessorContext.Convert`. So it's a bit of a catch-22.

The `BoneContent` class has a constructor but no methods except those inherited from `NodeContent`... though now (true to form) maybe I've realized the solution by asking the question. Should I create a root `NodeContent` with two children: one `MeshContent` and one `BoneContent` as the root of my skeleton; then pass the root `NodeContent` to `ContentProcessorContext.Convert`?

# Answer
Solved!

A bone will be created for each `NodeContent` whether it is a `BoneContent` or a `MeshContent`. In the former case, it appears the intention of the `BoneContent` class is simply to indicate that the node is a bone *only*. The bone hierarchy at runtime will match this build time `NodeContent` hierarchy.

In my simple case, the solution was simply

```
MeshContent mc = new MeshContent();
... create mesh ...

mc.Transform = Matrix.CreateTranslation(0,10.0f,0);

// NOTE: type parameter has changed from MeshContent to NodeContent
ModelContent model = context.Convert<NodeContent, ModelContent>(mc, "ModelProcessor");

```

which creates a single bone at runtime. For a more complicated hierarchy I could do something like:

```
BoneContent turtle = new BoneContent();
MeshContent body = new MeshContent();
MeshContent head = new MeshContent();
MeshContent eye = new MeshContent();

turtle.Children.Add(body)
body.Children.Add(head);
head.Children.Add(eye);

head.Transform = ...;
body.Transform = ...;
eye.Transform = ...;

// create the one-eyed turtle
ModelContent model = context.Convert<NodeContent, ModelContent>(turtle, "ModelProcessor");

```

which would have 4 bones at runtime arranged in the chain: `turtle->body->head->eye`.

To assist in debugging, I found it useful to set the `Name` property (from `ContentItem`) at build time, then check `Model.Root.Index` and `Model.Root.Name` against the `Model.Bones` list.
> 4 votes

---
Tags: xna, xna-content-pipeline, skeletal-animation
---


# Question
Title: Why does my FPS drop gradually over time?
I'm working on this game: yt alpha preview

I came into a huge game-breaking problem - after 10-15 min of gameplay the FPS drops from 60 to 30 and is very unstable. I'm using tons of physics and particles, I'm deleting and nulling everything I can after it's supposed to be removed, I remove objects from vectors etc. The memory usage is stable at around 150mb so a leak is unlikely (or invisible?)- after a round ends and I delete everything, play a new round and performance is still terrible. I spent two days trying to figure this out and I just can't fix it. Maybe I'm missing something? I know it's hard to help with no code but I would just have to post my whole source.

# Answer
> 14 votes
Flash garbage collector doesn't work very well, nor its destructors do a good job of actually destroying things either.

Even if your code is correct and shouldn't leak, Flash might mess it anyway.

Try to allocate the bare minimum of things you actually need, and instead of destorying and recreating them, just recycle them.

# Answer
> 4 votes
I managed to fix it with a profiler (the miner). I had b2vec2 and sprite leaks.

GC won't gather if you keep references to objects so just make sure you have a destructor in your custom classes, delete and null everything you can. Most of all if you use big libraries such as box2d make sure you null even local vars. With bitmap data use `bmpdat.dispose();` and null it. Thanks to this I'm using around 30-40mbs less and the game is stable and fluid for many rounds.

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


# Question
Title: How to program a cutting tool for 3D model in game
I'm looking for a resource to figure out how to program a function to cut a 3d model in game.

Example: Enemy/NPC is sliced into 2 pieces with a sword. His body is not hollow, you can see bloody texture where normally a 'polygon hole' would be.

The first step is to actually 'cut/slice' the model, then add in polygons to fill the hole in the model. I know this can be done in 3D modelling software, but I'm not sure how to go about doing this in a game, code-wise. I do not wish to use 'pre cut-up" models, the code will determine where the cut is.

Any pointers in the right direction would be greatly appreciated.

# Answer
> 2 votes
What you want to look for are techniques for doing Constructive Solid Geometry, CSG for short. CSG isn't particularly hard (although numerical border cases might cause some trouble), but doing it in realtime isn't trivial.

Sander van Rossen writes interesting stuff about the datastructures he used for his particular implementation. His approach might be more approriate for animated character models than the standard BSP representation often used in non-realtime CSG.

A solid open implementation of rendering CSG objects is OpenCSG.

---
Tags: 3d, graphics, software-engineering, models, effects
---


# Question
Title: Looking for articles/books on: How do games make money? What models do they use?
I'm trying to research the ways in which games make money. I want to know more about the models they use (free/premium, trial/subscription, free-to-play with micro-transactions, etc.). In addition, I want information on which models work for which games, what models are best for which age groups, etc.

I've tried my best to find information, and Google hasn't turned anything up at all. I think I'll stop by my University's library and see if there's anything there.

This may seem like a broad question, but I'm looking for links and titles of books, not typed-out answers.

# Answer
> 24 votes
The main models I can think of are:

* Charge per copy - the traditional "software licensing" model, you charge your customers a retail price to "buy" a copy of the software and the subsequent right to install or play it. This is still a dominant model for software of all kinds including PC, console and mobile device games, even after the introduction of other feasible models. Games of all genres from FPS to MMO to arcade and puzzle games use this model to great effect, but it's probably the least accessible method to the average one-man dev house.
* Monthly subscription - The next most popular licensing model, regardless of what the software initially costs the user, they sign up for access to dynamic content on a monthly basis. This can be combined with an initial software price. MMOs are the foremost genre that benefits from this and there are a lot of examples; however, there are a lot of MMOs that do NOT charge a monthly subscription fee. Guild Wars is the one that comes to mind, because I played it specifically because it wasn't WoW.
* Microtransactions - This is a relatively new model, first seen in MMOs and then spread to "social apps" a la Facebook. The idea is that the program may be free to install, free to play, but to get the "most" out of your game experience (or to progress quickly within the game) you can spend real money to buy in-game objects. The first I heard of this kind of thing, it was underground; Diablo 2 and WoW players would "grind" through dungeons constantly, acquiring rare items, that they'd then sell on eBay for real money with the trade consummated in-game. Blizzard cracks down on trades for real money between players pretty hard, but other game devs have embraced the concept for their own gain. Entropia allows users to deposit *and withdraw* money from the virtual world, and people actually make a living in the real world by running in-game businesses. Even Blizzard allows you to buy in-game gold with real money (but you can't "cash out" like in Entropia, and there are certain things that you'd be hard-pressed to spend any amount of gold to buy). Similarly, Facebook apps are a HUGE cash cow, with companies like Zynga and Maxis offering titles like Farmville and Sims Social where normal play is free, but you can pay for virtual objects to spruce up your little corner of the game (often, paying real money is the only way to acquire certain highly-desirable items).
* Pay-per-play - Very point-of-sale-based gaming. Your customers pay you for a finite unit of play. Obviously arcade games are the first thing that comes to mind, but the model generally holds for online casinos, video poker machines, etc. However those are the main genres of games that use this model effectively; most users would balk at a game they download to their phone or XBox that charges their account based on the number of times they play it. However, pay-per-use is a valid model for certain other mobile device apps, such as for navigation, song identification, etc etc.
* Ad-based - A lot of mobile device games are monetized using this model. Free to install, free to play, but the game display features product placement for which advertisers pay the rights holders. This can be straight up ad displays along the top or bottom of the screen, or it can be more subtly integrated into the game; an MMO based in the present-day or near-future might put real ads on "billboards" and charge advertisers for the online billboard space much like a real-world billboard owner would do. Basically any game with "real estate" that can be devoted to ads without disrupting gameplay would benefit from it. It's really taken off with mobile devices, as previously mentioned, because you as a game dev can put your work in the app store free for the downloading, but still make money. Certain genres like FPSes are less effective with an in-game ad model, as a dedicated place in the "HUD" for ads must be out of the way by necessity, and players are focused more on other players than background elements like an ad banner as a texture on a wall in the map. But, things like loading screens become a natural place for ads, because the user is just watching and waiting and so is a pretty captive audience for a full-screen ad panel.
* Provider billing - You can make money from a game by selling it not to an end user, but to a provider who will then offer it to the end user using their own model (usually pay-per-play, but they may absorb the cost). Usually this is in the form of an arcade game that you sell to a business owner, who will drop it into their store as a change-catcher. However, the model may also work as a "drop-in" to an online website (as an embedded object, most likely a very simple puzzle game), by charging people who host game servers (beyond the cost of a license for the game server) or as a "benny" for subscribed users of some other service (sign up for Dish Network and get unlimited access to our MMO from your TV or a PC with an Internet connection). This would generally work for dynamic-content games like MMOs, and also for very simple "applets" that web portal companies can drop into their site as an amusement for a nominal per-play fee, or for free. However, there has also been money made in charging by the hour for access to retail games, with multiplayer environments hosted on private servers.

These are the models most suited to game development that allow you to profit from the game itself. However, there are other ways to profit from the IP of that game:

* Merchandising - Doom, Quake, Mario, Zelda, Donkey Kong, Sonic, Sephiroth, even the Angry Birds are available on T-shirts, action figures, plushies, and in myriad other forms besides. Regardless of who makes the product, the owner of the IP is compensated for every item made in which the IP has been used.
* Code Licensing - Valve Ltd got its start by buying rights to use the Quake II game engine from Id Software, then programming Half-Life around it. Valve now has their own engine (with the embedded Havoc physics engine licensed from another dev house) and are where Id was a decade ago, licensing use of the Source engine to developers who've used it for everything from other FPSes to arcade games to racing simulations. This is the primary way to monetize computer code other than licensing its end-use as a game program.
* Sponsorships - Sponsored play events such as mass demos and tournaments are yet another way that money can be made from a game. The IP holders of the game(s) played during the event are, of course, entitled to a substantial cut of sponsor dollars. Usually, this is secondary to selling the game itself; the event is either a promo for the game prior to or at its release, or an incentive for people to buy and play the game (to get good so they can win the tourney). The majority of money made by the IP holder is thus made before or after such an event.

# Answer
> 9 votes
For some actual stats, here is a detailed survey conducted on Flash games in 2009: http://wiki.mochimedia.com/w/page/15156195/Flash%20Games%20Market%20Survey

You' probably be only interested in some of the slides like below though (slide 18).

# Answer
> 6 votes
Although it is meant for software selling in general and not just only games, I found this book very useful and clear (and it's free!): Don't just roll the dice, by Neil Davidson (He also has other free books which may be worth reading).

# Answer
> 2 votes
I'm not sure about books on this but, there are plenty of MMORPGs that have gone from a pay to play model to a free to play model and have tripled even quadrupled the number of players they have on the game. I'm sure if you could find the games that have gone from P2P to F2P they will have numbers somewhere on their site of their success.

Here is the only list I could find of games gone from P2P to F2P(keep in mind it is a bit oudated and there are many more games that have done this):

http://mmohuts.com/editorials/pay-to-play-gone-free-to-play

As for age ranges it's pretty much self explanatory that F2P audiences are going to generally be a bit younger than P2P based on the fact that children don't have income. Again no real evidence on this.

I know Aion is an mmorpg that was P2P and is going F2P on April 11, 2012.

Games like Maple Story were very successful with micro transactions. Solely based on the ratio of P2P games to F2P games, F2P seems the more successful. Like I said the only real way to back this up is to look at the increase of subscribers games get when they go F2P.

---
Tags: game-industry, marketing, monetization
---


title: Multiple buffering in OpenGL on Windows

text:
# Question
Title: Multiple buffering in OpenGL on Windows
1. What is the most common way modern games perform triple buffering ?
2. What does the SwapBuffers exactly do in terms of OpenGL states ?
3. Is it possible to perform double and triple buffering independently of window system (for example, by manipulating with glDrawBuffer or by using FBO/PBO) ? If so, any hints ?
4. Does 3. even make sense in terms of performance and flexibility ?

# Answer
This quote answers most of your questions:

> You cannot control whether a driver does triple buffering. You could try to implement it yourself using a FBO. But if the driver is already doing triple buffering, your code will only turn it into quadruple buffering. Which is usually overkill.

http://www.opengl.org/wiki/Common\_Mistakes#Triple\_Buffering

> What does the SwapBuffers exactly do in terms of OpenGL states ?

From what I understand, it doesn't really do anything other than flushing GL and swapping the buffers.
> 3 votes

---
Tags: c++, opengl, performance, winapi, double-buffering
---


title: When does depth testing happen?

text:
# Question
Title: When does depth testing happen?
I'm working with 2D sprites - and I want to do 3D style depth testing with them. When writing a pixel shader for them, I get access to the semantic DEPTH0. Would writing to this value help? It seems it doesn't. Maybe it's done before the pixel shader step? Or is depth testing only done when drawing 3D things (I'm using SpriteBatch)? Any links/articles/topics to read/search for would be appreciated.

# Answer
Depth testing, according to the description of modern 3D pipelines, is done after the pixel shader, which is why Direct3D provides the `DEPTH` output semantic and OpenGL provides the `gl_FragDepth` built-in variable that allow you to *change* the value against which depth testing is performed.

However, it's kind of a waste of precious GPU processing power to shade a pixel and then throw it out because it's behind an object that we already knew was there, particularly if the pixel shader *doesn't* change the Z value. This is the idea behind the **Early-Z** optimization, where if you're rendering a pixel whose pixel shader *doesn't* change the depth, the hardware may never actually run the pixel shader (or, more likely, if a full 2x2 quad of pixels is occluded, then none of them will be run through the pixel shader). This is why you want to render a fully-opaque scene from front to back.

This leads into *another* almost universally-implemented optimization called hierarchical Z-culling, or **Hi-Z**. The idea here is that the hardware can keep lower-resolution conservative depth buffers around and throw out huge chunks of pixels at once if it knows that all those pixels are occluded by pixels currently in the depth buffer (by knowing the "rearmost" depth over large regions of the depth buffer). This process is not unlike mipmapping, but it keeps the *maximum* (or most permissive) depth value instead of the *average* one.

Neither of those optimizations are available if you change your output depth in the pixel shader, so for 3D scenes doing so is discouraged. However, both Direct3D and OpenGL have a "conservative depth output" feature that is intended to let you change the depth and still let the GPU do its optimization (this is `SV_DepthGreater`, `SV_DepthLessEqual`, and friends in Direct3D 11 and ARB\_conservative\_depth in OpenGL). The idea there is that you're allowed to change the depth as long as you make some promise about it: i.e. "my altered depth is always less than the original depth." If you promise never to bring an object forward in the scene, the GPU can throw out pixels that are definitively behind another object because it knows your pixel shader won't screw everything up.

All this is intended to say that you should be careful when changing a pixel's depth. In 2D most of the culling-related implications probably won't affect you very much, so you're probably in the clear. But you should be aware that when pipeline descriptions say that the depth test happens *after* the pixel shader, they're only telling part of the truth.
> 8 votes

# Answer
In the traditional render pipeline, depth testing occurs between the stencil and blending steps of fragment processing (source). Usually it's something that can only be taken control of via state variables (at least in OpenGL), and I must admit that I'm not as familiar with the pipeline of XNA.

I guess what I'm trying to get at is the depth-buffer corresponding to the active frame-buffer is not typically something that is part of the programmable graphics pipeline. Several techniques will usually fill the depth-buffer in one pass and access it as a texture in a second pass.

To sum up, depending on how you draw your primitives, it may already be done for you.
> 1 votes

# Answer
Depth testing happens in what is known as the merging stage *after* the pixel shader (also check this link). There's however an optimization technique called the "Early-Z Test" which is available in some graphic cards, and it consists of moving the check before the pixel shader so that it can be skipped completely for occluded fragments.

As for whether you can modify the depth value of a fragment in the pixel shader, yes you can and this source confirms it. although I'm not sure how to use it correctly. Quoting:

> The DEPTH output semantics can be used to change the destination depth value at the current raster location.

As for your confusion regarding 3D, you should know that the `SpriteBatch` class also works with 3D behind the scenes. It's basically generating two triangles (i.e. one quad) for each of your draw calls.

Finally, I think what you're trying to achieve is usually done in another way, by using deferred rendering, where you'll also need an heightmap (and a normal map if you intend to do lighting) for each for your sprites. Check this amazing video example of the technique. I used to see an article with an implementation of the technique but I can't seem to find it at the moment. The video does state at one point "Writing the heightmap to the depth buffer allows for objects to intersect in 3D" which might be a useful hint.
> 1 votes

---
Tags: xna, xna-4.0, depth-buffer
---


title: How to make a scrolling background

text:
# Question
Title: How to make a scrolling background
I'm making a Shooter game like "1943" and "Jamestown". I am Using Visual Basic 2010. I was wondering how I would make the background scroll up to simulate moving forward. I would also like it to scroll slightly to the left and right when the player reaches the sides of the screen. Finally, how would I make this efficient? I was thinking about using a animated GIF or making a looping BitMap. Please could someone help me out?

# Answer
> 4 votes
The backgrounds in Jamestown are *not* looping bitmaps, because they are always changing from the start of the level to the end.

But if you only need a looping bitmap, and you only need it to loop vertically, the **easiest** way I know is the following (cross reference with the image below):

1. Draw the background *twice*, stacked vertically like on the image below. Of course the image you use must be seamlessly tileable. The red rectangle represents your screen.
2. Start moving both background instances down. You do this by adding some value to their vertical position each frame.
3. When they reach the position represented in the image (e.g. when `topBackground.Y >= 0`), subtract one background height from each of their vertical positions to bring them back to step 1.
4. Repeat.

There are more complex ways of handling the problem depending on whether you need to loop horizontally and vertically at the same time, or if you need to zoom and rotate the background. You can use these as reference if needed, although I'm not sure how you'd translate it to your platform:

# Answer
> 0 votes
I would suggest against an animated GIF (at least to implement scrolling).

Instead, start with getting a single image onto the screen via whatever framework, technology stack or methodology you're most familiar with (or seems to make the most sense). e.g. WinForms, WPF, GDI+, XNA, HTML 5 Canvas.

Once you done this, start on making it move over time. There are quite a few ways to achieve this but most come back to the idea of incrementing the position by a small amount at regular intervals. (In XNA, its done in the Update Method. In Winforms and WPF it's done via the addition of a timer.)

After achieving this, you just need to extend the idea to an entire grid of images moving in a particular direction. There are various approaches to deal with the fact that your arena of play is probably going to be a lot larger than the screen... but best not to stress about these bridges until you actually need to cross them.

---
Tags: game-mechanics
---


# Question
Title: Need to make animation whereby the character shatters into a bunch of pieces
I would like to take a 3d character model, cut out a bunch of shapes (or a bunch of triangles in the shape of the pieces I want) and then have the pieces separate from each other at the beginning of the animation and fall apart with gravity so it looks like the model is falling apart in shattered pieces.

Is there a way to run a script on a mesh, cut out these pieces, instantiate all of them as separate models and then run gravity on them during the simulation?

# Answer
> 1 votes
Option a) have your 3d artist cut up suitable chunks for you, and disperse them at will. This will still demand a lot of work getting the pieces to do what you wish them to do. Make it look reasonably good without all the fuss. Slice the characters up in as many ways as you have attacks : horizontal, vertical, diagonal splits whatever, maybe even have them preanimated. Or you can have the bits drop around like particles. If you want every piece realistically floppy, prepare for lots of work.

Option b) make some fairly challenging code to cut the mesh at specific points, and separate pieces into objects that fly out. This is not perhaps not worth the effort, though it may look pretty cool.

( Apologies for slack first answer which simply suggested taking the easy way out. )

---
Tags: animation, character, dynamic-mesh
---


title: Corona SDK Continuous Integration

text:
# Question
Title: Corona SDK Continuous Integration
Is it possible to build corona applications from console?
Or how can I automate build process?

# Answer
I don't think this is possible, since apps are built only via the Corona client application - your source actually gets sent to Corona's server where it is built, then sent back to you as a packaged application. See Building your App using Corona for more info.
> 2 votes

---
Tags: corona-sdk
---


# Question
Title: How to correctly export UV coordinates from Blender
Alright, so I'm just now getting around to texturing some assets. After much trial and error I feel I'm pretty good at UV unwrapping now and my work looks good in Blender.

However, either I'm using the UV data incorrectly (I really doubt it) or Blender doesn't seem to export the correct UV coordinates into the obj file because the texture is mapped differently in my game engine. And in Blender I've played with the texture panel and it's mapping options and have noticed it doesn't appear to affect the exported obj file's uv coordinates.

So I guess my question is, is there something I need to do prior to exporting in order to bake the correct UV coordinates into the obj file? Or something else that needs to be done to massage the texture coordinates for sampling. Or any thoughts at all of what could be going wrong?

(Also here is a screen shot of my diffused texture in blender and the game engine. As you can see in the image, I have the same problem with a simple test cube not getting correct uv's either)

Edit -

Added my geometry pass shader source code to show how I'm rendering and sampling the diffuse texture. I'm simply using the UV coordinates provided by the obj file and an anisotropic sampler.

```
Texture2D    diffuseTexture : register(t0);
SamplerState textureSampler : register(s0);

cbuffer ObjectTransformBuffer : register(b0) {
    float4x4 worldTransformMatrix,  // Translates to world space.
             cameraTransformMatrix; // Translates to camera space. (not including rotation)
};

cbuffer ScreenTransformBuffer : register(b1) {
    float4x4 viewProjectionMatrix; // Rotates to camera space and then projects to screen space.
}

cbuffer MaterialBuffer : register(b2) {
    float3 materialDiffuseAlbedo;
    float  materialSpecularExponent;
    float3 materialSpecularAlbedo;
    bool isTextured,
         isLighted;
};

struct vsInput {
    float3 positionLS : POSITION;
    float3 textureLS  : TEXTURE; // Input signature uses a uvw coordinate but w is 0 and not needed for any geo pass textures.
    float3 normalLS   : NORMAL;
};

struct vsOutput {
    float4 positionCS : SV_POSITION;
    float2 textureLS  : TEXTURE;
    float3 normalWS   : NORMAL;
    float3 positionWS : POSITION;
};

struct psOutput {
    float4 positionWS : SV_Target0;     // Surface positions.
    float4 normalWS   : SV_Target1;     // Surface normals.
    float4 diffuseAlbedo : SV_Target2;  // Surface diffuse albedo.
    float4 specularAlbedo : SV_Target3; // Surface specular albedo.
};

vsOutput VS( in const vsInput _in ) {
    vsOutput _out;

    _out.positionCS = mul(float4(_in.positionLS, 1.0f), mul(cameraTransformMatrix, viewProjectionMatrix));
    _out.positionWS = mul(float4(_in.positionLS, 1.0f), worldTransformMatrix).xyz;
    _out.normalWS   = mul(float4(_in.normalLS, 0.0f), worldTransformMatrix).xyz;
    _out.textureLS  = _in.textureLS.xy; // w coordinate is 0 and not needed.

    return _out;
}

psOutput PS( in vsOutput _in ) {
    psOutput _out;

    // Use the alpha channel to indicate specular light intensity.
    _out.normalWS = float4(normalize(_in.normalWS), materialSpecularExponent);

    float _lightEffectModifier;
    if (isLighted)
        _lightEffectModifier = 1.0f;
    else _lightEffectModifier = 0.0f;
    // Use the alpha channel to indicate whether the surface is affected by light for the light pass.
    _out.positionWS = float4(_in.positionWS, _lightEffectModifier);

    _out.diffuseAlbedo = float4(materialDiffuseAlbedo, 1.0f);
    if (isTextured)
        _out.diffuseAlbedo *= diffuseTexture.Sample(textureSampler, _in.textureLS.xy);

    _out.specularAlbedo = float4(materialSpecularAlbedo, 1.0f);

    return _out;
}

```

# Answer
Alright, found my issue. Not sure if this applies to OpenGL but for my DirectX application I needed to invert the v coordinate for sampling the texture.

```
u = u
v = 1 - v;

```
> 5 votes

---
Tags: textures, blender, uv-mapping
---


# Question
Title: Calculating a circle or sphere along a vector
**Updated this post and the one at Math SE (http://math.stackexchange.com/questions/127866/calculating-a-circle-or-sphere-along-a-vector), hope this makes more sense.**

I previously posted a question (about half an hour ago) involving computations along line segments, but the question and discussion were really off track and not what I was trying to get at. I am trying to work with an FPS engine I am attempting to build in Java.

The problem I am encountering is with hitboxing. I am trying to calculate whether or not a "shot" is valid.

I am working with several approaches and any insight would be helpful. I am not a native speaker of English nor skilled in Math so please bear with me.

Player position is at P0 = (x0,y0,z0), Enemy is at P1 = (x1,y1,z1). I can of course compute the distance between them easily. The target needs a "hitbox" object, which is basically a square/rectangle/mesh either in front of, in, or behind them.

Here are the solutions I am considering:

1. **I have ruled this out...doesn't seem practical.** \[Place a "hitbox" a small distance in front of the target. Then I would be able to find the distance between the player and the hitbox, and the hitbox and the target. It is my understanding that you can compute a circle with this information, and I could simply consider any shot within that circle a "hit". However this seems not to be an optimal solution, because it requires you to perform a lot of calculations and is not fully accurate.\]
2. **Input, please!** Place the hitbox "in" the player. This seems like the better solution. In this case what I need is a way to calculate a circle along the vector, at whatever position I wish (in this case, the distance between the two objects). Then I can pick some radius that encompasses the whole player, and count anything within this area a "hit".
3. I am open to your suggestions. I'm trying to do this on paper and have no familiarity with game engines. If any software folk out there think I'm doing this the hard way, I'm open to help!

Also - Anyone with JOGL/LWJGL experience, please chime in.

Is this making sense?

# Answer
> 2 votes
> Player position is at P0 = (x0,y0,z0), Enemy is at P1 = (x1,y1,z1). I can of course compute the distance between them easily. The target needs a "hitbox" object, which is basically a square/rectangle/mesh either in front of, in, or behind them.

The hitbox should always be 'inside' the target and depending on how hard you want it to be the hit something it should totally encompass the target or be slightly smaller than the target.

Now you have a hitbox and a bullets firing in the direction of the hitbox. What you need to do is calculate if a ray, following the path of the bullets, will intersect with the hitbox. This is a very well documented problem.

You can find all sorts of math and source code here for X-\>Y intersection: http://www.realtimerendering.com/intersections.html

See that you can also use sphere's (very easy) cylinders and other primitives to test if a bullet hit the target.

Finally I would like to point out that you don't need to limit your self to one bounding primitive per object. Often it's a better fit to use multiple and check against each one of them:

You should also look at this question: Best/Efficient way to implement a 3d Collision

After you have the basic collision detection algorithms implemented and things seem to get slow when there are many collidable objects in the scene you should look up spatial partitioning and octrees.

---
Tags: graphics
---


# Question
Title: How can I render player movement on a 2d plane efficiently?
I'm prototyping a 2d HTML5 game with similar interaction to Diablo II. (See an older post of mine describing the interaction here: How can I imitate interaction and movement in Diablo II?)

I just got the player click-to-move system working using the Bresenham algorithm but I can't figure out how to efficiently render the player's avatar as he moves across the screen. By the time redraw() is called, the player has already finished moving to the target point. If I try to call redraw() more frequently (based on my game timer), there's incredible system lag and I don't even see the avatar image glide across the screen.

I have a game timer based off this awesome timer class: http://www.dailycoding.com/Posts/object\_oriented\_programming\_with\_javascript\__timer\_class.aspx

In the future, there will be multiple enemies chasing the player. Fast pace is essential to the experience.

What should I do?

# Answer
> 0 votes
You should probably cache your player move in an array, and step through it frame after frame. Let's say you store your Bresenham result in an array called `path`, you'll need an additional variable to hold the current position, let's call it `pathMarker`:

```
var path = new Array();
var pathMarker = -1;

```

Somewhere in you're update function, you'll need something like this:

```
// if our player clicked somewhere, compute a new path
if (click.x != -1 && click.y != -1)
{
    bresenham(path, click);
    pathMarker = -1;
}

// if there's a current path, move along it
if (path.length > 0)
{
    ++pathMarker;

    if (pathMarker >= path.length)
    {
        // reached the end of path, clear everything
        var path = new Array();
        pathMarker = -1;
    }
    else
    {
        // set the player at current path position
        player.pos = path[pathMarker]:
    }
}

```

Depending on the size of your grid, this could be too slow or too fast.

If it's too slow this means that instead of incrementing `pathMarker` one by one you'll have to use greater steps, e.g. replace `++pathMarker` by:

```
    var speed = 4; // for instance
    pathMarker += speed

```

If it's too fast you can step only once in a while instead of each frame:

```
    var framesForAMove = 4; // for instance
    if ((frameCount % framesForAMove) == 0)
    {
        ++pathMarker;
    }

```

NB: using discrete grid positions directly isn't a really good idea in a lot of contexts: variable framerate, variable player speed, etc. But it's simpler to grasp, and quick to code, so very appropriate for prototyping.

---
Tags: 2d, javascript, html5, efficiency
---


# Question
Title: XNA - Error while rendering a texture to a 2D render target via SpriteBatch
I've got this simple code that uses `SpriteBatch` to draw a texture onto a `RenderTarget2D`:

```
private void drawScene(GameTime g)
{
    GraphicsDevice.Clear(skyColor);
    GraphicsDevice.SetRenderTarget(targetScene);
    drawSunAndMoon();
    effect.Fog = true;
    GraphicsDevice.SetVertexBuffer(line);
    effect.MainEffect.CurrentTechnique.Passes[0].Apply();
    GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
    GraphicsDevice.SetRenderTarget(null);
    SceneTexture = targetScene;
}

private void drawPostProcessing(GameTime g)
{
    effect.SceneTexture = SceneTexture;
    GraphicsDevice.SetRenderTarget(targetBloom);
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null);
    {
        if (Bloom) effect.BlurEffect.CurrentTechnique.Passes[0].Apply();
        spriteBatch.Draw(
            targetScene,
            new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
            Color.White);
    }
    spriteBatch.End();
    BloomTexture = targetBloom;
    GraphicsDevice.SetRenderTarget(null);
}

```

Both methods are called from my `Draw(GameTime gameTime)` function. First `drawScene` is called, then `drawPostProcessing` is called.

The thing is, when I run this code I get an error on the `spriteBatch.Draw` call:

> The render target must not be set on the device when it is used as a texture.

I already found the solution, which is to draw the actual render target (`targetScene`) to the texture so it doesn't create a reference to the loaded render target.

However, to my knowledge, the only way of doing this is to write:

```
GraphicsDevice.SetRenderTarget(outputTarget)
SpriteBatch.Draw(inputTarget, ...)
GraphicsDevice.SetRenderTarget(null)

```

Which encounters the same exact problem I'm having right now.

So, the question I'm asking is: how would I render `inputTarget` to `outputTarget` without reference issues?

# Answer
Sounds like `targetScene` and `targetBloom` are the same texture. You should check you're not assigning one to the other somewhere in your code. Or maybe, your `spriteBatch` is using the same texture you're using as a render target (`targetBloom`); you just can't do that (that's a hardware limitation).

I know your question is about how to fix your fix, but I don't understand what you're trying to do, and I see no reason why your first solution wouldn't work.
> 0 votes

---
Tags: xna, c#, post-processing, bloom
---


# Question
Title: Error X3650 when compiling shader in XNA
I'm attempting to convert the XBDEV.NET Mosaic Shader for use in my XNA project and having trouble. The compiler errors out because of the half globals.

At first I tried replacing the globals and just writing the variables explicitly in the code, but that garbles the Output. Next I tried replacing all the half with float vars, but that still garbles the resulting Image.

I call the effect file from `SpriteBatch.Begin()`.

**Is there a way to convert this shader to the new pixel shader conventions? Are there any good tutorials for this topic?**

Here is the shader file for reference:

```
/*****************************************************************************/
/*
File: tiles.fx
Details: Modified version of the NVIDIA Composer FX Demo Program 2004
Produces a tiled mosaic effect on the output.

Requires:  Vertex Shader 1.1
           Pixel Shader 2.0

Modified by: bkenwright@xbdev.net (www.xbdev.net)

*/
/*****************************************************************************/

float4 ClearColor : DIFFUSE = { 0.0f, 0.0f, 0.0f, 1.0f};
float ClearDepth = 1.0f;

/******************************** TWEAKABLES *********************************/
half NumTiles = 40.0;

half Threshhold = 0.15;

half3 EdgeColor = {0.7f, 0.7f, 0.7f};

/*****************************************************************************/

texture SceneMap : RENDERCOLORTARGET <
float2 ViewportRatio = { 1.0f, 1.0f };
int MIPLEVELS = 1;
string format = "X8R8G8B8";
string UIWidget = "None";
>;

sampler SceneSampler = sampler_state {
texture = <SceneMap>;
AddressU  = CLAMP;
AddressV  = CLAMP;
MIPFILTER = NONE;
MINFILTER = LINEAR;
MAGFILTER = LINEAR;
};

/***************************** DATA STRUCTS **********************************/

struct vertexInput {
half3 Position : POSITION;
half3 TexCoord : TEXCOORD0;
};

/* data passed from vertex shader to pixel shader */
struct vertexOutput {
half4 HPosition : POSITION;
half2 UV        : TEXCOORD0;
};

 /******************************* Vertex shader *******************************/

vertexOutput VS_Quad( vertexInput IN)
{
vertexOutput OUT = (vertexOutput)0;
OUT.HPosition = half4(IN.Position, 1);
OUT.UV = IN.TexCoord.xy;
return OUT;
}

/********************************** pixel shader *****************************/

half4 tilesPS(vertexOutput IN) : COLOR {
half size = 1.0/NumTiles;
half2 Pbase = IN.UV - fmod(IN.UV,size.xx);
half2 PCenter = Pbase + (size/2.0).xx;

half2 st = (IN.UV - Pbase)/size;
half4 c1 = (half4)0;
half4 c2 = (half4)0;
half4 invOff = half4((1-EdgeColor),1);
if (st.x > st.y) { c1 = invOff; }
half threshholdB =  1.0 - Threshhold;
if (st.x > threshholdB) { c2 = c1; }
if (st.y > threshholdB) { c2 = c1; }
half4 cBottom = c2;
c1 = (half4)0;
c2 = (half4)0;
if (st.x > st.y) { c1 = invOff; }
if (st.x < Threshhold) { c2 = c1; }
if (st.y < Threshhold) { c2 = c1; }
half4 cTop = c2;

half4 tileColor = tex2D(SceneSampler,PCenter);
half4 result = tileColor + cTop - cBottom;
return result;
}

/*****************************************************************************/

technique tiles
{
pass p0
{
    VertexShader = compile vs_1_1 VS_Quad();
    ZEnable = false;
    ZWriteEnable = false;
    CullMode = None;
    PixelShader = compile ps_2_0 tilesPS();
}
}

```

# Answer
I believe you should be able to fix this simply by replacing all the half variables by float variables.
The only difference is that a half is a 16-bit float value while a true float is 32-bits.
> 2 votes

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


title: Doing a passable 4X game AI

text:
# Question
Title: Doing a passable 4X game AI
I am coding a rather "simple" 4X game (if a 4X game can be simple). It's indie in scope, and I am wondering if there's anyway to come up with a passable AI without having me spending months coding on it.

The game has three major decision making portions; spending of production points, spending of movement points and spending of tech points (basically there are 3 different 'currency', currency unspent at end of turn is not saved)

* Spend Production Points
    + Upgrade a planet (increase its tech and production)
    + Build ships (3 types)
* Move ships from planets to planets (costing Movement Points)
    + Move to attack
    + Move to fortify
* Research Tech (can partially research a tech i.e, as in Master of Orion)

The plan for me right now is a brute force approach. There are basically 4 broad options for the player -

1. Upgrade planet(s) to its his production and tech output
2. Conquer as many planets as possible
3. Secure as many planets as possible
4. Get to a certain tech as soon as possible

For each decision, I will iterate through the possible options and come up with a score; and then the AI will choose the decision with the highest score. Right now I have no idea how to 'mix decisions'. That is, for example, the AI wishes to upgrade and conquer planets at the same time. I suppose I can have another logic which do a brute force optimization on a combination of those 4 decisions....

At least, that's my plan if I can't think of anything better. Is there any faster way to make a passable AI? I don't need a very good one, to rival Deep Blue or such, just something that has the illusion of intelligence.

This is my first time doing an AI on this scale, so I dare not try something too grand too. So far I have experiences with FSM, DFS, BFS and A\*

# Answer
> 4 votes
Sounds like you could try out Minimax to "mix" your decisions. There was a talk at last year's Game AI Conf by the programmers behind Green Corp, and that's what they used to build their AI. It took them a lot of time to get it right, but they have a decent result.

# Answer
> 1 votes
If it is good enough to arouse interest (and you'll have to assume it will be, or you can quit it right now), and it supports networking, the best course of action for this kind of thing is:

* built it multiplayer without any AI
* ensure that every data that is send to the client can be easily "understood" by an AI
* create a **very** simple AI, which allows either some kind of scripting, or **a lot** of configuration options
* allow the players to modify the AI scripts, bind them to the game, and let the AI play via-networking, as if it was a real player

Doing so, the hard part will be to allow the AI to be scripted and used this way, and you'll just "outsource" the actual AI optimization to the players.

This will not only give you a much better AI, but will also add a lot of value to the game itself!

---
Tags: ai, 4x
---


title: Slick2D, Nifty GUI listeners problem

text:
# Question
Title: Slick2D, Nifty GUI listeners problem
I'm trying to get Nifty GUI to work with Slick2D. So far everything is going great, except that I can't seem to figure out how to properly interact with the GUI. I'm trying the example in the nifty manual http://sourceforge.n....0.pdf/download but it doesn't seem to entirely work.

The Element controller is being called for bind(...), init(...) and onStartScreen() as it should, as I can see their println output, but the next() method isn't being called when I click on the GUI element that I assigned the controller to, nor the screen controller as no output from println is shown.

What's weird is, that the player is moving, so the mouse input is working. It's supposed to be called when I click the mouse button on it from the in the XML.

Here is my code:

My Element controller:

```
public class ElementController implements Controller {

private Element element;

@Override
public void bind(Nifty nifty, Screen screen, Element element, Properties parameter, Attributes controlDefinitionAttributes) {
  this.element = element;
  System.out.println("bind() called for element: " + element);
}

@Override
public void init(Properties parameter, Attributes controlDefinitionAttributes) {
  System.out.println("init()  called for element: " + element);
}

@Override
public void onStartScreen() {
  System.out.println("onStartScreen()  alled for element: " + element);
}

@Override
public void onFocus(boolean getFocus) {
  System.out.println("onFocus()  called for element: " + element + ", with: " +
    getFocus);
}

@Override
public boolean inputEvent(NiftyInputEvent inputEvent) {
  return false;
}

public void next() {
  System.out.println("next() clicked for element: " + element);
}
}

```

MyScreenController:

```
class MyScreenController implements ScreenController {
    public void bind(Nifty nifty, Screen screen) {}
    public void onEndScreen() {}
    public void onStartScreen() {}
    public void next() {
     System.out.println("next() called from MyScreenController");
}
}

```

And my XML file:

```
<?xml version="1.0" encoding="UTF-8"?>
<nifty xmlns="http://nifty-gui.sourceforge.net/nifty-1.3.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://niftygui.sourceforge.net/nifty-1.3.xsd http://nifty-gui.sourceforge.net/nifty-1.3.xsd">
<screen id="start" controller="predaN00b.theThing.V0004.MyScreenController">
  <layer childLayout="center" controller="predaN00b.theThing.V0004.ElementController">
   <panel width="100px" height="100px" childLayout="vertical" backgroundColor="#ff0f">
     <text font="aurulent-sans-16.fnt" color="#ffff" text="Hello World!">
      <interact onClick="next()" />
     </text>
   </panel>
  </layer>
</screen>
</nifty>

```

My main class, in case it's needed:

```
public class MainGameState extends BasicGame {

public Nifty nifty;

public MainGame() {
  super("Test");
}

public void init(GameContainer container, StateBasedGame game) throws SlickException {

  nifty = new Nifty(new SlickRenderDevice(container), new NullSoundDevice(), new PlainSlickInputSystem(), new AccurateTimeProvider());

  nifty.addXml("/xml/MainState.xml");
     nifty.gotoScreen("start");

}

public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
  nifty.update();
}

public void render(GameContainer container, StateBasedGame game, Graphics graphics) throws SlickException {
  nifty.render(false);
}

  public static void main(String[] args) throws SlickException {
     AppGameContainer app = new AppGameContainer(new MainGame());
     app.setAlwaysRender(true);
     app.setDisplayMode( 1260 , 720, false); //window size
     app.start();
}
}

```

# Answer
> 2 votes
Sorry, I do not keep track on the quests asked here. For support on the Nifty-GUI and on Slick best use the boards of Slick2D and Nifty-GUI to ask your questions.

How ever in case your question is still relevant, you shall get your answer.

To enable the Nifty-GUI to receive mouse and keyboard you have to forward all events arriving in Slick2D to the Nifty-GUI. This is a pretty major task as Slick2D and Nifty-GUI have separated polling times for this events. So you basically have to buffer the events from Slick2D and forward them to Nifty-GUI upon request.

How ever you are using the PlainSlickInputSystem that basically has this functionality already included. In order to hook it into Slick properly you need to do the following:

```
public void init(GameContainer container, StateBasedGame game) throws SlickException {
 SlickInputSystem inputSys = new PlainSlickInputSystem();
 inputSys.setInput(input);

 nifty = new Nifty(new SlickRenderDevice(container), new NullSoundDevice(), inputSys , new AccurateTimeProvider());

 input.removeListener(this);
 input.removeListener(inputSystem);
 input.addListener(inputSystem);

 nifty.addXml("/xml/MainState.xml");
 nifty.gotoScreen("start");
}

```

Once you did so the PlainSlickInputSystem will take care for relaying the input events from Slick to Nifty.

How ever I propse that you make use of the Game, BasicGame, GameState and BasicGameState implementations that are delivered along with the Slick2D-render library for Nifty. Those classes implement the default Slick classes with there respective names and add all functionality to display and use the Nifty-GUI. The entire initialization is done more or less automatically. Updating and rendering is done automatically as well.

Please also take a look at the Nifty-Slick2D-Renderer reference page for further details on how use use this renderer in the best way.

---
Tags: java, slick
---


title: RenderTarget2D behavior in XNA

text:
# Question
Title: RenderTarget2D behavior in XNA
I've been dabbling with XNA for a couple of days now. This chunk of code doesn't work as I expect. The goal is to render sprites individually and composite them on another rendertarget.

```
P = RenderTarget2D(with RenderTargetUsage.PreserveContents)
D = RenderTarget2D(with RenderTargetUsage.DiscardContents)

for all sprites:
{
    graphicsDevice.SetRenderTarget(D);
    <draw sprite i>

    graphicsDevice.SetRenderTarget(P);
    <Draw D>
}

graphicsDevice.SetRenderTarget(null);
<Draw P>

```

The result I get is - only the last sprite is visible. I'm sure I'm missing some piece of information about RenderTarget2D. Any hints on what that might be?

# Answer
> 1 votes
The problem was that I wasn't clearing `D` with Color.Transparent for every sprite. So, when I tried to overlay `D` onto `P`, the alpha channel didn't work as expected. Changing the code to this made it work:

```
for all sprites:
{
    graphicsDevice.SetRenderTarget(D);
    graphicsDevice.Clear(Color.Transparent);
    <draw sprite i>

    graphicsDevice.SetRenderTarget(P);
    <Draw D>
}

```

# Answer
> 1 votes
Why do you need to set rendertargets so many times? Why not just:

```
graphicsDevice.SetRenderTarget(D);
graphicsDevice.Clear(Color.Transparent);

for all sprites:
{
    <draw sprite i>
}
graphicsDevice.SetRenderTarget(P);
<Draw D>

```

# Answer
> 0 votes
Well I think what's happening is that the render target is clearing the draw buffer and therefore any spritebatch calls are going to be unset. Basically, render all the render targets at once, then draw their content all at once.

# Answer
> 0 votes
Change this:

```
for all sprites:
{
    graphicsDevice.SetRenderTarget(D);
    <draw sprite i>

    graphicsDevice.SetRenderTarget(P);
    <Draw D>
}

```

to this:

```
for all sprites:
{
    graphicsDevice.SetRenderTarget(D);
    <draw sprite i>
}

graphicsDevice.SetRenderTarget(P);
<Draw D>

```

The problem is that `D` or `P` are being cleared somewhere (probably when they get set as a render target), so the only sprite that "survives" is the last one.

Since you have all your sprites rendered to `D` you only need to render `D` onto `P` once.

---
Tags: xna, xna-4.0
---


# Question
Title: Different texture for multiple resolution
How to use different texture(image) for different resolution in libGDX? Also specify how to detect it from asset folder?

# Answer
The question is pretty vague, but if I'm interpreting it correctly, you're going to need to do it manually, but libgdx can help. You're going to want to use the `ResolutionFileResolver`. The author of libgdx provides an example in his `AssetManagerTest`. I wrote about how to use the `ResolutionFileResolver` in this answer.

I think if you read through the code, that should be enough to get you started, and you can come back with more specific questions.
> 2 votes

---
Tags: libgdx
---


# Question
Title: JMonkeyEngine display a spatial in a Nifty GUI interface
I want to display a spatial (or the rendering of a spatial/scene) in my HUD interface. I'm really not sure how to go with this. I have search the documentation, but all the queries I search yields no result, and all I could find about images is that one can specify one with the `setBackgroundImage` method in the builder and `setImage` from the `ImageRenderer` class. The latter takes a `String` or a `NiftyImage`, but I'm not sure how to create one without loading an image file.

Any help to understand this (if even possible) is appreciated. Thanks!

# Answer
There is but one way I can imagin to get this working.

Creating a new `NiftyImage` as it is needed to get requires two arguments:

1. the `NiftyRenderEngine` you can receive from the current Nifty-GUI instance using the `getRenderEngine` function
2. A `RenderImage` that is part of the SPI.

The key is to implement the `RenderImage` yourself. To be more precise you have to overload `RenderImageJme` that is used by the JME-Renderer for Nifty to to define images. This class implements a `getTexture()` method you can overwrite to send in a alternative texture.

If you render the things you want to display to a texture and return this texture in your own implementation of the `RenderImageJme`, then you should be able to display what ever you want.
> 2 votes

---
Tags: jmonkeyengine
---


# Question
Title: What is the most efficient way to add and remove Slick2D sprites?
I'm making a game in Java with Slick2D and I want to create planes which shoots:

```
int maxBullets = 40;
static int bullet = 0;
Missile missile[] = new Missile[maxBullets];

```

I want to create/move my missiles in the most efficient way, I would appreciate your advise:

```
public void shoot() throws SlickException{
    if(bullet<maxBullets){
        if(missile[bullet] != null){
            missile[bullet].resetLocation(plane.getCenterX(), plane.getCenterY(), plane.image.getRotation());
        }else{
            missile[bullet] =
            new Missile("resources/missile.png", plane.getCenterX(), plane.getCenterY(), plane.image.getRotation());
        }
    }else{
        bullet = 0;
        missile[bullet].resetLocation(plane.getCenterX(), plane.getCenterY(), plane.image.getRotation());
    }
    bullet++;
}

```

I created the method `resetLocation` in my `Missile` class in order to avoid loading again the resource. Is it correct?

In the update method I've got this to move all the missiles:

```
if(bullet > 0 && bullet < maxBullets){
    float hyp = 0.4f * delta;
    if(bullet == 1){
        missile[0].move(hyp);
    }else{
        for(int x = 0; x<bullet; x++){
            missile[x].move(hyp);
        }
    }
}

```

# Answer
> 2 votes
First thing would be to load all your bullets when starting your game. This will barely slow down the start up time and avoids performance problem when loading the bullets during the game.

Furthermore you should ensure that each bullet uses the same OpenGL texture. So you don't load the same image 40 times into the video memory. It might be good to only construct the first bullet and create the remaining ones using copy constructors that ensure that the same texture is used.

For the update method... while the idea you had there is okay, the additional check won't provide much of the speedup and makes the code simply more complicated. I guess most of the time will will have more then one bullet on the screen anyway. If the `for` loop is too slow for your taste you can easily switch to a while loop looking like:

```
int x = -1;
while (++x < bullet) {
    missile[x].move(hyp);
}
```

Other than that you can turn the variables that never change `final`. That does not cause the massive speedup... but it does not hurt.

Last thing is that I think you got a but in this whole concept. You have one variable (`bullet`) that mark the current position in your array where you write new bullets too. But what happens for example if I fire 42 bullets? The count raises up to 40, then drops to 0 at the 41st shot and to 1 at the 42nd shot. You update function will now only update `missile[0]` and the other bullets (index 1 to 39) are stuck.

Most likely its a better approach to use two lists (`ArrayList`s for example). One containing the "active" bullets, one the buffered bullets. And as new bullets are needed you transfer them to the active bullet list and update them until they are out of the screen or hit something or ended there lifetime on any other way. And put them back into the buffered list after to be reused.

# Answer
> -1 votes
Load the resource once, at start of level. Draw every frame.

---
Tags: java, slick
---


title: XNA: Huge Tile Map, long load times

text:
# Question
Title: XNA: Huge Tile Map, long load times
Recently I built a tile map generator for a game project. What I am very proud of is that I finally got it to the point where I can have a GIANT 2D map build perfectly on my PC. About 120000pixels by 40000 pixels. I can go larger actually, but I have only 1 draw back. #1 ram, the map currently draws about 320MB of ram and I know the Xbox allows 512MB I think? #2 It takes 20 mins for the map to build then display on the Xbox, on my PC it take less then a few seconds.

I need to bring that 20 minutes of generating from 20 mins to how ever little bit I can, and how can a lower the amount of RAM usage while still being able to generate my map.

Right now everything is stored in Jagged Arrays, each piece generating in a size of 1280x720 (the mother piece). Up to the amount that I need, every block is exactly 40x40 pixels however the blocks get removed from a List or regenerated in a List depending how close the mother piece is to the player. Saving A LOT of CPU, so at all times its no more then looping through 5184 some blocks. Well at least I'm sure of this.

But how can I lower my RAM usage without hurting the size of the map, and how can I lower these INSANE loading times?

EDIT:

Let me explain my self better. Also I'd like to let everyone know now that I'm inexperienced with many of these things.

So here is an example of the arrays I'm using. Here is the overall in a shorter term:

```
    int[][] array = new int[30][];
        array[0] = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
        array[1] = new int[] { 1, 3, 3, 3, 3, 1, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };

```

that goes on for around 30 arrays downward. Now for every time it hits a 1, it goes and generates a tile map 1280x720 and it does that exactly the way it does it above.

This is how I loop through those arrays:

```
        for (int i = 0; i < array.Length; i += 1)
        {
            for (int h = 0; h < array[i].Length; h += 1)
            {
            }
        {

```

Now how the tiles are drawn and removed is something like this:

```
    public void Draw(SpriteBatch spriteBatch, Vector2 cam)
    {
        if (cam.X >= this.Position.X - 1280)
        {
            if (cam.X <= this.Position.X + 2560)
            {
                if (cam.Y >= this.Position.Y - 720)
                {
                    if (cam.Y <= this.Position.Y + 1440)
                    {
                        if (visible)
                        {
                            if (once == 0)
                            {
                                once = 1;
                                visible = false;
                                regen();
                            }
                        }
                        for (int i = Tiles.Count - 1; i >= 0; i--)
                        {
                            Tiles[i].Draw(spriteBatch, cam);
                        }
                        for (int i = unWalkTiles.Count - 1; i >= 0; i--)
                        {
                            unWalkTiles[i].Draw(spriteBatch, cam);
                        }
                    }
                    else
                    {
                        once = 0;
                        for (int i = Tiles.Count - 1; i >= 0; i--)
                        {
                            Tiles.RemoveAt(i);
                        }
                        for (int i = unWalkTiles.Count - 1; i >= 0; i--)
                        {
                            unWalkTiles.RemoveAt(i);
                        }
                    }
                }
                else
                {
                    once = 0;
                    for (int i = Tiles.Count - 1; i >= 0; i--)
                    {
                        Tiles.RemoveAt(i);
                    }
                    for (int i = unWalkTiles.Count - 1; i >= 0; i--)
                    {
                        unWalkTiles.RemoveAt(i);
                    }
                }
            }
            else
            {
                once = 0;
                for (int i = Tiles.Count - 1; i >= 0; i--)
                {
                    Tiles.RemoveAt(i);
                }
                for (int i = unWalkTiles.Count - 1; i >= 0; i--)
                {
                    unWalkTiles.RemoveAt(i);
                }
            }
        }
        else
        {
            once = 0;
            for (int i = Tiles.Count - 1; i >= 0; i--)
            {
                Tiles.RemoveAt(i);
            }
            for (int i = unWalkTiles.Count - 1; i >= 0; i--)
            {
                unWalkTiles.RemoveAt(i);
            }
        }
    }
}

```

If you guys still need more information just ask in the comments.

# Answer
> It takes 20 mins for the map to build then display on the Xbox, on my PC it take less then a few seconds.
>
> Up to the amount that I need, every block is exactly 40x40 pixels however the blocks get removed from a List or regenerated in a List depending how close the mother piece is to the player.

If I had to hazard a guess your map generation method generates a lot of garbage. Try just using the stack and arrays you allocated.

If I remember correctly the Xbox's GC looks over ***every*** reference and frees the unused ones for every ***1mb*** of memory changed. In the future try to deploy often to the 360 as there a lot of gotchas like this and its easier to fix them as you go rather than having to rewrite your systems.
> 1 votes

---
Tags: xna, tilemap
---