title: One Step-Ahead A-Star

text:
# Question
Title: One Step-Ahead A-Star
I am attempting to create a server-centric RTS (as opposed to usual parallel synchronised simulation route of most RTS games today) - however I am still leveraging the discreet N-turns-ahead paradigm discussed by one of the AOE developers on Gamasutra.

I have \[possibly questionably?\] decided that the path finding should only ever find the next cell the entity needs to move to, and was wondering if anyone has any clever ideas on how to optimize the algorithm for this specific scenario - or any other ideas on how to keep the pathfinding as lean as possible on the server.

I have investigated a few possible algorithms but could only come up with one appropriation: Tiered A-Star \- Relatively large T1 tiles, work out (and cache) each cell as you enter it. Other than that: doing the full A-Star pass and caching the entire path, which might use too much memory if a large amount of units are present.

I know about the existence of naive progressive pathfinding algorithms (if you hit a block, turn in the direction closer to your target etc.) but they suffer from infinite feedback loops - and very poor pathing even if visited blocks are memorised. Not an option.

Many thanks.

# Answer
Check out BlobMaps for something simpler, at least, than A\*. Still not only one step ahead, but fine under many circumstances, according to the author (I've not tried them as yet).
> 2 votes

# Answer
Computing just one move sounds like a bad idea to me. If you don't compute the whole path, then you don't know that the next tile to move to is correct, so a lot of the time units will get trapped.

Caching the entire path for a unit won't take too much memory. It's just a list of node IDs. The main problem is generating the path in the first place, and how much of an issue that is depends on the complexity of your map - how many discrete nodes you have, the branching factor for each one, and whether you have a lot of large obstacles.

This is not to say that hierarchical A\* won't help, and it will definitely speed things up, but you seem to be micro-optimising ahead of time. Why not just implement the simplest approach and go from there? If it turns out to be too slow, you can trivially change it later because you have a simple input interface (the source and destination nodes) and output interface (a list of nodes to travel on) - the algorithm you use to handle that is easily interchangeable.
> 16 votes

# Answer
Your best bet is to use Tiered A-Star and then employ various strategies for minimizing the overhead. For example, the memory footprint can be dramatically reduced by having multiple units share the same path. That is, there's no need to store a path for each individual unit; instead store all the units that started in the same area, and then calculate just one path from that area.
> 4 votes

# Answer
I've used the shared path idea that jhocking brought up, it works well in a situation where you're moving groups (say like infantry squads) around.

I've also used a variant of the tiered approach where paths between the higher tier(s) are pre-calculated when the map is built and cached by the server, the lowest tier is still best served by a local path of its own.

If you haven't done it already move your path finder out into an asynchronous service for your server, in this way a flood of requests on the same tick won't bog down the main simulation.

And finally, have you measured how much space/time is actually used by a path? It could be that you're worrying over nothing =) Kylotan is right about measuring before optimizing.
> 1 votes

---
Tags: path-finding
---


# Question
Title: Marshalling C# Structs into DX11 cbuffers
I'm having some issues with the packing of my structure in C# and passing them through to `cbuffer`s I have registered in HLSL. When I pack my struct in one manner the information seems to be able to pass to the shader:

```
[StructLayout(LayoutKind.Explicit, Size = 16)]
internal struct TestStruct
{
    [FieldOffset(0)]
    public Vector3 mEyePosition;

    [FieldOffset(12)]
    public int type;
}

```

This works perfectly when used against this HLSL fragment:

```
cbuffer PerFrame : register(b0)
{
    Vector3 eyePos;
    int type;
}

float3 GetColour()
{
    float3 returnColour = float(0.0f, 0.0f, 0.0f);

    switch(type)
    {
        case 0:
            returnColour = float3(1.0f, 0.0f, 0.0f);
            break;
        case 1:
            returnColour = float3(0.0f, 1.0f, 0.0f);
            break;
        case 2:
            returnColour = float3(0.0f, 0.0f, 1.0f);
            break;
    }

    return returnColour;
}

```

However, when I use the following structure definitions...

```
// Note this is 16 because HLSL packs in 4 float 'chunks'.
// It is also simplified, but still demonstrates the problem.
[StructLayout(Layout.Explicit, Size = 16)]
internal struct InternalTestStruct
{
    [FieldOffset(0)]
    public int type;
}

[StructLayout(LayoutKind.Explicit, Size = 32)]
internal struct TestStruct
{
    [FieldOffset(0)]
    public Vector3 mEyePosition;

    //Missing 4 bytes here for correct packing.

    [FieldOffset(16)]
    public InternalTestStruct mInternal;
}

```

... the following HLSL fragment no longer works.

```
struct InternalType
{
    int type;
}

cbuffer PerFrame : register(b0)
{
    Vector3 eyePos;
    InternalType internalStruct;
}

float3 GetColour()
{
    float3 returnColour = float(0.0f, 0.0f, 0.0f);

    switch(internaltype.type)
    {
        case 0:
            returnColour = float3(1.0f, 0.0f, 0.0f);
            break;
        case 1:
            returnColour = float3(0.0f, 1.0f, 0.0f);
            break;
        case 2:
            returnColour = float3(0.0f, 0.0f, 1.0f);
            break;
    }

    return returnColour;
}

```

Is there a problem with the way I am packing the struct, or is it another issue?

To re-iterate: I can pass a struct in a `cbuffer` so long as it does not contain a nested struct.

# Answer
The layout is perfectly valid for both samples in C#/HLSL (I did a quick test with your layout and It's working - SharpDX based), so I suspect that there is something wrong elsewhere (marshaling the struct/update of the constant buffer... etc). You should also be able to debug your application with PIX and check exactly if the uploaded buffer is wrongly packed.
> 2 votes

---
Tags: c#, directx11
---


title: using blender to generate a 3D skybox

text:
# Question
Title: using blender to generate a 3D skybox
Is it possible for me to use Blender to generate a 3D skybox?

The concept is fairly simple: I create a scene that I want to display on the skybox (mountains, clouds, water, etc). Then, couldn't Blender render it from the origin, calculating the images that would be placed on the six sides of the skybox?

Is there a way of doing this? It'd be a very easy way of making one's own skyboxes...

# Answer
> 2 votes
The wikibook Blender 3D: Noob to Pro covers this.

Jump down to the "Render an Environment Map" section.

* Set up your Scene, including an object (you can use an Empty) for the location of the skybox.
* Create a new material for the object
* Create a new texture for that material. Change its type to EnvMap (environment map)
* Check \[Static\] or \[Anim\] for whether you want to render it once or every frame of an animation
* Set the \[Ob: \] field for the texture to your object. This determines where the rendered skybox is centered.
* Set CubeRes to your desired resolution
* Optionally set Clip distances if you have clipping issues
* Render the scene
* Go back to the textures pane of your object and click \[Save EnvMap\]

After rendering, the textures pane should look like this:

---
Tags: 3d, assets, blender, sky
---


# Question
Title: Architecture a for a central renderer rather than self-rendering
For the architectural side of rendering, there's two main ways: having each object render itself, and having a single renderer which renders everything.

I'm currently aiming for the second idea, for the following reasons:

* The list can be sorted to only use shaders once. Else each object would have to bind the shader, because it's not sure if it's active. The objects could be sorted and grouped.
* Easier to swap APIs. With a few macro lines, it can be easy to swap between a DirectX renderer and an OpenGL renderer (not a reason for my project, but still a good point)
* Easier to manage rendering code

Of course, if anyone has strong recommendations for the first method, I will listen to them.

But I was wondering how make this work.

**First idea**
The renderer has a list of pointers to the renderable components of each entity, which register themselves on RenderCompoent creation. However, I'm worrying that this may end up as a lot of extra pointer weight. But I can sort the list of pointers every so often.

**Second idea**
The entire list of entities is passed to the renderer each render call. The renderer then sorts the list (each call, or maybe once?) and gets what it wants. That's a lot of passing and/or sorting, however.

**Other ideas**
???
PROFIT

Anyone got ideas? Thank you.

# Answer
**Third idea**

Each entity submits an encoded integer key, possibly with an associated value to the renderer for each item to be rendered. The renderer can then sort the keys using any fast integer sorting method, and submit each item to be rendered.

By encoding the key in the order you want each component sorted, from MSB to LSB, you get the benefits of your second idea with a much faster sorting step.

There's a huge amount of flexibility here in terms of how you encode your key, from something as minimal as:

```
|MaterialID|Depth|MeshID|
|         4|   20|      8|  (16 materials, 256 models)

```

To a more complex 64-bit key & pointer value:

```
|Fullscreen|Viewport|Layer|Blend|Depth|MaterialID|  :  ptr_to_data
|         2|       3|    3|    2|   23|        30|

```

There are several additional benefits to using integer keys; for example, if you have a static section of the scene you can cache the resulting keys and simply re-submit the prepared list (if used often, pre-sort and use a suitable sorting algorithm).
> 18 votes

# Answer
**Have your renderer persistently manage all the renderable data**

When a new renderable instance is created the renderer passes back a handle. The handle allows the client code to make basic changes to the renderable, eg. make it invisible, change its transform, per instance material properties (eg. alpha) etc.

Benefits of this architecture as I see them:

* allows the renderable to remain in a predetermined bucket as determined by it's material/shader properties (see Jason's post for how to possibly classify these buckets) at creation time, not at run-time.
* It also allows the renderer to keep these buckets/lists compact from frame to frame, allowing the renderer to manage the memory footprint of each bucket in a nice coherent way.
* Allows the renderer to gather renderable instances to improve per-draw call overhead using instancing.
* Allows the renderer to double buffer these lists, and dispatch jobs to multiple processors (eg. using DX11 deferred contexts, or asynchronous per-bucket sorting) without revealing the complexity of the implementation to the client code.
> 5 votes

# Answer
I asked a similar question over at Stack Overflow which got some decent responses that might help you: "What's wrong with the architecture of a game object drawing and updating itself?". I think reading this question and its answers will help you validate that yes, you should have a central renderer (though you already seem to get that), and hopefully clarify how to do so.
> 4 votes

# Answer
In practice I use both. I try to keep the number of items types sufficiently low (e.g. particles, sprites and GUI images have a hell of a lot in common with each other and can share much code) but where it helps I break things out (e.g. some types of model can be drawn with instancing which is sufficiently different to standard drawing that I feel centralizing this would over-complicate the design).

For the common stuff it's just a matter of deciding what properties they all share and designing some wrappers around them. For particles, sprites and GUI images I did a simple "Quad drawing" interface that I can just hand a list of vertexes to, as well as a texture and a set of shaders to use. The interface then handles changing state as needed, appending to a dynamic vertex buffer, drawing in batches, etc. It ended up looking a lot like ID3DXSprite in fact, but setup to meet my own specific requirements rather than in a more general fashion.

I've another layer beneath this that's used by both generalized and specialized drawing, which handles lower-level stuff like flushing buffers, updating shader parameters, etc.
> 0 votes

---
Tags: architecture, rendering
---


# Question
Title: How to access the nth element in a 2d texture from a pixel shader in XNA
How can I access the nth element in a texture2d from a pixel shader? For example if I wanted to get the 5th vector4 from 10 x 10 texture2d

# Answer
2D textures usually aren't addressed in terms like the "nth element". The whole point of a 2D texture is that you want to access it using 2D coordinates. If you want to send a 1D array to the shader I'd use a 1D texture.

That being said, you can compute it by something like this:

```
int x = n % textureWidth;
int y = n / textureWidth;                            // integer division
float u = (float(x) + 0.5) / float(textureWidth);    // map into 0-1 range
float v = (float(y) + 0.5) / float(textureHeight);
float4 result = tex2D(sampler, float2(u, v));

```

(This assumes you already know how to set up a sampler parameter in the shader and bind a texture to it from the application side.)
> 1 votes

---
Tags: xna-4.0, fragment-shader
---


title: What does tex1D do with a 2d texture?

text:
# Question
Title: What does tex1D do with a 2d texture?
If I call tex1d from my pixel shader on a texture that has been initialized as a texture2d will it treat the data as a one dimensional array and then just take the element at whichever position you specify?

For instance if you have a 10 x 10 texture(that would be a one dimensional array 100 elements in length) and you call tex1d(mySampler, 0.95) will it give you back element 95?

# Answer
> 1 votes
I think you will find this quote (regarding DirectX 9, which is what XNA is built on) relevant:

> Because the runtime does not support 1D textures, the compiler will use a 2D texture with the knowledge that the y-coordinate is unimportant. Since tex1D(s, t) (DirectX HLSL) is implemented as a 2D texture lookup, the compiler is free to choose the y-component in an efficient manner.

In other words: you specify the X coordinate, and the Y coordinate is undefined.

From here.

So, no, it won't unwrap the indices. But you already got an answer about how to do that.

# Answer
> 0 votes
I haven't used XNA, but my guess is that calling tex1D on a 2D texture (or more generally any mismatch between the dimensionality of the sampling function and the actual texture being sampled) is an error, and will probably return some default value like black.

---
Tags: xna-4.0, fragment-shader
---


title: How does a BSP tree work for Z sorting?

text:
# Question
Title: How does a BSP tree work for Z sorting?
I'm developing a 3D engine in software, and so I must compute Z sorting manually. I'm currently using the painter's algorithm to sort triangles and then drawing them back-to-front. This causes artifacts that I'm trying to correct.

1. Would using a dynamic BSP-tree ensure "correct Z sorting" of triangles? Why? Because the bounding volumes of triangles would be similar?
2. Since I would have a single "world" BSP tree, would I have to remove and re-add any moved/scaled/rotated object into the tree?
3. Is it possible to add triangles into a BSP tree without the expensive cutting process? Why do you need to cut triangles on the axis planes anyway?
4. Is it faster to traverse a BSP tree from any angle, than to sort all tris each draw like the painters algorithm?

# Answer
> 7 votes
1. Using a dynamic BSP tree *can* ensure correct z-sorting of triangles, if you draw those triangles by walking through the BSP tree, and if you have only one triangle per BSP branch. The basic idea is that each branch of your BSP tree breaks up space into two pieces (typically "in front of" and "behind" that triangle). By checking which of those two pieces of space contains your camera, and drawing the other one first (recursing into the BSP tree branch for that space, if you're not in a leaf node), then you're ensured that you always draw the tree from back to front, which is exactly what you need for the painter's algorithm.
2. Yes. Adding or moving triangles will require re-building the BSP tree, which can be very computationally expensive. Most games with moving objects do not include those moving objects as part of the BSP tree for exactly that reason, and instead build a separate BSP tree for each movable object, and then pick an order in which to draw those movable objects using a more traditional z-sorting.
3. You CAN add triangles into a BSP tree without clipping them according to your BSP planes (so triangles may have corners 'poking through' the division planes), but doing so can result in errors in the back-to-front traversal of the tree. In fact, there are many situations where it's impossible to correctly draw a set of triangles from back to front, simply because they overlap in a complicated manner (for example, it's possible to arrange three long, slender triangles in a loop such that each overlaps the next, and none is entirely "in front". In this situation, the only way to make these triangles render correctly is to split the triangles, and z-sort the triangles after the split. The BSP triangle cutting process typically handles cutting triangles which might have this problem automatically, while building the BSP tree). But you don't necessarily have to cut triangles on cardinal axis planes, as you imply -- in fact, when building your BSP tree, it's often most convenient to pick one of the existing triangles in a space, and to use the plane of that triangle as the split plane for cutting the other triangles into "front" and "back" groups.
4. It is much, much faster to traverse a BSP tree than to sort triangles naively. Traversing a BSP tree requires a vector subtraction and a dot product at each branch, while a sort requires.. well.. a sort. So one is O(n), while the other is probably O(n\*logn), depending on the sort algorithm you choose. That can be a huge difference, when you're dealing with a large set of triangles.

# Answer
> 1 votes
As per request :-)

You will always have artefacts if you draw triangle per triangle, BSP or not.

That is why the Z-Buffer became so popular in the nineties ;-)

BTW, sorting triangles is usually used

A) for drawing semi transparent triangles and/or

B) for optimizing overdraw

---
Tags: software-rendering, bsp-tree
---


title: Does XNA support 1 dimensional textures

text:
# Question
Title: Does XNA support 1 dimensional textures
Does XNA support 1 dimensional textures. And by 1 dimension texture I mean something like Texture1d not a Texture2d where one dimension is 1 (because of the 4096 limit)

# Answer
> 2 votes
As per my comment, `SetValue(Vector4[])` does not work. However, you should be able to use a `Texture2D` to achieve what you are after.

You can map a one-dimensional index to a two-dimensional index using the following function:

```
x = index % width;
y = (index - x) / width;

```

Therefore you can simply perform a `SetData(Vector4[])` on a `Texture2D` and map the indicies within the shader (make sure you use point sampling). If you use all the pixels in a 4096x4096 texture you will effectively have an array that can contain 16777216 values.

```
int ValuesStride = 4096; // a.k.a Width.
texture2D Values;
sampler2D ValuesSampler =
sampler_state
{
  Texture = <Values>;
  Filter = POINT;
  AddressU = CLAMP;
  AddressV = CLAMP;
};

float4 PixelShaderFunction(float4 Position : POSITION0, float2 UV : TEXCOORD0) : COLOR0
{
  var value = ArrayLookup(ValuesSampler, ValuesStride, 100);
  // ...
}

float4 ArrayLookup(sampler2D sampler, int width, int index)
{
  float2 coord = (float2)0;
  coord.x = index % width;
  // We don't need to subtract coord.x because of how integral math works.
  coord.y = asint(index / width);
  return tex2D(sampler, coord);
}

```

# Answer
> 0 votes
HLSL has a Texture1D but XNA doesn't. I know little about shaders but I suggest you start first checking if the included basic effect supports Texture1D. If so then you just need to store in a buffer then pass it to the effect. If not you have to implement it from the ground up.

Not sure if it does but I hope that helps.

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


# Question
Title: Is there any guarantee about the graphical output of different GPUs in DirectX?
Let's say that I run the same game in two different computers with different GPUs. If for example they are both certified for DirectX 10. Is there a guarantee that the output for a given program (game) is going to be the same regardless the manufacturer or model of the GPU? I am assuming the configurable settings are exactly the same in both cases.

I heard that it is not the case for DirectX 9 and older, but that it is true for DirectX 10. If someone could provide a source confirming or denying it, it would be great. Also what is the guarantee offered. Will the output be exactly the same or just perceptually the same to the human eye?

# Answer
> 9 votes
In DirectX 10 the cards all have the same **capabilities**: this means that they guarantee that all features are available and implemented.

However, they are free to do driver-level optimizations. Take, for example, the major difference in the way that they do anisotropic filtering (this article contains sources). Not only is the output of each vendor different - the user is also able to tweak the enabled optimizations in configuration tools provided by most vendors.

If you want guaranteed and perfect results use the reference rasterizer from the DirectX SDK \- it's extremely slow; but it is what Microsoft expects vendors to approximate.

In regard to output quality guarantees there is no difference between DirectX 9 and DirectX 10: there is absolutely no guarantee (even worse, quite a substantial amount of laptop chipsets advertise support for a feature and do nothing when it is used - leading to severely degraded quality).

# Answer
> 2 votes
It's impossible to make this guarantee; there are just so many variable factors. Not even OpenGL's invariance rules go that far, and OpenGL tends to be much more specific about this kind of thing than D3D: http://glprogramming.com/red/appendixh.html

> OpenGL is not a pixel-exact specification. It therefore doesn't guarantee an exact match between images produced by different OpenGL implementations.

# Answer
> 1 votes
I think the answer is a definitive *no*.

Case in point: nVidia Quadro cards have identical hardware as the consumer-level Geforce cards, but are controlled with different drivers or firmware. The Quadro cards do more precise calculations which can produce more accurate graphics.

From Wikipedia (unsourced):

> The performance difference comes in the firmware controlling the card. Given the importance of speed in a game, a system used for gaming can shut down textures, shading, or rendering after only approximating a final output—in order to keep the overall frame rate high. The algorithms on a CAD-oriented card tend rather to complete all rendering operations, even if that introduces delays or variations in the timing, prioritising accuracy and rendering quality over speed.

# Answer
> 0 votes
You're not going to get binary perfect output even between different driver versions of the same video card, much less different cards and manufacturers.

Look at it this way, Joe Walmart end user has no idea what color calibration is and so even across the same card and drivers the players will be seeing different colors.

The only "guarantee" is that if the driver reports that a particular feature is done in hardware then maybe it is, except when it's not.

This is an odd question. What problem are you trying to solve?

---
Tags: directx, directx9, gpu, directx10
---


title: XNA CustomModelAnimationSample problem

text:
# Question
Title: XNA CustomModelAnimationSample problem
I downloaded the official tutorial from:CustomModelAnimationSample It works fine but when I try to replicate it in my project, it fails to load the `Tag` property in my model.

Is found that the probelm is in the line:

```
skinnedModel = Content.Load<Model>("DudeWalk");

```

This line loads the model from the DudeWalk.fbx file and with the custom `SkinnedModelProcessor`. It loads the animations data in the model. After the line the `Tag` property is full. I stepped into the method and it went to the custom `ModelData` class.

I copied everything from the projects `CustomModelAnimationWindows` and `CustomModelAnimationPipeline` to my solution and set all the references. I tried the same line of code and couldn't step in the method. It called the default method or model constructor and after the line the model's `Tag` propetry was `null`.

I have to load the model through my custom `SkinnedModelProcessor` class, but how I tell the game to use this class? In the tutroail CustomModelClass the line is changed to:

```
model = Content.Load<CustomModel>("tank");

```

So I assumed that I have to set the generic type to a custom model class, but the first example works without it.

If anyone has some useful advice or some other helpful link, I'll be happy to try it.

**EDIT :**

I tried this tutorial Creating a Custom Importer and Processor but it didn't work either.

I understand now that the binding of the custom pipeline processor is done at build-time and not a run-time. But my custom processor never gets bound nor called.

# Answer
> 2 votes
In order to do custom processing, you also have to set the importer/processor for the model in question. Go to the Content, click the model and select the desired importer/processor from the properties window.

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


title: Tool for creating complex paths?

text:
# Question
Title: Tool for creating complex paths?
I want to create some fairly complex 2d predefined paths for my AI sprites to follow.

I'll need to use curves, splines etc to get the effect I want.

Is there a drawing tool out there that will allow me to draw such curves, "mesh" them by placing lots of points along them at some defined density and then output the coordinates of all of those points for me?

I could write this tool myself but hopefully one of the drawing packages can do this?

Cheers!

# Answer
You could use Inkscape (open-source vector drawing program) to draw bézier curves, add as many nodes as needed in them and then turn them to straight paths.

Inkscape outputs SVG files, which are XML documents. You can then extract points fairly easily from the d attribute of svg:path elements.

A few hints for using Inkscape:

* Create a rectangle in your document, this will add an svg:rect to your SVG file
* You can turn it into an svg:path by hitting Ctrl+Shift+C
* You can then move and distort the nodes however you want. Double-clicking on a segment will add a new node. Dragging anywhere on a segment will turn it into a bézier curve
* To add more nodes to your path (make it smoother), select all nodes and click the "+" button in the node toolbar.
* Once you're done editing your curve and you have added enough nodes, you can turn it back into a straight path by clicking on the button named "Make selected segments lines"
* Ctrl+Shift+X opens an XML editor from which you can copy / paste the path data.

The SVG path data for straight segments is pretty straightforward:

* "M x,y" moves the pen to the specified location
* "L x,y" (or just "x,y", the L can be and is ommitted by Inkscape) draws a segment to the specified location

See here for full syntax: http://www.w3.org/TR/SVG/paths.html#PathData

---

Alternatively, you could try using my VectorLevelProcessor content pipeline processor, which parses SVG files & path data and can generate point list for bézier curves. But it might be too much work to integrate if you only need a few paths.

Here's a link to the main source file: http://nuclearwinter.codeplex.com/SourceControl/changeset/view/1268293a8bff#VectorLevelProcessor%2fVectorLevelProcessor.cs

It's part of a bigger framework called Nuclear Winter that you can check out.
> 4 votes

# Answer
Try the Curve Editor from App Hub's education catalog.
> 1 votes

# Answer
I recommend that you don't do this. For a useful blog post, with some video demonstrations, see Fixing Pathfinding Once and For All. Some of the most annoying pathing bugs in Everquest are due to the older zones and their waypoint graphs (also known as lattice pathing), where it looks like the NPCs ride on rails once they've reached the mesh.
> 0 votes

---
Tags: xna, 2d, ai, tools, path-finding
---


# Question
Title: How can I write only to the stencil buffer in OpenGL ES 2.0?
I'd like to write to the stencil buffer without incurring the cost of my expensive shaders. As I understand it, I write to the stencil buffer as a 'side effect' of rendering something. In this first pass where I write to the stencil buffer, I don't want to write anything to the color or depth buffer, and I definitely don't want to run through my lighting equations in my shaders.

Do I need to create no-op shaders for this (and can I just discard fragments), or is there a better way to do this?

As the title says, I'm using OpenGL ES 2.0.

I haven't used the stencil buffer before, so if I seem to be misunderstanding something, feel free to be verbose.

# Answer
Disable writing to the color buffer and depth buffer:

```
glColorMask(false, false, false, false);
glDepthMask(false);

```

Then do your draw as normal (with stencil testing/writing enabled), and restore color/depth writing afterward by repeating those calls with `true` instead of `false`. This *should* automatically short-circuit the pixel shader, I believe.
> 7 votes

---
Tags: opengl, glsl, opengl-es2, stencil
---


# Question
Title: What exactly is the difference between separation and obstacle avoidance
I've been reading some literature that explains both separation and obstacle avoidance. On first sight, they both seem very similar in what they are supposed to do: keeping objects apart form each other. If that is the case, why would I need to have both behaviors? Is separation sort of wrapping obstacle avoidance, and adding to it?

# Answer
> 7 votes
# Avoidance

This makes an object avoid obstacles that may be hindering it while it navigates to a goal. Perfect avoidance would never allow objects to overlap.

# Separation

This deals with the situation when avoidance fails to keep objects apart. This often occurs 'between frames': an object can move into a new position that overlaps other objects because the precise time of collision happened between the last frame and the current one (or some other condition such as momentum). Separation will seek to move the object so that it no longer collides.

# Are They The Same Thing?

They are not really the same, but they are related - in a system which contains both separation is only there because avoidance would need to multisample (and hence impact performance) to avoid collisions between frames. Thus, we simply allow the overlap to occur from the perspective of avoidance and **IMMEDIATELY** resolve it using separation.

Note that separation can exist alone in a system: for example when the movement of an object is controlled by physics and not by AI. I do not think the inverse (avoidance alone) would be found alone in any serious implementation.

---
Tags: collision-detection, ai, movement, behavior
---


# Question
Title: What can be the cause of sudden lag spikes in my Android game?
My Android game has sudden lag spikes sometimes. I know this is due to something going wrong. My phone has a 1GHz processor so there shouldn't be a problem. Basically I use the `Canvas` class to render my entire game (I am about to learn OpenGL and don't know if this is the cause). I have a main game loop and about 4 threads. Why does it lag?

Thanks in advance.

# Answer
This is most presumably the garbage collector kicking in.

There is no clean way to solve this problem unless you are willing to ditch Java for another language such as C++. See How can I avoid garbage collection delays in Java games? (Best Practices) for a few hints on how to mitigate the problem.
> 6 votes

---
Tags: android, java, opengl-es, game-loop
---


title: Simulating water droplets on a window

text:
# Question
Title: Simulating water droplets on a window
How do I simulate water droplets realistically falling, gathering, and flowing down a window? For example, see http://www.youtube.com/watch?v=4jaGyv0KRPw. In particular, I want to simulate how smaller droplets merge together to form larger droplets that have enough weight to oppose the surface tension and flow downward, leaving a trail of water.

I'm aware of fluid simulation, but how would it be applied in this situation?

# Answer
There was a good rain-on-glass simulation in the ATI Toy Shop demo from a few years ago. See the video starting at 1:30; and here are detailed slides on how all the rain effects work.
> 4 votes

# Answer
Metaballs in 2D. A great raindrop example (3D) here, while this shows how metaballs look in motion. You can write this as a shader, if you want to use the GPU.

Alternatively, in late 80's / early 90's demos they sometimes just use transparent sprites and move them down the screen irrespective of one another. It doesn't look too bad, but it's not very realistic. However kudos to those guys back in the day for keeping things simple. I think there are some blendmodes on some platforms that do not add to each other's effect, i.e. they will just merge. This would look somewhat better, using the same approach.
> 3 votes

# Answer
Unless rain is especially important in your game I'd go with a fairly simple simulation like the one used for MotoGP described here by Shawn Hargreaves:

> Jay (the lead artist) and I found one of those sprays like you use for misting plants, and spent some time squirting it on the office window, then examining the resulting droplets from different angles and against different backgrounds. Here's what we learned:
>
> * Droplets are egg shaped: roughly oval, but wider at the bottom
> * Droplets have no intrinsic color of their own, unless you shine a bright light on them
> * Droplets refract light as it passes through them, so the scene behind them is inverted and distorted
> * Pretty much the entire street outside our office was visible in every droplet (but upside down and mirrored)
> * Although most droplets appeared darker on top and lighter at the bottom, we decided this wasn't an intrinsic property, but just because the sky was bright that day
>
> ...
>
> First, we made a droplet texture. We drew the shape of a typical droplet into the alpha channel, and I wrote a function (using the MotoGP equivalent of a content processor) that generated 2D refraction offsets into the red and green channels.
>
> We were already drawing the main 3D scene into a rendertarget, so we could apply postprocessing effects such as motion blur. It was trivial to draw a number of 2D droplet sprites over the top, using a pixel shader that sampled the droplet texture, used its refraction offset to compute texture coordinates into the main scene image, then sampled the scene at this modified location (a similar concept to this XNA Framework sample).

The linked article includes how they overcame performance challenges in order to maintain 60 fps performance.
> 3 votes

# Answer
I found a good paper related to this topic: "Realistic real-time rain rendering" by Rousseau, et. al. They survey several current techniques (with references) and describe a new algorithm and their GPU based implementation
> 0 votes

# Answer
Just maybe, you already spelled out your solution, it will just be your job to implement it.

Looking at what you've mentioned, you have the following things to implement:

1. Metaballs in 2D
2. Estimated mass from size of Metaball
3. Estimated surface tension (a constant)
4. Whether F=mg is enough to overcome the surface tension.

This will give you the desired effect; a more advanced implementation may then introduce metaballs which are "left behind" when the source metaball has a non-zero velocity. Then just apply a function that randomly generates impacting raindrops by throwing metaballs at your surface from a specified vector.

As for the performance of this, your on your own :P.
> 0 votes

---
Tags: 2d, physics, simulations
---


title: How do I make complex AI manageable?

text:
# Question
Title: How do I make complex AI manageable?
In the past, I've used simple systems like finite state machines (FSMs) and hierarchical FSMs to control AI behavior. This pattern falls apart very quickly or any complex system.

I've heard about behavior trees. They seem like the next obvious step, but I haven't seen a working implementation or really tried it yet.

What other patterns can make complex AI behaviors manageable?

# Answer
Behaviour trees are a really great way to manage AI, and Ai Game dev is the best place to learn about them! There are tonnes of example implementations out there on places like Codeplex, or even AIGD's own Sandbox engines implementation (which admitedly is fairly complex and can be hard to follow).

Last year at the game AI confrence there was alot of excitement about planners, but this year alot of that had fallen away. Best tip seemed to be just to start simple. The whole 20% of the work to get you 80% there thing seems to totaly hold true in most cases
> 3 votes

# Answer
One think I think is important is to seperate why an agent wants to acomplish something from how it does it. Goal-orientated Action Planners do this well, but there are also other solutions. This gives you great flexibility for constructing agents as you can pick and choose from a bucket of goals and a bucket of actions.

Behaviour trees are designed to ecompass the whole solution - decision making as well as actions - and as such can be hard to maintain.
> 2 votes

# Answer
One technique you should be familiar with in any case is the action list approach. At the simplest level, it's just a list of action objects, which each action object has its update() method called each frame. You can quickly expand on this however to allow blocking actions, multiple lanes of actions, child groups, etc. Just about anything you can build with a high-level FSM can be implemented in a more modular, flexible, and debuggable fashion with an action list using behavior actions.

Aside from being a useful technique for managing all the animation, path finding, and other miscelleneous "stuff" your characters can do, it makes it trivial to implement a priority-based decision making system by creating behavior actions.

A few notes about how to use them can be found in this slide deck: http://sonargame.com/2011/11/01/new-game-slides/

Pretty sure there's been articles about it in the AI Programming Wisdom series, too.
> 2 votes

---
Tags: architecture, ai, behavior
---


# Question
Title: Open GL ES 2.0 Android Texture,Shader, etc... loading
I have gotten texture's to load along with shader's however it seems that I can only create shaders and textures in onSurfaceCreated in my implementation of the render interface. Is this truly the only place one can create shaders, textures, ...?

# Answer
> 1 votes
No you don't need to compile your shader in there, but you need to do it after the creation of the GLSurface, because you need an active OpenGL Context to be present.

Usually, I have a separate thread that I use to setup all my 3D scene, thene when all objects are created, I load my textures, meshes and shaders into opengl.

---
Tags: android, opengl-es2
---


title: RK4 Bouncing a Ball

text:
# Question
Title: RK4 Bouncing a Ball
I am trying to wrap my head around RK4. I decided to do the most basic 'ball with gravity that bounces' simulation. I have implemented the following integrator given Glenn Fiedler's tutorial:

```
/// <summary>
/// Represents physics state.
/// </summary>
public struct State
{
    // Also used internally as derivative.

    // S: Position
    // D: Velocity.
    /// <summary>
    /// Gets or sets the Position.
    /// </summary>
    public Vector2 X;

    // S: Position
    // D: Acceleration.
    /// <summary>
    /// Gets or sets the Velocity.
    /// </summary>
    public Vector2 V;
}

/// <summary>
/// Calculates the force given the specified state.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="t">The time.</param>
/// <param name="acceleration">The value that should be updated with the acceleration.</param>
public delegate void EulerIntegrator(ref State state, float t, ref Vector2 acceleration);

/// <summary>
/// Represents the RK4 Integrator.
/// </summary>
public static class RK4
{
    private const float OneSixth = 1.0f / 6.0f;

    private static void Evaluate(EulerIntegrator integrator, ref State initial, float t, float dt, ref State derivative, ref State output)
    {
        var state = new State();

        // These are a premature optimization. I like premature optimization.
        // So let's not concentrate on that.
        state.X.X = initial.X.X + derivative.X.X * dt;
        state.X.Y = initial.X.Y + derivative.X.Y * dt;
        state.V.X = initial.V.X + derivative.V.X * dt;
        state.V.Y = initial.V.Y + derivative.V.Y * dt;

        output = new State();
        output.X.X = state.V.X;
        output.X.Y = state.V.Y;
        integrator(ref state, t + dt, ref output.V);
    }

    /// <summary>
    /// Performs RK4 integration over the specified state.
    /// </summary>
    /// <param name="eulerIntegrator">The euler integrator.</param>
    /// <param name="state">The state.</param>
    /// <param name="t">The t.</param>
    /// <param name="dt">The dt.</param>
    public static void Integrate(EulerIntegrator eulerIntegrator, ref State state, float t, float dt)
    {
        var a = new State();
        var b = new State();
        var c = new State();
        var d = new State();

        Evaluate(eulerIntegrator, ref state, t, 0.0f, ref a, ref a);
        Evaluate(eulerIntegrator, ref state, t + dt * 0.5f, dt * 0.5f, ref a, ref b);
        Evaluate(eulerIntegrator, ref state, t + dt * 0.5f, dt * 0.5f, ref b, ref c);
        Evaluate(eulerIntegrator, ref state, t + dt, dt, ref c, ref d);

        a.X.X = OneSixth * (a.X.X + 2.0f * (b.X.X + c.X.X) + d.X.X);
        a.X.Y = OneSixth * (a.X.Y + 2.0f * (b.X.Y + c.X.Y) + d.X.Y);
        a.V.X = OneSixth * (a.V.X + 2.0f * (b.V.X + c.V.X) + d.V.X);
        a.V.Y = OneSixth * (a.V.Y + 2.0f * (b.V.Y + c.V.Y) + d.V.Y);

        state.X.X = state.X.X + a.X.X * dt;
        state.X.Y = state.X.Y + a.X.Y * dt;
        state.V.X = state.V.X + a.V.X * dt;
        state.V.Y = state.V.Y + a.V.Y * dt;
    }
}

```

After reading over the tutorial I noticed a few things that just seemed 'out' to me. Notably how the entire simulation revolves around `t` at 0 and `state` at 0 - considering that we are working out a curve over the duration it seems logical that RK4 wouldn't be able to handle this simple scenario. Never-the-less I forged on and wrote a very simple Euler integrator:

```
static void Integrator(ref State state, float t, ref Vector2 acceleration)
{
    if (state.X.Y > 100 && state.V.Y > 0)
    {
        // Bounce vertically.
        acceleration.Y = -state.V.Y * t;
    }
    else
    {
        acceleration.Y = 9.8f;
    }
}

```

I then ran the code against a simple fixed-time step loop and this is what I got:

> 0.05 0.20 0.44 0.78 1.23 1.76 ... 74.53 78.40 82.37 86.44 90.60 94.86 99.23 103.05 105.45 106.94 107.86 108.42 108.76 108.96 109.08 109.15 109.19 109.21 109.23 109.23 109.24 109.24 109.24 109.24 109.24 109.24 109.24 109.24 109.24 109.24 109.24 109.24 109.24 109.24 ...

As I said, I was expecting it to break - however I am unsure of how to fix it. I am currently looking into keeping the previous state and time, and working from that - although at the same time I assume that will defeat the purpose of RK4.

How would I get this simulation to print the expected results?

# Answer
Try this: run your Runge-Kutta integration to compute the motion, and then *when it's done* check for the bounce condition and update your state. It worked for me. And yes, this does mean that you still have to patch up the inter-penetration like you would with Euler integration.

I can't claim this authoritatively, but I think step changes don't go well with the RK4 state evaluator function.
> 1 votes

---
Tags: c#, physics, rk4
---


# Question
Title: How to set TextureFilter to Point to make example Bloom filter work?
I have simple app that renders some particles and now I am trying to apply the bloom shader from the xna samplers ( http://create.msdn.com/en-US/education/catalog/sample/bloom ) to it, but I am running into this exception:

"XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Vector4."

When the BloomComponent tries to end the sprite batch in the DrawFullscreenQuad method:

```
        spriteBatch.Begin(0, BlendState.Opaque, SamplerState.PointWrap, null, null, effect);
        spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
        spriteBatch.End(); //<------- Exception thrown here

```

It seems to be related to the pixel shaders that I am using to animate the particle. In a nutshell, I have a texture2d in vector4 format that holds particle positions, and another one for velocities. Here is a snippet from that area:

```
        GraphicsDevice.SetRenderTarget(tempRenderTarget);
        animationEffect.CurrentTechnique = animationEffect.Techniques[technique];
        spriteBatch.Begin(SpriteSortMode.Immediate,
                          BlendState.Opaque,
                          SamplerState.PointWrap,
                          DepthStencilState.DepthRead,
                          RasterizerState.CullNone,
                          animationEffect);

        spriteBatch.Draw(randomValues, new Rectangle(0, 0, width, height), Color.White);
        spriteBatch.End();

```

What I comment out the code that calls the particle animation pixel shaders the bloom component runs fine. Is there some state that I need to reset to make the bloom work?

# Answer
`GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap;`

This will set the first `SamplerState` to `PointWrap`. Do this before you call your `spriteBatch.Begin();`.
> 0 votes

---
Tags: c#, xna-4.0, hlsl, fragment-shader
---


# Question
Title: Directory paths for resources and assets
If I have a file stucture for my final, released game something like:

* Main folder
    + Media
        - Images
        - Other assets
        - Sounds
    + Executable
    + List item

And a different one for my 'in development' project, with the same Media folder but:

* Main
    + Source and .obj, etc.
    + Media with everything
    + Bin folder with executable

I obviously cannot hardcode file pathnames into this, like:  `"../Media/Image/evilguy.png" or "Media/Image/foo.jpg"`  because they wouldn't work with one of the builds and would require a lot of switching names.

Instead, does it make sense for my resource manager, that loads everything, to have some kind of prefix path? Then, I can just do  `Get("foo.jpg") or Get("Sounds/boom.ogg")`
And simply switch out, for the final release, the ctr argument from the relative path for the development build to the release layout?

If not, how have other people sorted these sorts of things out?

# Answer
That absolutely makes sense. You should not have any constant path in the string you pass to your Get function, or else it ties you down later. For example, if you decide to package your assets into some sort of compressed/encrypted archive, you would then be locked down to create an useless Media folder in the archive and then put all the assets inside it, when really the archive itself is something of a Media folder.

Your resource manager should know where to go to find the resources, whether it's the file system, an abstraction (archive), perhaps a distributed file system, or even the network or internet.

I personally also think `Get("Sounds/boom.ogg")` might be redundant; doesn't the "ogg" extension establish it as a sound? Again, if this is the case, you could just use `Get("boom.ogg")` and the resource manager could look at the extension and know to go into the Sounds folder. But it's totally up to you.
> 2 votes

# Answer
You don't really need a full on resource manager in this case. But yes, it's pretty common to have your assets to be arranged in a particular structure under some root, but for the code to all be written in ignorance of what that root is.

Rather than a resource manager though, you can just have an indirection step that resolves a relative path into an immediately usable path. So:

```
LoadWAV(GetAssetPath("audio/SomeEvent.wav"));

```

which resolves to

```
LoadWAV("/projects/myproject/build/audio/SomeEvent.wav");

```

when running from your local machine or

```
LoadWAV("game:/audio/SomeEvent.wav")

```

when running from a DVD build.
> 0 votes

# Answer
You could also use resource IDs to decouple your resources from paths. On your development environment you would have a file such as:

```
<resources>
 <resource id="1" name="SomeFile" path="sounds/somefile.ogg" />
 <resource id="2" name="TrollFace" path="images/trollface.png" />
</resources>

```

You would then have a tool that would auto-generate a file in your programming language, such as:

```
public static class Resources
{
  public static class Sounds
  {
    public const int SomeFile = 1;
  }
  public static class Images
  {
    public const int TrollFace = 2;
  }
}

```

Your resource manager would have the following interface:

```
public interface IResourceManager
{
  IResource Load(int resourceId);
}

```

You would then auto-generate a portion of `IResourceManager` from the XML file, for example:

```
partial class IResourceManager
{
  private static string Lookup(int id)
  {
    switch(id)
    {
      case 1: return "sounds/somefile.ogg";
      case 2: return "images/trollface.png";
    }
  }
}

```

Loading a resource would then simply be something along the lines of:

```
resourceManager.Load(Resources.Sounds.SomeFile);

```

The auto-generated files here would be specific to development. If, for example, you chose to use a zip container or such you could possibly use the id as the filename within the zip (e.g. '1.bin') and switch the `IResourceManager` implementation.

Keep in mind that this would eliminate the possibility of modding.
> 0 votes

---
Tags: loading, file, release
---


# Question
Title: How to resolve concurrent ramp collisions in 2d platformer?
A bit about the physics engine: Bodies are all rectangles. Bodies are sorted at the beginning of every update loop based on the body-in-motion's horizontal and vertical velocity (to avoid sticky walls/floors). Solid bodies are resolved by testing the body-in-motion's new X with the old Y and adjusting if necessary before testing the new X with the new Y, again adjusting if necessary. Works great.

Ramps (rectangles with a flag set indicating bottom-left, bottom-right, etc) are resolved by calculating the ratio of penetration along the x-axis and setting a new Y accordingly (with some checks to make sure the body-in-motion isn't attacking from the tall or flat side, in which case the ramp is treated as a normal rectangle). This also works great.

Side-by-side ramps, eg. `\/` and `/\`, work fine but things get jittery and unpredictable when a top-down ramp is directly above a bottom-up ramp, eg. `<` or `>` or when a bottom-up ramp runs right up to the ceiling/top-down ramp runs right down to the floor.

I've been able to lock it down somewhat by detecting whether the body-in-motion `hadFloor` when also colliding with a top-down ramp or `hadCeiling` when also colliding with a bottom-up ramp then resolving by calculating the ratio of penetration along the y-axis and setting the new X accordingly (the opposite of the normal behavior). But as soon as the body-in-motion jumps the `hasFloor` flag becomes false, the first ramp resolution pushes the body into collision with the second ramp and collision resolution becomes jittery again for a few frames.

I'm sure I'm making this more complicated than it needs to be. Can anyone recommend a good resource that outlines the best way to address this problem? (Please don't recommend I use something like Box2d or Chipmunk. Also, "redesign your levels" isn't an answer; the body-in-motion may at times be riding another body-in-motion, eg. a platform, that pushes it into a ramp so I'd like to be able to resolve this properly.)

Thanks!

# Answer
There are two things you generally do in a "real" physics engine to resolve issues like these. It sounds like you're basically writing a simplified separating-axis style of collision response, but then trying to immediately correct position based on each collision. That leads to jitter in exactly the kinds of scenarios you describe.

The first technique you can use is to simply detect all collisions first, then resolve them. That is, instead of detecting that the object has collided with a bottom ramp, fixing the position, then checking for the top ramp, and fixing again, test and see that the object is colliding with both ramps and then calculate a correction that pushes the object out of both items. This can be done generically for ramps, walls, floors, ceilings, and other objects fairly well (but not perfectly in particularly complex scenarios).

The second technique -- which is best combined with the previous technique -- is to run through several iterations of the collision resolution each game update loop. If you think about it, your problem is basically that it takes several frames for your collisions to be fully resolved, because you're only doing one physics pass per frame. If you were to do 10 iterations of the physics handles for each object each frame, your problem would likely disappear (in your current situations at least).

Those are both fundamental requirements for a proper physics engines. Platformers are rarely implemented using proper physics, of course, not least of all because real physics don't make for good platformer behavior (which needs to be closer to Mario physics to "feel" right).

Platformers (and even many modern games) use character controllers that are not modeled after physics at all. It's not at all uncommon to just use a bunch of ray/segment casts *before* moving the character to see if or what it will collide with, and then moving it appropriately. For a rectangular hit box, for instance, you might do some segment/level collision tests for three or so hotspots per side of the character, and then use the detected limits along with the current velocity to move the character without ever penetrating the level geometry. This technique does not work well with the upside down V shapes though (^, /\\, however you want to draw it), so if your level uses those you might also want to combine with a simple resolution system that pushes the character up if it goes through any floors. Walking up ramps is just more special logic detecting that the player is trying to move into an angled surface. Likewise, walking down ramps is a special case that is explicitly checked for, which actually can result in much better behavior that the "physics" way of doing things (where characters tend to walk off, fall down onto, and then jitter down ramps; this is visible even in many AAA games today that are trying to use physics to model character movement). Moving platforms are again just another set of special checks and rules for resolving collisions and pushing. You can mix this character controller with a physics engine to allow players to push physically-modeled boxes and other objects around as well.
> 3 votes

---
Tags: collision-detection, physics, collision-resolution
---


title: Dealing with disconnected users

text:
# Question
Title: Dealing with disconnected users
Just a strange question. I was thinking about it today. About a poker game website/apps or any online gaming platform with money being involved.

What would be the best way to deals with disconnected users trying to avoid a loss or maybe real disconnection.

I doubt pausing the game until that player comes back is very suitable.

Any ideas? Suggestions?

# Answer
> 2 votes
Amount they bet stays in the pot and their chips get put back into their account. If they want to re-enter the game then allow them.

Is there more to your problem than what you're asking?

---
Tags: game-design, online
---


# Question
Title: Secure login for a game that is open source
I am making a game which i will be open sourcing. Its a simple arcade like game but requires a network connection because it is meant to be played with other people.

The thing i am worrying about is how would i be sure that the client is the one that i put out for the end user to play with? Kind of a like of sv\_pure for Team Fortress 2.

I was thinking of different ways to combat this such as the server requesting the client's version or even it's md5 hash but people with simple java knowledge could just force a method to always return what the server wants.

# Answer
There is *no* way to guarantee that the client in use is the client you want them to be using, there are *always* ways around every technique, *even* with a closed source application. When it comes down to it, with a closed-source application, any good reverse engineer with some free time can spoof packets to/from your server. In an open-source application, it would be even easier to have some fun. All you can do is make sure to give the client limited control over the game. The less control you give the client, the less you have to worry about *what* is sending your server packets.
> 20 votes

# Answer
I have 2 rules of networking that I keep in the back of my mind when programming.

1. **Give the client, only what information it needs**. This isn't completely relevant to the question, but still on the same topic. The client doesn't need the position of all the gold in the map, if they are no-where near it
2. **Keep it server side**.
> 2 votes

---
Tags: networking, open-source, security
---


# Question
Title: The Correct Usage of DLLs with a DirectX Game?
I'm using DirectX 10 (in C++) to make a game engine, and a test driver program on top of it.

Now that I've written many messy rough drafts of an engine, I want to make the final (or sorta final) clean version. I choose to follow how I've seen other engines do it, and that's to have all the core nasty messy crap in a DLL, and then you can create games with just a few functions (well, not really :D).

However, I'm unsure of what nasty messy crap to put in that DLL. I don't know about speed restrictions with DLLs. What I've done is put my winproc in the DLL, and have a class that takes the messages, and sends them through to the program using the DLL. Then that program does what it needs to do, and calls a rendering functions back in the DLL that renders everything.

Only problem is it gets very low FPS (2, to be exact...). I've looked through everything, and I don't know if the way I'm using DLLs in causing this, or its something different.

Whether it's the DLLs or not, I still want to know how to use a DLL correctly with a game engine. I like being neat, I hate having to see all those long names of DirectX classes. I use typedef a lot.

# Answer
> 5 votes
Your 2 FPS experience is most likely on account of something else in your code rather than use of a DLL. When loaded a DLL is mapped into the same address space as the main process, so a function call into a DLL is really nothing more than transferring execution to another address (with the standard stack work, of course).

Quake II used a DLL for it's renderer back in 1997 and certainly didn't exhibit any of these problems, so neither should you.

The only other thing I can think of is that you might be doing a LoadLibrary/GetProcAddress/make function call/FreeLibrary around each call you make into the DLL. That would certainly generate quite a bit of additional overhead, but - with the caveat that I haven't tested this particular use case - I doubt it would be so extreme.

Time for you to break out the debugger and profiler, and dig a little into what's going on inside your code I think.

Final note. This whole pattern is, I think, a variation on premature optimization. I'll call it "premature cleanliness", but it's just as evil. You know that you want to break out certain functions into a DLL, but you haven't actually sat down and mapped out exactly how you want to go about it yet. That's a pretty important thing to do before you actually start doing it. Ditto with your heavy use of typedefs to mask the D3D names. That's going to impact quite a lot on your ability to use documentation and other examples. You're better off swallowing your distaste and focussing on the end result.

# Answer
> 4 votes
You're intent on separation of "nasty" code from "non-nasty" code. That's what OOP encapsulation is for. Classes are as good as you'll ever need, since separation of code is a coding/compile time concern, not a runtime concern as DLLs are.

Not only that, but by factoring/organising your code into classes, you will have a better understanding of how they fit into the bigger picture. Assuming not all of this code comes from the depths of your own mind, it will also force you to understand it marginally better.

PS. Where did you get this idea that different parts of your game need to go into separate DLLs? Don't assume that because eg. graphics and networking libraries you may be making use of, are provided as DLLs, that you have to componentise your game's executable code to this degree as well. That's just misguided.

---
Tags: c++, directx10
---


# Question
Title: 3d Maya object mesh problems when used in Unity
Asking for help to solve a problem 3d Maya objects imported in Unity to make an ios app. Maya object change when imported on Unity mesh attributes disappears and mesh structure comes evident. Has anyone some suggestion to fix this problem?

# Answer
Unity converts models to .fbx format when importing them. As such, mesh attributes aren't retained because the .fbx format doesn't store them. You can add some things Unity-side to reassign and use attributes—using either scripts or layers depending on your needs.

I'm not sure what you mean by "mesh structure come evident" so I can't offer any insight there. Can you clarify/reword?
> 1 votes

---
Tags: unity, maya
---


title: Dynamic model interactions

text:
# Question
Title: Dynamic model interactions
I am just curious as to how in many games (namely games like arkham asylum/city, manhunt, hitman) do they make it so that your character can "grab" a character in front of you and do stuff to them. I know this may sound very confusing but for an example go to youtube and search "hitman executions", and the first video is an example of what i'm asking.

Basically I'm wondering how they make your model dynamically interact with whatever other model you come across, so in hitman when you come up behind some one with the fibre wire you strangle the other character or if you have the anesthetic you come up behind some person and put your hand over there mouth while they struggle and slowly go to the floor where you lay them down. I am confused as to whether it was animated to use two models using specific bone/skeletal identifiers, if it is just two completely separate animations that are played at the correct time to make it look like they are actually interacting or something else all together.

I am not an animator so i assume most of what i just said is not right but i hope that some one can understand what i mean and provide an answer.

PS) I am a programmer and I am in the process of building a hitmanesque game, just because i love that style of game and I want to increase my skills on something fun, so if you do know what i'm talking about have some examples with involving both models and programming (i use c++ and mainly Ogre3D at the moment but i am getting into unity and XNA) i would greatly appreciate it.

Thanks.

# Answer
I suspect they're synced animations, since that would under most circumstances (i.e. where characters are on the same floor level) be the easiest to implement. You can see that the Hitman animations are actually not particularly well synced, even so (swordstick scene). It was already a fairly revolutionary game for it's time so I think players were willing to overlook small inaccuracies; gamers I knew at the time certainly didn't complain.

Aside from that, there are some pretty amazing physically driven solutions these days for character animation, eg. Euphoria and Rune Skovbo Johansen's Locomotion system for Unity, to name but a couple. In Euphoria, you can see from their videos the degree of physical realism is *insane*. That system was used for GTA 4, Red Dead Redemption, and Star Wars: The Force Unleashed. There's no doubt it could pull off the example you gave, with ease. It also hints at the amount of development effort that goes into reactive animation.

It would be perhaps too time-consuming for an individual developer to do more than the sync'ed animations approach, and even that can have it's problems: characters at different heights, for example, you might need to bend their torso to make the attack on the other character, but that can have its own problems (eg. when strangling / slitting throats), such as if the angle is too acute. I guess one solution to that might be to have the character bend at the knees slightly, in order to get an even torso height with his victim. Bit like lining up for a golf shot, old chap.
> 4 votes

---
Tags: xna, unity, animation, models, ogre
---


# Question
Title: Where can I get a list or data base of light reflectance values for different materials?
I'm implementing lighting for a WebGL app but I'm not an artist so I don't know how to generate or where to obtain a list of materials with its values (diffuse, specular, ambient and shininess). I've been searching a lot but with no luck.

Is there any list or DB I might have overlooked? Any common repository or something similar?

Thanks in advance.

Note: English is not my main language, let me know if you don't understand something and I'll try to rephrase it.

# Answer
Great question! There are a few online repositories of measured optical data about various materials.

BRDFs:

1. http://www.merl.com/brdf/
2. http://www.cs.columbia.edu/CAVE/software/curet/

These are tabulated according to incoming and outgoing light direction, so if you want to approximate them as diffuse and specular, you'll have to fit those curves to the data yourself. You'll probably want to read up on BRDFs and also physically-based shading. (This is a huge area of research, so there's a lot to learn!)

For refractive indices. there's http://refractiveindex.info/ as you already mentioned; and in case you're interested, there is also some measured photometric data available about light sources - how bright they are and how they distribute light in different directions: http://www.americanelectriclighting.com/Library/Photometry/
> 6 votes

---
Tags: materials, reflection-rendering
---


title: Planar shadow matrix and plane b value

text:
# Question
Title: Planar shadow matrix and plane b value
I implemented planar shadows with the function D3DXMatrixShadow.

As you know, we need plane and light factor to calculate a shadow matrix.

The problem is that when I set the plane as D3DXPLANE p(0, -1, 0, 0.1f), the shadows by directional light are correctly rendered, but the shadows by point light are not rendered.

However, if I use D3DXPLANE p(0, 1, 0, 0.1f), the situation is reversed, shadows by directional light are not drawn, the shadows by point light are ok.

I cannot understand why it happens. Is it normal or am i missing something? Please explain to me why this happens.

Thanks in advance.

Code

```
//main.cpp
ID3D10EffectTechnique* oldTech = meshes[i]->technique;

D3DXPLANE groundPlane(0, -1, 0, 0.01f);
D3DXMATRIX S;//shadow matrix
D3DXVECTOR4 light;
if(lightType != 2) //2 here means point light
{
    light.x = lightDirection.x;
    light.y = lightDirection.y;
    light.z = lightDirection.z;
    light.w = 0;
}
else
{
    light.x = lightPosition.x;
    light.y = lightPosition.y;
    light.z = lightPosition.z;
    light.w = 1;
    groundPlane.b = 1;
}

D3DXMatrixShadow(&S, &light, &groundPlane);
D3DXMATRIX W = meshes[i]->GetWorldMatrix();
D3DXMATRIX matWorld = W * S;

meshes[i]->technique = shadowTechnique;
meshes[i]->render(&matWorld);
//Meshes here are drawn by ID3DX10Mesh,
//but I tested other code with LPD3DXMESH, it has the same problem.

meshes[i]->technique = oldTech;

 //shader code(.fx file)
 PS_Input VS_Shadow(VS_Input input)
 {
    PS_Input output = (PS_Input)0;
    output.pos = mul(float4(input.pos, 1), matWorld);
    output.pos.y = 0.1;
    output.pos = mul(mul(output.pos, matView), matProjection);
    output.normal = mul( input.normal, (float3x3)matWorld );
    output.color = input.color;
    output.worldPos = (float3)mul(input.pos, matWorld);
    output.tex = input.tex;
    return output;
 }

 float4 PS_Shadow( PS_Input input) : SV_Target
 {
    return float4(0,0,0,0.5f);
 }

 DepthStencilState StencilIncreaseOnce {
    DepthEnable = true;
    DepthWriteMask = ALL;
    DepthFunc = LESS_EQUAL;

    StencilEnable = true;
    FrontFaceStencilFunc = EQUAL;
        FrontFaceStencilPass = INCR;
    FrontFaceStencilFail = Keep;
 };

 BlendState BlendAlpha {
    AlphaToCoverageEnable = FALSE;
    BlendEnable[0] = TRUE;
    SrcBlend = SRC_ALPHA ;
    DestBlend = INV_SRC_ALPHA ;
    BlendOp = ADD;
    SrcBlendAlpha = ONE;
    DestBlendAlpha = ZERO;
    BlendOpAlpha = ADD;
    RenderTargetWriteMask[0] = 0x0F;
 };

 technique10 ShadowRender
 {
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, VS_Shadow() ) );
        //SetVertexShader( CompileShader( vs_4_0, VS() ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, PS_Shadow() ) );

        SetDepthStencilState( StencilIncreaseOnce, 0x0 );
        SetBlendState( BlendAlpha, float4( 0.0f, 0.0f, 0.0f, 0.0f ),
                   0xFFFFFFFF ); //blendState, blendFactor, sampleMask
    }
 }

```

# Answer
Your code looks mostly correct to me. One thing that's a little weird is the `output.pos.y = 0.1;` in your VS. The reason this concerns me is that when you're using a point light, the shadow matrix is a projection matrix, and that means that after going through it your points are going to come out with w != 1.0. So you can't just set y to 0.1 to make them come out at y = 0.1...you'd have to set y to w * 0.1.

Another thing that might be an issue is a possible mismatch in the convention of `lightDirection`. I believe the function expects a vector pointing toward the light, but some people prefer to define it in terms of the direction the light is traveling, which the opposite. But if this was the probem I'd expect to see the shadows appearing to the lit side of the object instead of the shadowed side, since the whole vector would be negated and not just the y component.
> 0 votes

---
Tags: directx, shadows
---


# Question
Title: What's a good way to store a series of interconnected pipe and tank objects?
I am working on a puzzle game with a 6 by 6 grid of storage tanks that are connected to up to 4 tanks adjacent to them via pipes. The gameplay is concerned with combining what's in a tank with an adjacent tank via the pipe than interconnects them.

Right now I store the tanks in a 6x6 array, vertical pipes in a 5x6 array, and horizontal pipes in a 6x5 array. Each tank has a reference to the object that contains both tanks and pipes and when a pipe needs to be animated filling with liquid, the selected tank just calls a method on the container object telling it to animate the pipes it is connected to (subtract 1 from row or column to find connected pipes).

This feels like the wrong way of doing it, as I've also considered just giving each tank references to the pipes connected to it to access directly.

# Answer
You can easily replace your array architecture with an object-based approach where tanks have pointers to there adjacent pipes and the pipes know about their start and end object.

What you're doing here is modelling a graph. The tanks are the graphs nodes (vertices) and the pipes are the edges.

Of course you can also model a graph using an array. Usually you would use an adjacency matrix for that.

The appropriate structure really depends on your architecture and how you're accessing the data and what you're planning to do with it. The object based approach is closer to reality and might be easier to work with.
> 0 votes

---
Tags: data-structure
---


title: XNA Windows Phone 7 Sprite movement

text:
# Question
Title: XNA Windows Phone 7 Sprite movement
I'm working on a Windows phone game and I'm having difficulty with the sprite movement. What I want to do is make the sprite gradually move to the position that is touched on screen, when there is only one quick touch and release. At the minute all I can do is either make the sprite jump instantly to the touch location or move along to the touch location when the touch is held down.

Code for jumping to touch location:

```
TouchCollection touchCollection = TouchPanel.GetState();
    foreach (TouchLocation tl in touchCollection)
    {
        if ((tl.State == TouchLocationState.Pressed)
             || (tl.State == TouchLocationState.Moved))
        {
            Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y);

                if (position != newPos)
                {
                    while (position.X < newPos.X)
                    {
                        position.X += (float)theGameTime.ElapsedGameTime.Milliseconds / 10.0f * spriteDirectionRight;
                    }
                }
        }
    }

```

Code to gradually move along while touch is held:

```
TouchCollection touchCollection = TouchPanel.GetState();
    foreach (TouchLocation tl in touchCollection)
    {
        if ((tl.State == TouchLocationState.Pressed)
             || (tl.State == TouchLocationState.Moved))
        {
            Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y);

                if (position != newPos)
                {

                        position.X += (float)theGameTime.ElapsedGameTime.Milliseconds / 10.0f * spriteDirectionRight;

                }
        }
     }

```

These are in the Update() method of the Sprite class.

# Answer
> 1 votes
This should move the object to the last touch location, you can change ratio to adapt the speed. (I have developed never for wp7 but I think it should do the job)

EDIT: I didn't know TouchLocation was a struct. So I've changed the code.

```
bool Active = null;
Vector2 Target;

float ratio = 0.001f;

void Update()
{

    TouchCollection touchCollection = TouchPanel.GetState();
    foreach (TouchLocation tl in touchCollection)
    {
        if ((tl.State == TouchLocationState.Pressed)
        {
             Target =  new Vector2(tl.Position.X, tl.Position.Y);
             Active= true;
        }
    }

    if (Active)
    {

         Vector2 Delta = (Target- position) * ratio;

         if (Delta.Length()<0.001f)
         {
               position = Target;
               Active = false;
         }
         else
         {
               position += Delta;
         }
    }
}

```

# Answer
> 0 votes
I think a good way to do it is to represent the game object you are rendering as a class that has all the require information to update and render. This way you can better manage your object. For example, lets say what you are controlling is your `Player` class, it might look something like this.

```
public class Player
{
    public Vector2 Position { get;set; }
    public Vector2 Target { get;set }
    public float Speed { get;set; }
    public float DistanceToTarget { get;set; }
    public Texture2D Texture { get;set; }
    public Rectangle Source { get;set;
    public bool IsMoving { get;set; }
    private Vector2 movementVector = new Vector2();

    public void Update(GameTime gameTime)
    {
         DistanceToTarget = Vector2.Distance(Position,Target);
         if(Position != Target && IsMoving)
         {
             if(DistanceToTarget < (Speed * movementVector)) // to avoid your character getting stuck in a loop due to speed etc
             {
                  Position = Target;
             }
             else
             {
                  movementVector = Target - Position;
                  movementVector.Normailze();
                  Position += movementVector * Speed;
             }
         }
    }

```

Where you are handling your input you might want to use something like.

```
if (gest.GestureType == GestureType.Tap)
{
     myPlayer.Target = gest.Position  // assuming your world only existing within your screen
     myPlayer.IsMoving = true;
}

```

Regarding handling of input, please see the Game State Management example on the AppHub education resources for a good way to handle input state on the Windows Phone platform and how to best use Gestures. (Look for the `InputState` class)

You could do away with the bool of `IsMoving` but I think it helps with readability and you might want to know this elsewhere for something else.

Hope this helped.

---
Tags: xna, sprites, windows-phone-7
---


# Question
Title: What is the relationship between ID3D10Buffer and ID3DX10Mesh?
I'm new to Direct3D, I'm currently learning Direct3D 10 in Uni. I'm confused about buffers and meshes. We've been shown code to draw cubes etc that use `ID3D10Buffer`. However I've seen some stuff online that uses `ID3DX10Mesh` to draw cubes.

What's the advantage/disadvantage for each of them? `ID3DX10Mesh` seems more versatile, I guess this comes with a cost?

# Answer
> 2 votes
`ID3DX10Mesh` is a higher-level wrapper. Internally, I expect it uses `ID3D10Buffer`s and other things to render the mesh, but it keeps track of all the data for you and provides convenience functions that implement more complex operations. The upside is that you don't have to implement all that stuff yourself; the downside is the same one as with all higher-level wrappers, that if you want to do something outside of what it the class was designed for, it may be inefficient or even impossible.

On the other hand, `ID3D10Buffer` is a very low-level object that basically just represents a chunk of VRAM in which you can store more or less arbitrary data, and which you can use as an input to shaders. When used to store vertex and index buffers they can be used to draw a mesh, but they also store shader parameters (in which case they're called "constant buffers").

---
Tags: directx
---


# Question
Title: Is there an application that converts a PC into a video game kiosk/arcade machine?
Sorry to make the question so vague.

What I ultimately want is software that allows people to play independent video games on a PC and not have to worry about maintaining it.

Imagine a game that was made in a few hours that does not have a restart button and crashes often. It should be able to handle these kinds of things and do more!

The software should:

* allow the game to be restarted manually
* handle game crashes (likely by restarting the game)
* restrict the user from doing anything crazy

later...

* offer a UI to select the game from a list
* handle pre-configured key bindings
* cross-platform (start with windows)

I just want to know if this exists already before I start creating one. As of now AutoHotKey is being used to do this sloppily.

If such software does not exist then perhaps someone could recommend a general open source Kiosk software? Open Kiosk? I'll take anything.

(I also could not find a related tag. Not even sure if this question should be here rather than stackoverflow)

# Answer
Babycastles, the indie game arcade in NYC, is starting an initiative to help people setup similar venues. The software bundle they use for their cabinets is on GitHub: https://github.com/edibletoaster/Babycastles-Trollkit

It's still early in development, but it manages restarting games and generates AutoHotKey scripts. Since it was use for their exhibitions, it's setup to maintain just one game at a time. If you're looking to provide a Steam-like game selector for arcade machines, you might want to consider contributing to expanding these tools to add that functionality.

The Babycastles site is redirecting to the Mozilla anti-SOPA page right now, but they post a lot of info on the Facebook page, and their Tumblr and Twitter accounts.

Another project to look at is Winnitron. The way it works is they maintain a central database of games and high score tables, and anybody can build their own cabinet and request authorization. Then your own Winnitron will automatically download new games and update existing ones. They have a standard mapping of keys to the joystick and two buttons, and have a nice screen for selecting installed games to play.

It's not really available for personal use, but if you'd like to setup a kiosk in a public location you can email them to get specs and the launcher software.
> 5 votes

# Answer
MAME is exactly what you describe for arcade games. I haven't seen a general-purpose one though; Steam and OnLive are the closest things I can think of, if you were to maximize them on the screen and somehow restrict the player from closing them, not to mention keep the player from tampering with your account and so on.
> 0 votes

---
Tags: modding
---


# Question
Title: Path tables or real time searching for AI?
What is the more common practice in commercial games; path lookup tables or real time searches?

I've read that in many games path lookup tables are pre-calculated and baked into each map, so to speak, then steering behaviour is used to handle dynamic obstacles.

or is it better practice to use optimised hierarchical A\* searches? I understand the pro's and cons of each, I'm just curious as to what is most often used in the industry.

# Answer
Seeing as how I've done this a few times in the industry, here's my rule of thumb:

Always, always implement dynamic "on-demand" pathfinding first, because it's simpler, faster to code, is much (MUCH) easier to debug, is more flexible, and has fewer moving parts (doesn't require changes to file formats, makes fewer demands on the data pipeline, etc).

I'm currently working on a commercial racing game which has fixed but branching tracks. Even though each track might only have four or five possible routes to reach the finish line, each car (8+ of them) is dynamically generating its own path from the starting point to the finish line, independently from the other cars. You might call it a waste for the cars to generate these same paths over and over again. But it's not -- it's simply faster and easier for me to code it this way than to bother with doing it as a pre-process, which means I can spend more of my time on things which actually will be noticed and valued by the end-user. Or to put it differently; we're trading a vanishingly small amount of CPU time for a whole lot of my time.

Pre-building paths is a form of code optimisation, and as such, you really shouldn't be thinking about it at all until profiling has shown that the dynamic approach is actually having a measurable impact on performance. In many (most?) cases, it doesn't. And so the fast-to-implement and flexible "dynamic, on demand" approach should always be preferred, until concrete profiling shows otherwise.
> 4 votes

# Answer
That's entirely dependent on the type of game and the requirements. In a game where there are lots of entities and therefore lots of path-finding queries, a lookup-table will come in handy.

In highly dynamic worlds or worlds with lots of possible paths, lookup-tables are either useless or not practicable (as they would potentially consume huge amounts of memory).

Albeit my insight into "the industry" is quite limited, I think it's common sense to use the tool that's best suited for the job. In some cases this might be a lookup table, in other cases real-time search is the way to go.
> 2 votes

# Answer
Precalculate whatever you can. Do real-time searches through the rest.

To look at it one way, almost every single implementation has a bit of both - you can't perform an A\* search without a graph, so someone had to create the graph, usually as part of the level design process. And even if you do A\* searches, for pretty much everything but turn-based strategy games you still have to move smoothly from one node to the next, meaning some sort of steering operation is going on (even if it's a trivial linear interpolation).

Also, don't assume everybody is using hierarchical A\* for searches. Often just a plain A\* is fine, and sometimes forming a decent hierarchy is difficult. Sometimes people use different variations on A\*, such as IDA\*.
> 1 votes

# Answer
Use the simplest-to-implement approach that you can afford to use.

* If, for example, your game has preset maps, and it's easier for you to bake paths in while creating the map asset, do so.
* If it has preset maps, but you have eg. only one artist and one coder, and the artist has a lot of work to do already, the coder can write in a dynamic pathfinder.
* If your game has only procedurally generated maps, then obviously pathing has to be calculated at runtime, but runtime here could mean either precalculating paths before play begins, but after the map is generated, or it could mean simply calculating pathing during play.

Keep it simple inasmuch as possible, unless you have a pressing need to make things more complex.
> 0 votes

---
Tags: ai, path-finding
---


# Question
Title: Converting from different handedness coordinate systems
I am currently porting a demo from XNA to DirectX which, as I understand it, both have coordinate systems with different handednesses.

What are the things I need to bare in mind when converting between the two? I understand not everything needs to be changed.

Also I notice that many of the 3D maths functions in some of the direct3D libraries have right handed and left handed alternatives. Would it be better to just use these?

# Answer
Direct3D doesn't actually specify any handedness, so it's no longer correct to say things like "D3D has a left-handed coordinate system". You can in fact use either left-handed or right-handed in D3D; just select either of the -LH or -RH versions for the projection matrix setup functions and that is all that is required.

For example, look in your DirectX SDK for D3DXMatrixPerspectiveFovLH and D3DXMatrixPerspectiveFovRH.

The important thing is that you're consistent in your own code, so that you don't need to switch back and forth between each system. If you're dealing with existing code you should respect it's system and convert as required, but if you're porting from XNA (or from OpenGL for that matter) then just set D3D up to be right-handed too, and be done with it.
> 4 votes

# Answer
First of all, I'll refer you to an answer of mine I posted a while back:

Why / how does XNA's right-handed coordinate system effect anything if you can specify near/far Z values?

The only real difference with the change in handedness is what happens on the Z-axis.

XNA is right handed (positive Z moves out of the screen) and DirectX can be left handed (positive Z moves into the screen) or right handed, as pointed out by mh01. Refer to his answer to make use of the right handed functionality of DX.

The easy way of converting vertices etc from one system to the other is just to negate the Z value.

Another difference you might notice is that a positive rotation along the Z axis will be different. Easiest way to figure it out: Make 2 thumbs up and point your thumbs towards you. The direction in which your fingers coil around to make a fist on your left hand is a positive rotation in the left handed coordinate system. Right hand, right-handed coordinate system.

If you've got the functions available to you form DirectX, then by all means use them. Test them out, if they work for you, great; if not, observe what's going wrong and feel free to ask another question :)
> 2 votes

---
Tags: 3d, mathematics, directx, coordinates, directx10
---


# Question
Title: Is it possible to use SFML with the Android NDK?
I've started using SFML recently and I absolutely love it. I'd like to make games that could be ported to android, linux, mac and windows, but it seems that SFML lacks portability.

I've searched for a while and I've only found unrelated or unanswered questions on forums.

Does anyone know of any way to use SFML with the android NDK or any plans to support it in the future?

# Answer
> 4 votes
I asked this few months ago, the answer is : not at the moment. It's possible but it requires some changes. Currently there is a rewriting for the 2.0 release so maybe after it's done it will be possible to add this.

As it's an open-source project I guess if there is a simple way to help the SFML author, you could propose a patch once 2.0 is done.

source : http://www.sfml-dev.org/forum/viewtopic.php?t=2503

---
Tags: android, sfml
---


title: Moving two objects proportionally

text:
# Question
Title: Moving two objects proportionally
I'm trying to move two objects away from each other at a proportional distance, but on different scales. I'm not quite sure how to do this. Object A can go from position 0.1 to 1. Object B has no limits. If object B is decreasing, then Object A should be decreasing at rate R. Likewise, if Object B is increasing, then Object A increases at rate R. How can I tie these two Object positions together so that in an update loop, they automatically update their positions?

I tried using:

```
ObjA.Pos.X +=  0.001f * ObjB.VelocityY; //0.001f is the rate

```

This works but there's an error each time it runs. ObjA starts off at its max position `1` but then the next time it will stop at 0.97, 0.94, 0.91 etc.. This is due to the `0.001f` rate I put in. Is there a way to control the rate, yet not end up with the rounding error?

EDIT - To clarify the scenario: The user can provide a force to Object B in a vertical motion (2D game). Gravity will bring the object back down once the user lets go of the up/down button. As the object moves up or down, I want object A to move left and right on the X axis. Maximum distance to the right can be '1', and to the left can be '0.1'. Therefore, if the user keeps holding up forever,object A will still only be at 0.1.

> Object A at max 1 = Object B at position 4.5 (this is the starting position)
>
> Object A at min 0.1 = object B at position +/- 9.9

Obejct B does take the game time into account.

# Answer
You could just set object A's x coordinate directly based on object B's y coordinate:

```
ObjA.Pos.X = 1 - 0.9 * Math.Max(0, Math.Min(1, (ObjB.Pos.Y - 4.5) / (9.9 - 4.5)))

```
> 1 votes

---
Tags: c#, mathematics, algorithm
---


# Question
Title: User generated content: a basic yet simple to use OR a complex yet powerful solution?
As stated above, which solution is better for a game based on user generated content?

1. The simple solution (in-game editor) is great for gamers without experience in coding and etc. In this way every player could populate the game with content. But the content would be very limited.
2. The complex solution would allow the content to be with almost no limitation but casual gamers probably couldn't make hardly any content at all.

If both solutions are used, the quality behind the second solution would be more valuable than the first solution's quantity.

However, making a powerful in-game editor could even take more time and manpower than the actual game and every gamer would have to learn how to use the new complex tool, understand it, and master it if he or she wants to make quality content.

You would be able to make levels and objects for it as well as the player model itself.

# Answer
I think there's a fake dichotomy here. It's possible to make simple, yet powerful tools. The key is how you present them to the users, and what frame of mind you're going in to when designing them.

This also depends on what, exactly, type of tools you're talking about here. Do you mean that users would be editing levels a la Atmosphir or Little Big Planet, or is it more all inclusive like Second Life?

If you're talking about the former, you can make everything work within your system and do some things to prevent mistakes and issues with authoring content.

For example, you can implement a visual scripting system a la Kismet and have it be very powerful but still safe for users to use. When users are authoring content, find out what issues there are with the content being generated and try to prevent it from happening in the first place. If you set up some kind of system that has triggers and effects, don't let players save the level that doesn't have everything that needs to be hooked up, hooked up. If the game is a platformer, have some logic that determines that maximum distant/height people can jump and warn the user if they have made something that's physically impossible to complete. That kind of thing.

One other thing to keep in mind is the amount of investment you expect people to have in the game. It may be harder to author content in Second Life, but then again you can sell your creations. If your game doesn't have some mechanism to empower users to do something meaningful with their content, then you need to keep it simple.
> 3 votes

# Answer
This may not be that helpful, but I think the goal should be an editor in which it's easy to do simple things, but scales gracefully to allow advanced users to do complex things. I'd rather not have two editors. Provide some tutorials that cover the range from simple to advanced use.

Also consider developing the editor as a tool for your own team and use it to build your own content; that'll make it easier to justify the development cost and also provide much more comprehensive testing than you'd be likely to get otherwise. You'll probably need to provide "backdoors" to allow the team to bring in custom assets, scripts, etc. but try to discourage this where not absolutely necessary, and make it easy for team members to add new tools/features to the editor.
> 1 votes

---
Tags: user-generated-content
---


# Question
Title: Why is my model's scale changing after rotating it?
I have just started a simple flight simulator and have implemented Roll and pitch. In the beginning, testing went very well; however, after about 15-20 seconds of constantly moving the thumbsticks in a random or circular motion, my model's scale begins to grow. At first I thought the model was moving closer to the camera, but i set break points when it was happening and can confirm the translation of my orientation matrix remains 0,0,0. Is this a result of Gimbal Lock?

Does anyone see an obvious error in my code below?

```
    public override void Draw( Matrix view, Matrix projection )
        {
            Matrix[] transforms = new Matrix[Model.Bones.Count];
            Model.CopyAbsoluteBoneTransformsTo( transforms );

            Matrix translateMatrix = Matrix.Identity
                * Matrix.CreateFromAxisAngle( _orientation.Right, MathHelper.ToRadians( pitch ) )
                * Matrix.CreateFromAxisAngle( _orientation.Down, MathHelper.ToRadians( roll ) );

            _orientation *= translateMatrix;

            foreach ( ModelMesh mesh in Model.Meshes )
            {
                foreach ( BasicEffect effect in mesh.Effects )
                {
                    effect.World = _orientation * transforms[mesh.ParentBone.Index];
                    effect.View = view;
                    effect.Projection = projection;
                    effect.EnableDefaultLighting();
                }
                mesh.Draw();
            }
        }

        public void Update( GamePadState gpState )
        {
            roll = 5 * gpState.ThumbSticks.Left.X;
            pitch = 5 * gpState.ThumbSticks.Left.Y;
        }

```

# Answer
> 6 votes
You are combining matrices for the effect.World backwards.

It should be:

```
effect.World = transforms[mesh.ParentBone.Index] * _orientation;

```

Most likely, there is some model root or local ModelMesh scaling coming from the 'transforms' (via the 3d modeling app usually). When you place the orientation first, it takes the system out of world space alignment. But then the 'transforms\[\]' is trying to scale in the direction of world space basis vectors so it scales it all out of local space alignment. Remember SRT, and if there is any scaling in the 'transforms\[\]', it must be dealt with first..

Also, it is very important that when you use CreateFromAxisAngle(), that the axis argument be exactly unit length (as been said by other posts). Can't stress that enough, if you do this, your \_orientation matrix will last hours without shearing or distorting while being updated 60 times per second.

Try:

```
Matrix.CreateFromAxisAngle( Vector3.Normalize(_orientation.Right), MathHelper.ToRadians( pitch ) )

```

# Answer
> 4 votes
The \_orientation matrix is likely accumulating error from the rotation that is applied each frame, and is losing its orthogonal property. Try normalizing it after applying the rotation:

```
_orientation.Forward = _orientation.Forward.Normalize;
_orientation.Left= _orientation.Left.Normalize;
_orientation.Up= _orientation.Up.Normalize;

```

# Answer
> 1 votes
You need to recompute the orientation each frame; currently you are just accumulating it;

> \_orientation \*= translateMatrix;

needs to be more like

> \_orientation = Matrix.Identity;
>
> \_orientation \*= translateMatrix;

Or you could use the Matrix.CreateWorld static method

---
Tags: xna, xna-4.0, matrix, rotation, gimbal-lock
---