# Question
Title: How do I create an efficient long, pannable, sprite-animated scene in a Windows Store game?
I am creating my first Windows Store application in XAML, and I cannot seem to find a proper example for the requirements I have.

The basic idea of the app is to have a large scrollable canvas which would lazily start animating visible parts of the view as soon as user stops panning over a certain content (with some audio played also):

My original idea was to use a `StackPanel` to add a bunch of custom controls, each of which would then animate itself once visible (with a short delay), but I have a couple of concerns:

1. If the entire canvas is ~50 screen widths wide, is it feasible to load all content at the beginning, or do I need to plan doing some lazy loading during scrolling? For example, when I select a certain region in the Bing Travel app, it seems to lazily load tiles as I scroll it towards the end.
2. Since content is stretched 100% vertically, and these animations are vectorized to be resolution independent, I am not sure if XAML (`CompositionTarget`) will be able to handle this, or I have to go for DirectX (MonoGame or C++) to get rid of flicker.
3. Even better, is there an example for Windows 8 which uses a 100% vertically sized `GridView` with custom animated controls inside?

# Answer
> 1 votes
If you want to render game content in Windows Store App the best way to do this is SwapChainBackgroundPanel (Windows 8), SwapChainPanel (Windows 8.1)

I think this is what you are looking for.

---
Tags: directx, spritesheet, windows-8
---


# Question
Title: fragment shader directional light positioning with camera
Im trying to set up directional lighting in the fragment shader. So the direction of my light moves with the camera position.

```
      #version 150 core

      uniform sampler2D diffuseTex;
      uniform vec4 lightColour;
      uniform vec3 lightDirection;

      vec3 LNorm     = normalize(lightDirection);
  vec3 normal    = normalize(IN.normal);
      vec3 calColour = lightColour[i].rgb  * intensity;
  gl_FragColor   = vec4(diffuse.rbg * calColour, diffuse.a);

```

It lights the entire scene.

# Answer
> 1 votes
If you want the light direction to move with your camera position then by definition it's not a directional light, because directional lights are meant to have position at infinity and have uniform direction across the whole scene.

Regardless of definitions, in order to make your light direction change with the camera position you need to calculate the light direction in your vertex shader and pass to your fragment shader:

```
//In your vertex shader
uniform vec3 lightPosition; // you need to pass it to VS, define it to be very far away
out vec3 lightDir;

lightDir = normalize(lightPosition - cameraPos);

```

This way you get different light direction based on the camera position.

---
Tags: opengl, glsl, lighting, terrain
---


# Question
Title: How can I find a position between 4 vertices in a fragment shader?
I'm creating a shader with SharpDX (DirectX11 in C#) that takes a segment (2 points) from the output of a Vertex Shader and then passes them to a Geometry Shader, which converts this line into a rectangle (4 points) and assigns the four corners a texture coordinate.

After that I want a Fragment Shader (which recieves the interpolated position and the interpolated texture coordinates) that checks the depth at the "spine of the rectangle" (that is, in the line that passes through the middle of the rectangle.

The problem is I don't know how to extract the position of the corresponding fragment at the spine of the rectangle. This happens because I have the texture coordinates interpolated, but I don't know how to use them to get the fragment I want, because the coordinate system of a) the texture and b) the position of my fragment in screen space are not the same.

# Answer
> 1 votes
One way to do this is to create another output from the geometry shader, called `spinePos` for example. In the geometry shader, calculate the spine position at each end of the rectangle, and assign it to `spinePos` for the two vertices at that end.

The rasterizer will interpolate this value across pixels as it normally does, but since the two vertices at each end have the same `spinePos` value, there will be no change in the value from interpolating across the thickness of the rectangle. It will only change as you move along the length of the rectangle.

---
Tags: shaders, directx11, geometry
---


# Question
Title: What's the difference between displacement mapping and height mapping?
What's the difference between displacement mapping and height mapping and what is the connection to adaptive tessellation?

# Answer
Displacement mapping and height mapping are two names for "almost" the same technique, they aim to do the same effect but **are used in different contexts.**

To explain more:

**Displacement Mapping:** Is a technique that aims to render bumps as true geometry, in a very fine mesh. Unlike bump mapping, parallax, and relief mapping which tries to "fake" bumps using normal maps, Displacement mapping actually displaces the surface, creating triangles between the texels. .

**Height Mapping:** is the same thing, but it's usually used in the context where a displacement map (also called height map) is applied on a terrain where the value are only used to modify the vertex height.

**It can be implemented on the CPU or the GPU.**

**One common CPU approach** is to read height or displacement values from a height/displacement map(texture) where each texel directly maps to one vertex. Where each texel encodes a height/displacement value. This is then applied directly to the geometry by displacing each vertex using the looked up value in a unique direction.

Choosing the direction can be in the Up direction (usually in case of terrains), which results in modifying the vertex Y value, or could be in the direction of the face normal usually used on objects other than terrains.

**A GPU alternative** is to use the vertex texture fetch feature (introduced in Shader Model 3.0) to have a the terrain mesh modified by accessing a displacement/height map The height retrieved from the texture is used by the vertex shading program to modify the vertex's location.

Other uses for Using a texture allows for *faster manipulation of data for wave simulations and other animations to apply to the mesh.*

Regarding adaptive tessellation:

One draw back of displacement mapping is that for large terrains you need a lot of polygons and vertices to model a detailed terrain which makes displacement maping somehow inefficient for large terrains.

This is where adaptive tessellation and level of detail techniques come to play to make displacement mapping more feasible, especially with the advancement of the GPUs and introducing geometry shaders, performing tessellation on the fly with this advancement has become the dominant technique. It is simple to program and on newer GPUs and has few drawbacks.

Other techniques like relief and bump mapping offer additional realism at a generally reasonable cost, but the fact that the base surface is unperturbed makes collision detection, and therefore object interaction, more challenging.

As a conclusion Displacement mapping and adaptive tessellation brings superior detail and quality with less draw backs at a feasible performance cost.
> 12 votes

# Answer
Displacement mapping can mean (but doesn't always mean) a *vector* displacement at each point on the surface. Height mapping implies only a *scalar* displacement value, i.e. each point gets pushed along its normal. The term "displacement mapping" can also be used for scalar displacements, though, so when vector displacements are discussed, people often explicitly say "vector displacement mapping".

Tessellation can be used to apply a displacement map, by subdividing a surface into small polygons and applying a displacement (looked up from the map) to each vertex of the subdivided surface. The level of subdivision you need depends in part upon how noisy/detailed the displacement map is, so adaptive tessellation can be used to subdivide more finely in the areas that have more detail, but less in the areas that are flatter, improving performance.
> 14 votes

# Answer
Basically, they are the same thing.

Displacement mapping is a technique for adding surface detail, like bump mapping. Unlike bump mapping, however, displacement mapping is about actually deforming the geometry based on some input *height map* (essentially a grid of elevation values).

"Displacement mapping" is basically another, more technically accurate, term for what is colloquially known as "height mapping" (strictly speaking, "height mapping" probably should refer to the process of generating the grid of elevation data from some source material, such as a 3D scanner, that will be used in a displacement mapping implementation -- but in practice most people just use the terms interchangeably, if they even say "displacement mapping" at all).

The technique is not directly tied to adaptive tessellation, which is itself about controlling the breakdown of a mathematical description of a mesh (such as a sphere) into the concrete collection of triangles that will be used to render that mesh. The "adaptive" bit means that the tessellation detail will change based on some input criteria, such as view distance.

In the sphere case, for example, you can tessellate that sphere very crudely (effectively as a cube) when that sphere is very far away, but use more detail when the sphere is close.

Often you will see techniques like displacement mapping discussed in conjunction with tessellation because the tessellation will affect how you want to map the elevation map to the geometry to perform the displacement (or which resolution of the elevation map you want to select, et cetera).
> 3 votes

# Answer
They are the same concept.

EDIT: Displacement can be composed of heights in more than one dimension!

Don't start any semantic wars over this, but realistically, height mapping usually refers to large scale / tessellation based techniques, where displacement mapping usually refers to small scale / raytracing techniques.
> 2 votes

---
Tags: textures, heightmap, tessellation, displacement-mapping
---


title: Rope Colliding with a Rectangle

text:
# Question
Title: Rope Colliding with a Rectangle
I have my rope, and I have my rectangles.

The rope is similar to the implementation found here: http://nehe.gamedev.net/tutorial/rope\_physics/17006/

Now, I want to make the rope properly collide with the rectangle such that the rope will not pass through a rectangle, and wrap around the rectangle and all that good stuff.

Currently, I have it set so no rope node can pass through a rect (successfully), however, this means a rope *segment* can still pass through a block. Ex:

So the question is, what can I do to fix this?

What I have tried:

I create a rectangle between two nodes of a rope, calculate rotation between the nodes, and get myself a transformed rectangle.

I can successfully detect a collision between rope segments and a (non-transformed) rectangle.

Create a new node or pivot point around the corner of the block, and rearrange nodes to point to the corner node. Trouble is determining what corner the rope segment is passing through. And then the current rope setup goes wonky (based on verlet integration, so a sudden change in position causes the rope to wiggle like a seismograph during a magnitude 8 earth quake.) Among other issues that *might* be solvable, but its turning into a case by case thing, which doesn't seem right.

I think the best answer here would just be a link to a tutorial (I simply can't find any, most lead to box2D or farseer, but I want to at least learn how it works before I hide behind an engine).

# Answer
You should use a method of collision response to ensure that your rope segments are always not overlaping your blocks. This tutorial is a good starting point: http://www.metanetsoftware.com/technique/tutorialA.html.

It mentions 3 types of collision response techniques: projection, penalty-force and impulse-based. Projection is simpler, but doesn't take into consideration important physical info (such as velocities and accelerations), which can make the rope behave non-realistically.

Penalty-force is a mid-way on simplicity and accuracy. These methods try to avoid penetration by generating a restoring force. There is a good reference in the tutorial, which was used on Hitman: Using Verlet Integration and Constraints in a Six Degree of Freedom Rigid Body Physics Simulation (unfortunately I could not found the doc free on the web...). If you want to do this continuously (so you cannot miss collisions), check: http://gamma.cs.unc.edu/CPF/paper.pdf.

Finally, as the tutorial suggests, you can read http://graphics.stanford.edu/courses/cs468-03-winter/Papers/ibsrb.pdf for an impulse-based method, which is the more accurate.

In your case I whould try penalty-based or impulse-based methods, since you already have forces in your mass-spring system and can also take them into consideration.
> 2 votes

---
Tags: 2d, physics, xna-4.0, rope-physics
---


# Question
Title: Pyglet: How to use second screen's vsync
does anybody know if it's possible to use the vsync of the second monitor instead of the first one with pyglet?

I have 2 monitors, one running at 60Hz and the other at 120Hz. I want to be able to set my application on whatever monitors I have, and have the application use the monitor's rate to swap the buffers.

This needs to be cross platform.

I found this information... pyglet.window

But I was wondering if anybody knows a way...

Thanks for your help.

# Answer
`vsync = True` just means to wait with swapping buffers until the next vertical retrace, which is the point in time where a frame is completely drawn on the monitor, instead of somewhere halfway through, which can cause visible tearing during animations.

Enabling vsync (on whatever platform) will simply tell OpenGL to wait for the *next* retrace. It will do this with respect to the refresh rate of the screen, which means on a 120 Hz monitor it has 120 opportunities per second to swap buffers with vsync enabled (instead of 60 at 60 Hz).

So you don't need to do anything other than enable vsync and it'll just do the right thing depending on which screen you're rendering to.

See also the platform vendor documentation, e.g. `NSOpenGLCPSwapInterval` for OS X.

You can query the refresh rate of each screen using `get_mode()`:

```
import pyglet
platform = pyglet.window.get_platform()
display = platform.get_default_display()
for screen in display.get_screens():
    print(screen.get_mode().rate)

```
> 1 votes

---
Tags: opengl, pyglet
---


# Question
Title: How to draw image in memory manually in pyglet?
In pyglet, I want to create an image buffer in memory, then set the bytes manually, then draw it. I tried making a 3x3 red square like this in my draw() function:

```
imageData = pyglet.image.ImageData(3, 3, 'RGB', [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 ])
imageData.blit(10, 10)

```

...but at runtime, Python complains:

```
ctypes.ArgumentError: argument 9: <type 'exceptions.TypeError'>: wrong type

```

Is this the right approach? Am I missing a step? How can I fix this?

# Answer
> 3 votes
Yes, you can do this, but as the error tells you, you must use `ctypes` instead of Python types for it.

RGB values are unsigned byte triplets, which means `c_ubyte` in ctypes, also available in `pyglet.gl` as `GL_ubyte`. So you can do this:

```
pixels = [
    255, 0, 0,      0, 255, 0,      0, 0, 255,     # RGB values range from
    255, 0, 0,      255, 0, 0,      255, 0, 0,     # 0 to 255 for each color
    255, 0, 0,      255, 0, 0,      255, 0, 0,     # component.
]
rawData = (GLubyte * len(pixels))(*pixels)
imageData = pyglet.image.ImageData(3, 3, 'RGB', rawData)

```

The above is the recommended `ctypes` syntax, which generates an array of `GLubyte` with the right size and then populates it with your pixel data.

---
Tags: pyglet
---


# Question
Title: How can I deal with actor translations and other "noise" in third-party motion capture data?
I'm working on a game, and I've run into a problem with motion capture data. My team is using 3DS Max 2011 and trying to put free motion capture files on our models.

The problem we're having is it has become extremely hard to find motion capture data that stays in place. We've found some great motion captures of things like walking and jumping but the actors themselves move within the data, so when we attach these animations to our models and bring them into XNA, the models walk forward even when they should technically be standing still (and then there's also the problem of them resetting at the end of the animation).

How can we clean up, at runtime or asset-processing time, the animation in these motion capture files?

# Answer
> -1 votes
If your models wind up walking forward after you apply the mocap data, then write some code to subtract the position of the model's abdomen for each animation frame. Then the model will stay still, won't it?

---
Tags: xna, motion-capture
---


title: scaling point sprites with distance

text:
# Question
Title: scaling point sprites with distance
How can you scale a point sprite by its distance from the camera?

GLSL fragment shader: `gl_PointSize = size / gl_Position.w;` seems along the right tracks; for any given scene all sprites seem nicely scaled by distance. Is this correct?

How do you compute the proper scaling for my vertex attribute `size`? I want each sprite to be scaled by the modelview matrix.

I had played with arbitrary values and it seems that `size` is the radius in pixels at the camera, and is not in modelview scale.

I've also tried:

```
gl_Position = pMatrix * mvMatrix * vec4(vertex,1.0);
vec4 v2 = pMatrix * mvMatrix * vec4(vertex.x,vertex.y+0.5*size,vertex.z,1.0);
gl_PointSize = length(gl_Position.xyz-v2.xyz) * gl_Position.w;

```

But this makes the sprites be bigger in the distance, rather than smaller:

# Answer
To answer my own question, here's what I got working:

The scaling in the GLSL vertex shader is:

```
gl_PointSize = (heightOfNearPlane * pointSize) / gl_Position.w;

```

Where you compute your `heightOfNearPlane` using the viewport height and the field-of-view angle you constructed the perspective matrix with:

```
float fovy = 60; // degrees
int viewport[4];
glGetIntegerv(GL_VIEWPORT,viewport);
float heightOfNearPlane = (float)abs(viewport[3]-viewport[1]) /
    (2*tan(0.5*fovy*PI/180.0));

```

Which you pass in as a uniform.

Thx to the coders on irc.freenode.net ##opengl that helped me sort this out!
> 8 votes

# Answer
I found the solution to scale PointSprites:

```
const float SIZE_MULTIPLIER = 300.0;
 attribute float inSize;
uniform vec2 g_Resolution;
…

vec4 modelSpacePos = vec4(inPosition, 1.0);
vec4 position = g_WorldViewProjectionMatrix * modelSpacePos;
#ifdef POINT_SPRITE
  //  vec4 worldPos = modelSpacePos  * modelSpacePos;
    float spriteDist;

    if (position.w == 0.0) {
      spriteDist = 0.00001;
    } else {
      spriteDist = position.w;
    }

    gl_PointSize = (((inSize * SIZE_MULTIPLIER * (g_Resolution.x/g_Resolution.y)) / spriteDist) * (g_Resolution.x/g_Resolution.y));
#endif

```

Here is my talk on jMonkey engine: http://hub.jmonkeyengine.org/forum/topic/pointsprote-size-limitation/#post-250817
> 1 votes

---
Tags: sprites, glsl, webgl
---


# Question
Title: DirectX11 Swap Chain RGBA vs BGRA Format
I was wondering if anyone could elaborate any further on something that's been bugging me.

In DirectX9 the main supported back buffer formats were D3DFMT\_X8R8B8G8 and D3DFMT\_A8R8G8B8 (Both being BGRA in layout).

http://msdn.microsoft.com/en-us/library/windows/desktop/bb174314(v=vs.85).aspx

With the initial version of DirectX10 their was no support for BGRA and all the textbooks and online tutorials recommend DXGI\_FORMAT\_R8G8B8A8\_UNORM (being RGBA in layout).

Now with DirectX11 BGRA is supported again and it seems as if microsoft recommends using a BGRA format as the back buffer format.

http://msdn.microsoft.com/en-us/library/windows/apps/hh465096.aspx

Are there any suggestions or are there performance implications of using one or the other?

(I assume not as obviously by specifying the format of the underlying resource the runtime will handle what bits your passing through and than infer how to utilise them based on the format.)

# Answer
> 4 votes
Now when using the discard presentation in a Win32 app it passes the render target to DWM which then blits the target to the screen and when in full screen mode (provided you have resized your back buffer and refresh rate correctly) it will disable DWM and perform flips to render the scene.

Now with metro apps there's no such thing as full screen exclusive (as they are essentially borderless window). So they would blit all the time (the discard presentation model is actually not allowed for metro apps).

So you have to set the presentation model to flip in Win32 apps and metro apps(with this being your only option for metro :\]). It will than pass your render target to DWM (I assume maybe it allows you access to its underlying target to draw into and uses dirty rectangles), and instead of blitting it will straight up flip/merge your target into the screen space it currently resides in and you get flip performance and in full screen it does the flip (assuming you resized buffers and refresh rate).

Now for some reason the windows default back buffer for the OS is BGR and if you use this as your back buffer format the flip is slightly faster as it doesn't have to swizzle or do whatever it does to merge/flip. But you can use either RGBA or BGRA.

Heres the msdn explaining the new presentation model: http://msdn.microsoft.com/en-us/library/windows/desktop/hh706346%28v=vs.85%29.aspx

And heres another msdn confirming the slightly faster flip with bgra: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/f56e4449-f3e1-491e-9f64-e65e989a518a/best-swap-buffer-format-rgba-or-bgra-

---
Tags: directx11, directx9, directx10
---


# Question
Title: Math > Logic for a Logarithmic Score Meter
I'm trying to implement a score meter whereby I specify a maximum value (say 15,000) and I can render values on it in a logarithmic manner ie:

```
+------+---+--+-++        +------+---+--+-++
|==              |        |======          |
+------+---+--+-++        +------+---+--+-++
 200 pts                   1,000 pts

+------+---+--+-++        +------+---+--+-++
|=============   |        |================|
+------+---+--+-++        +------+---+--+-++
 5,000 pts                 15,000 pts +

```

The upper bound needs to be variable, and need to be able to convert a score to a percentage, using the above mockup as an example:

```
score2pct(15000, 200)   = 0.2
score2pct(15000, 1000)  = 0.4
score2pct(15000, 5000)  = 0.8
score2pct(15000, 15000) = 1

```

Does anyone have any pointers for me?

# Answer
> 9 votes
I added a simpler curve to Nathan's answer,

The curve is

```
1 - ( b - x ) / (c*x + b)

```

It doesn't use log, and you can alter the steepness of the curve using the `c` parameter. When `c=0`, the curve becomes linear.

# Answer
> 3 votes
Sure, you can use a logarithmic function for this, for example:

```
scale = log(score / 160.0 + 1.0) / log(maxScore / 160.0 + 1.0)

```

Here, the value 160 is a constant that controls how steep or shallow the curve is. I also added 1.0 to make the curve start from zero (otherwise, the log function goes to negative infinity at zero).

I used the Desmos online graphing calculator app to plot your suggested points and play around with the curve. It's a quite handy tool for this sort of problem.

# Answer
> 1 votes
So your max score is 15000, and you want to do everything on the log scale (I'm assuming base 10, but it doesn't matter as long as you're consistent. Some languages use e as a basis, some use 10).

First you need to find the max score on your log scale that corresponds to 15000 (your chosen max). Then you'd just log transform your score and compute the percentage from those. It's pretty simple.

```
max = 15000
logMax = log(max + 1)
score = 200
logScore = log(score + 1)

percent = log(score)/log(max)

```

I hope that helps.

---
Tags: mathematics, leaderboards
---


title: OpenGL texture on sphere

text:
# Question
Title: OpenGL texture on sphere
I want to create a rolling, textured ball in OpenGL ES 1.0 for Android. With this function I can create a sphere:

```
public Ball(GL10 gl, float radius)
{
    ByteBuffer bb = ByteBuffer.allocateDirect(40000);
    bb.order(ByteOrder.nativeOrder());

    sphereVertex = bb.asFloatBuffer();
    points = build();
}

private int build()
{
    double dTheta = STEP * Math.PI / 180;
    double dPhi = dTheta;

    int points = 0;

    for(double phi = -(Math.PI/2); phi <= Math.PI/2; phi+=dPhi)
    {
        for(double theta = 0.0; theta <= (Math.PI * 2); theta+=dTheta)
        {
            sphereVertex.put((float) (raduis * Math.sin(phi) * Math.cos(theta)));
            sphereVertex.put((float) (raduis * Math.sin(phi) * Math.sin(theta)));
            sphereVertex.put((float) (raduis * Math.cos(phi)));

            points++;
        }
    }

    sphereVertex.position(0);
    return points;
}

public void draw()
{
    texture.bind();

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, sphereVertex);

    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}

```

My problem now is that I want to use this texture for the sphere but then only a black ball is created (of course because the top right corner s black). I use this texture coordinates because I want to use the whole texture:

```
0|0    0|1    1|1    1|0

```

That's what I learned from texturing a triangle. Is that incorrect if I want to use it with a sphere? What do I have to do to use the texture correctly?

# Answer
> 1 votes
Use an icosahedral sphere instead of a polar-coordinates one.

The net for the icosahedron can be laid out nicely, like this:

In a texture editing program, it's easy to UVMap an icosahedron with good/regular texel shapes.

# Answer
> 0 votes
Texture Coordinates -in a very technical terms-, are part of a parametric space that is a mapping between surface positions usually in model space and those texture coordinate. Those surface position are mapped to the parametric space using some sort of function. In other words each texture coordinate is a result of mapping a surface position to a parametric space (2D in case of 2D images).

The point that I wanted to explain is that texture coordinates are used to determine how each texture pixel(also called texel) can be mapped to a surface position.

Now back to your problem, given the above definition you need to assign each vertex its 2D texture coordinates in order to correctly map your 2D image to the 3D sphere. **OpenGL uses per vertex attributes and can't simply use the given four texture coordinates values and imply the rest of the texture coordinates for each vertex.** You either need to generate your texture coordinates using some sort of function or use a modelling package where an artist usually assigns each vertex its texture coordinate.

There are many ways you can generate texture coordinates a sphere but since you are generating a UV sphere, what best fits you is called the naiive appraoch in this page to summerize the approach:

* Directly map latitude-longitude onto sphere
* use single rectangular texture with a proportion of 2x1
* texture coordinates: u goes from 0 to 1 around the equator, v goes from 0 to 1 from pole to pole
* pro: simple, most data sources are already in this format
* con: wastes the majority of the texture resolution at the poles, where it is usually least needed

---
Tags: textures, opengl-es, sphere
---


# Question
Title: What are "world space" and "eye space" in game development?
I am reading a book about 3D concepts and OpenGL. The book always talks about *world space*, *eye space*, and so on.

* What exactly is a *world* inside the computer monitor screen?
* What is the world space?
* What is eye space? Is it synonymous to projection?

# Answer
Before understanding what is the world or eye space, **what is a space?**

In an abstract sense, a geometrical space (e.g. Euclidean Space) is a boundless extent where objects tend to exist. The space defines basic properties that objects living in this space should satisfy. For example in euclidean space **distance** is defined as `Sqrt( vector dot product with itself)`.

**Most people tend to mix between the definition of Space and Coordinate system.** A space as euclidean space defines the properties but doesn't define the coordinate system, **I would say "eye space" is better called "eye coordinates".**

In computer graphic we almost exclusively deal with euclidean space. When you define a Vertex of (X,Y,Z) in euclidean space it doesn't mean anything as is to us.

A more tangible definition would be to define it relative to some coordinate system. For example a Vertex(X,Y,Z) is relative to eye coordinates. So if Vertex=(0,2,3) relative to the eye coordinates. it means that this vertex is:

> * 0 in the X direction from the eye X position.
> * 2 in the Y direction from the eye Y position.
> * 3 in the Z direction from the eye Z position.
> * And the vertex distance from the eye is sqrt(0^2 + 2^2 + 3^2)=sqrt(13) unit.

**But what is eye coordinates and how do we define a coordinate system ?**

We define a coordinate system by providing three orthogonal basis(read: unit length and perpendicular) vectors which resembles orientation, and a position(translation).

So if the camera in openGL was defined (note that this is relative to World coordinates):

```
 - Position (0,3,10)
 - Up       (0,1,0)
 - Forward  (0,0,-1)
 - Right    (1,0,0)

```

This means that the viewer is setting at (0,3,10) from the world (0,0,0) and his right is aligned with the world X axis, and his forward is reverse the world Z, and his up is aligned to the World Y.

**But you talked too much about the eye coordinates, what is the World Coordinates?**

World coordinates is just a fixed parent coordinate system. The eye coordinates itself should be relative to something. This is the global coordinate system that everything is defined relative to.

World Coordinate has a fixed **i**=(1,0,0) in the X direction, **j**=(0,1,0) in the Y direction, **k**=(0,0,1) in the Z direction. These are the vectors that define Cartesian coordinate system.

**But that doesn't make sense! What is the coordinates that World coordinates is defined relative to?**

I would say it's relative to itself, in reality that would be the center of the universe (but that's too simplistic).

But in a more practical sense, I would say in Computer Graphics it's convenient to define world space as the center of the universe (game world) so we can imagine how things can relate to each other.
> 27 votes

---
Tags: 3d, terminology
---


# Question
Title: Beginning android games, 2nd edition engine
I recently bought the book from Apress and have worked my way through it, unfortunately, it seems to just be dealing with side scrolling games and not Zelda-like top down games. I was wondering if anyone out there can tell me if it's possible to use their engine to create such a game? It doesn't go into how to build a top down tile map. Using the engine in their book, how can I make a tile map easily that has walls and things like that? Any help would be appreciated. Thanks in advance.

# Answer
> 0 votes
android game development uses Java. Throughout the internet there are a ton of tutorials on isometric map development and top down map development.

use a 2d array, for example private int map\[\]\[\] = {{1,1,1,1},{0,0,0,0},{1,1,0,0},{1,1,1,1}};

to create a 2d data structure, assign the numeric value in the 2d array with an associated image, by looping through the 2d array and saying if the current position in the 2d array is a 1 or a 0 or any number or a character or a string or an object type (that also includes using Rectangle, for the use of defining square boundaries (useful in basic collision detection))

a top down map or an isometric map is a grid with small square images placed into position.

you could also wander about and find this post on dreamincode http://www.dreamincode.net/forums/topic/282580-java-2d-array-tile-map-collision/

---
Tags: android
---


# Question
Title: What is Opengl ES ? What is gl and GLES20 mean?
I am new in opengl. I saw tutorial some have gl at the beginning and some have GLES20 at the beginner and some has GL10.

What are the differences? Is GLES20 mean opengl es2 whereas GL10 mean version 1

# Answer
GLES20 = OpenGL ES 2.0

GL10 = OpenGL 1.0

In addition there is GLSL (OpenGL Shading Language) which also has its own version number (you can see them at wikipedia: http://en.wikipedia.org/wiki/OpenGL\_Shading\_Language)

GLES is meant for embedded systems. Read more at http://www.khronos.org/
> 2 votes

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


title: How to test a 3D rendering engine?

text:
# Question
Title: How to test a 3D rendering engine?
Me and some friends developing simple 3D rendering engine as practice for the university. We used Ogre 3d as prototype and now we are developing it from base

The engine is wrapped up in simple game that asks the user to select shape (circle, triangle, square...), color and dimensions and renders the image to the screen. It also enables to move and rotate the shape on screen using mouse.

We would like to test automate the view rendering. I could not find any test framework for this issue and I would like to know how 3D test is done in non manual matter

# Answer
The problem is that 3d engines aren't required to output an exact image bit-for-bit. Some leeway is tolerated as long as the artifacts caused by it aren't visible to the viewer. A texture being 1% darker than expected is usually not a serious problem... usually. Under some conditions it might be a visual artifact. And that's the problem: It is hard to judge for an automated test which artifacts would be noticed by a human viewer and which are not. Still, automated tests can be used for simple sanity checks when used on very simple geometry.

What you could do is render some simple scenes and then compare the generated image with a reference rendering. That reference rendering could either come from another graphic engine (like your Ogre3d prototype) or be an earlier screenshots from the same engine (regression testing).

When some tests fail after a change to the graphic engine, a human tester should compare the output to the reference image and judge for themself if the new output looks just as good as before (or even better). When that's the case, the test should be changed to compare to the new, improved outputs.

Another thing you could check automatically are performance requirements. One such requirement could be that during a self-running demo (simulating a real sequence from the game) the frame-rate must not drop below 40 Fps on the test system. This is something you can test automatically. What you can't test is that the rendering is satisfying. But you can use such tests to prevent your developers from developing a game which looks superb but doesn't run properly on any affordable system until years after launch (hello Crytek).
> 2 votes

---
Tags: 3d, testing
---


# Question
Title: Why is clip space always referred to as "homogeneous clip space"?
I've noticed in almost everything I've read so far that the term "clip space" is prepended with the word "homogeneous". Now I understand that it roughly means "all the same", but I don't understand why there is the express need to say "homogeneous clip space". When is clip space not homogeneous and why do we need to differentiate? And for that matter, what exactly does it mean that we're calling it "homogeneous clip space"? Homogenous in relation to what? In what way are the vertices "all the same"?

# Answer
Clip space is called *homogeneous* because the values in it use homogeneous coordinates, *i.e.* they are in the form **\[x y z w\]** instead of **\[x y z\]**. In order to get the latter, *perspective division* must still occur:

```
 [x y z w]   →   [x/w y/w z/w]
homogeneous     normalized device
clip space      coordinates (NDC)

```

The reason clipping is performed before perspective division is because divisions are expensive operations. Instead of testing *e.g.* `|x| > 1` in NDC space, we can just test `|x| > |w|` in homogeneous clip space, which gives exactly the same result, and allows to perform clipping before division.
> 29 votes

---
Tags: spaces
---


# Question
Title: When storing voxels in chunks, how do I access them at the world level?
I'm not looking for how to store the voxels, data wise; I'm looking for the theory. Currently, my voxel engine has no global list of tiles. Each chunk has its own list, and its "hard to do things" like collision detection or anything that may use tiles that are outside of its own chunk. I want to start using height maps, but I have a problem. If each chunk has its own list, then it will be pretty difficult to implement the height maps.

Should I store a global list of voxels, independent of the chunks? Then, I can just easily perform collision detection and terrain generation. However, it would probably be harder to do things such as frustum culling.

So how should I store voxels?

# Answer
You don't need a new way of storing them, just just need a new way of accessing them. Storing the data in lists in the chunks is fine. You just need a way to index into them at the world level.

The world should contain a list of chunks currently loaded, and the chunks contain lists of voxels. Each chunk should be the same size (contain the same volume of the world). Now when you want to access a specific voxel in the world, you only need to convert world coordinates into two pieces of data: chunk and chunk coordinates.

Imagine a 2D example. You have a 2D world where each chunk contains 10 x 10 pixels. At the world level you want to access the pixel data for pixel (342,103). First you need to find the chunk that contains the data. You can easily find that because you know each chunk contains 10 x 10 pixels. To get chunk coordinates, just divide by the number of pixels per chunk, `(int)342/10 = 34` and `(int)103/10 = 10`, giving you chunk (34,10).

Now you just need to get the coordinates within the chunk. Those coordinates can easily be found by getting the remainder after the division, i.e. a modulo operation. `342%10 = 2` and `103%10 = 3`, giving you pixel (2,3).

That means world position (342,103) can be found in chunk (34,10) at position (2,3).

Think of it like graph paper, where the larger thicker lines show you where the chunks are and the smaller grids are the data each chunk holds.

The system used to access each can be very similar. It's just that one system holds chunks, while the other holds voxels.
> 9 votes

---
Tags: voxels
---


title: Alpha interpolation in a pixel shader

text:
# Question
Title: Alpha interpolation in a pixel shader
How does the interpolation in a fragment shader work when it comes to the **alpha parameter**?

I'm programming a shader with SharpDX, DirectX11. My idea is to interpolate 2 3d points of a segment, so that I'll have the position interpolated in between in the pixel shader. But I want to know what happens with the alpha parameter when that position is blocked by another polygon.

For instance, if alpha is 1.0 at the left end of my segment and 0.0 at the other one. What is the value of alpha in the middle, 0.5? Or does it depend on the visibility at that point (meaning it could be, for instance, 1.0 OR 0.0 depending on if that part of the segment is hidden by a poolygon?

# Answer
> 2 votes
Alpha has nothing to do with the depth test. All vertex shader outputs just get interpolated across the pixels, and don't change based on per-pixel visibility. In your example, if an alpha parameter is output from the vertex shader as 0 at one end and 1 at the other end of the rectangle, it will be 0.5 in the center.

# Answer
> 0 votes
Think you're confusing some concepts there.

It also depends on which inputs you feed to your shader, because the most simple shader doesn't need any inputs at all.

The following would be a minimalistic fragment shader in GLSL, but I think it would work in HLSL as well (or with minimalistic changes):

```
float4 main() {
    float4 color;
    color.rgba = 1;
    return color;
}

```

This would simply set any and all pixels to plain white. You could of course set an alpha value based on the position, but that's a bit more tricky.

Your second part of the question isn't 100% clear to me: If a part of your polygon is hidden behind something else (i.e. the depth test fails), then the graphics card won't even execute your shader code for that pixel (optimization). This is also the reason why the render order is important when working with alpha transparency. You could of course disable depth testing and then adjust the pixel color based on the depth at that position (either completely transparent/hidden or based on depth etc.).

There's no general concept or solution to your question. It really depends on what you're aiming for.

---
Tags: directx, shaders, directx11, fragment-shader, sharpdx
---


# Question
Title: Fragment shader seems to floor() imprecisely
I'm trying to interpolate coordinates in my fragment shader. Unfortunately if close to the upper edge the interpolated value of `fVertexInteger` seems to be rounded up instead of beeing floored. This happens above approximately `fVertexInteger >= x.97`.

Example:

* `floor(64.7)` returns `64.0` --\> correct
* `floor(64.98)` returns `65.0` --\> incorrect

The same happens on ceiling close above `x.0`, where `ceil(65.02)` returns `65.0` instead of `66.0`.

**Q:** Any ideas how to solve this?

Note:

* GL ES 2.0 with GLSL 1.0
* highp floats are not supported in fragment shaders on my hardware
* flat varying hasn't been a solution, because I'm drawing TRIANGLE\_STRIP and can't redeclare the provoking vertex (only OpenGL 3.2+)

Fragment Shader:

```
varying float fVertexInteger;
varying float fVertexFraction;
void main() {

    // Fix vertex integer
    fixedVertexInteger = floor(fVertexInteger);

    // Fragment color
    gl_FragColor = vec4(
        fixedVertexInteger / 65025.0,
        fract(fixedVertexInteger / 255.0),
        fVertexFraction,
        1.0 );

}

```

# Answer
You said highp floats are not supported on your hardware, so I assume you're using mediump. The OpenGL ES shading language spec says that mediump has a minimum relative precision of 2^(-10), or 1/1024. So if `a` and `b` are two adjacent mediump values, the ratio `(b-a)/a` can be as large as 1/1024.

Unfortunately, if you look at 65.0 and 64.98, the ratio (65.0 - 64.98) / 64.98 is considerably less than 1/1024. Actually it's about three times smaller than that. So it seems likely that your hardware's mediump floats are simply not precise enough to represent the difference between 64.98, 65.0, and 65.02.
> 7 votes

---
Tags: shaders, glsl, opengl-es2
---


title: How to resolve collisions smoothly?

text:
# Question
Title: How to resolve collisions smoothly?
Currently my collision method is glitchy, because it gets the last "good" position it was when it wasn't colliding and teleports it to that location when it collides with something. This method works, but it causes the sprite to constantly micro-jump while it's touching things.

Any recommendations for a better collision system?

# Answer
> 2 votes
Resolve axis independently of each other, and rather than place your character back at its original location, place them at an appropriate location based on where the collision took place. Most ray casting implementations will return you a "t" value if not an actual vector. Identify this location, and then place your character at something such as: : (dirVector * t) - dirVector * charRadius;

dirVector = normalized direction from current pos to target pos, t = value returned by raycast indicating the intersection point of the ray (scalar), charRadius = radius of character capsule/box/whatever

This is just a rough idea, that will place your character at a location far enough from the point of collision so that you arent clipping into the wall.

General idea, you will have to adapt for yourself of course.

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


# Question
Title: Augmented reality on Mobile platform - iOS
Is there a way that we can control the iOS device camera to an extent what colors it sees, what shapes it sees ? etc

I'm speaking about the ability to read information before the image is captured.

Consider my question as: Possibility of making an augmented reality game on iOS phones.

I dont find relevant help for my query in internet/iOS developer site. Hence posting here.

# Answer
> 4 votes
If you mean you want your app to detect predetermined patterns using the camera, you will want to capture the result from the camera every few frames, and parse the image for near identical patterns.

If you want to save yourself the trouble of doing all the pattern matching you can use an AR library like the free and open source **open frameworks** or **vuforia**. It's very effective with the pattern matching, even at bizarre angles and on cylinders (bottles, cans...).

Here is an example of the tracking capacity of Vuforia. http://www.youtube.com/watch?v=OIBHNYxStmA

Vuforia is the only lib I have used. But there are others:

---

**Edit**:

---
Tags: android, ios, camera
---


# Question
Title: Relationship between Desktop and Android on LibGDX
So I finished tweaking a tutorial called Rain Catcher and I ran the desktop application. It works fine. I then proceeded to run the application using the android emulator the game then crashes.

I set up the project using libGDX's project set-up.

Why won't it run properly on the android emulator even though it runs fine on the desktop application?

I don't know if you can see it but if you zoom you would be able to see it easier.

# Answer
> 5 votes
If the Android project compiles correctly but is missing classes when run, it may be because ADK r17 (the current version atm) doesn't include the external game project as part of the build. There's an extra step you have to do that's still lacking from most of the existing documentation for project setup. It's described here. Copying from that site, the steps are:

> 1. Click on your Android Project
> 2. Select Properties
> 3. Select Java Build Path
> 4. Select Order and Export
> 5. Check all your references, e.g. the gdx.jar, the gdx-backend-android.jar, your main code project etc.

The pictures on the site are helpful, so go check that out.

# Answer
> 2 votes
It's unable to resolve the superclass for `Lcom/badlogic/drop/Drop` and unable to resolve `Lcom/badlogic/gdx/backends/android/AndroidApplication`

So I'd say there's an issue with the badlogic library. You may want to read the text files it wrote out to see their stack traces. Perhaps that'll give you more of a clue.

Did you look at the "Running the game on Android" section of the documentation you linked? Are you sure the `AndroidApplication` backend is present?

You really need to start investigating these types of errors on your own BluFire.

# Answer
> 2 votes
Generally, this problem (missing GDX libraries at run-time on Android) is because the "libs" directory isn't setup exactly as specified in the project doc. The directory must be called "libs" and it must contain the GDX backend and both sets of ARM libraries.

# Answer
> 0 votes
The behavior is odd because since you don't get a compile error on Drop.java, it appears that you have your project set up properly. For the Dalvik DexClassLoader to fail, it appears that something is getting messed up in the build process. If you really want to investigate, take the .apk and run it through dex2jar and open it with a Java Decomplier and see if there are classes missing.

If the classes are there, it would suggest to me that you have problems with your development environment. Either Java/JVM, your Android SDK or the build of libgdx you have is corrupt. Since it works in the Java Project like you said, one would think that maybe trying to reinstall the Android SDK may resolve your issues.

# Answer
> -2 votes
Had the same problem, realized i did not have the "Use host GPU" box checked on the emulator.

---
Tags: android, libgdx
---


# Question
Title: Fitting tilemap to any screen resolution
My game is a 2D Single-Screen (i.e. non-scrolling) platformer for Android, but the question here doesn't require a code-specific answer.

Basically it's easier for me to show the problem using a graphic, which I've attached below.

My game screen consists of a grid of 25 x 12 tiles. I am already scaling my viewport so that my ratio stays consistent (by introducing letterboxing / pillarboxing when required) - this works correctly. I am also scaling my tile sizes by the current viewport dimensions so they appear the same size relative to the current display.

However, clearly, dividing my screen width by 25 to get the tile size will produce a slightly different gap at the right hand side. (if the starting position is 0 (left edge)).

I get this problem also vertically but this isn't so much of an issue as I can just keep the gap - see the first 2 graphics below.

So, horizontally, what would be the best method to 'cover' this gap up.

I know I can make it more 'symmetrical' by moving all the tiles to the right by 1/2 of the gap width. But then I would just have smaller gaps on both sides.

Another solution would be to simply draw an extra tile to the right (make my grid 26x12) but this would mean that I would be drawing extra tiles that weren't needed on some screen resolutions (where screen width divided by 25 didn't produce a noticeable remainder / gap). So I'm all out of ideas and really have no clue how to proceed. How are these issues dealt with?

I know questions regarding the scaling of graphics are in abundance here on GDS but they do not answer this question. This question is specific to fitting a tile-grid onto multiple screens in an aesthetically pleasing way.

Help would be appreciated.

# Answer
> 4 votes
As congusbongus wrote, you have listed most of the options.

The usual solutions we use in games (sorry I'll be repeating you a lot):

* You can keep the gap. If you'll do that, you definitely should center the play area so the gap is the same on all sides. Otherwise it looks strange visually. Then you can..
+ Fill the gap with some solid tiles, or even some special tiles (visually). To indicate to player thats where they level area ends.
    + Put some nice 'panel' (decoration) there to fill the space visually.
* We usually use solution from your second figure from top. Making a bigger panel, that can be cropped (nothing player needs to see on the crop-able part), or displayed whole, filling the gap space.
* Most game devs just stretch the content (event non-proportionally) to fill whole screen on any device without much headache. I guess the tiles will already be stretched from its original resolution, so this shouldn't do much damage.

---
Tags: tiles, tilemap, screen, resolution, scale
---


# Question
Title: Can an RPG Leveling System be simulated on MS Excel?
I'm interested in seeing quickly if my leveling system still makes sense at level 60. Is there a quick way to do this on Excel?

# Answer
Yes, it can. This is a common way to tweak and evaluate these formulas. Enter the formula in one cell, with the inputs to the formula referencing other cells. Fill in the data to the "input" cells to see what kind of output you get.
> 1 votes

---
Tags: rpg, progression
---


# Question
Title: How to make "they need to be fed" movement style
This is the game for people who don't already know it: youtube video

I am looking for theory about making an object move around another object and stay stuck to it. How would I implement something similar?

# Answer
> 4 votes
I saw the game first time from your link, so I might be making wrong assumptions about it's mechanics. But I still think that it could be done this way.

The game seems to be all about gravity. Every block the player can walk on has it's own gravity well, and player can jump out of it if there's another gravity block nearby enough. It's simple planet-like gravitation explained here: 2D Planet Gravity

Objects sticking to the block is done with collision detection.

---
Tags: physics, movement
---


# Question
Title: Why, after calling SetVideoMode as in the following, does nothing appear on my screen?
I am trying to create an application that will need to use double buffering (for purpose of vsync). I am using SDL.NET. From what I understood, in order to have double buffering, I have to SetVideoMode with the `opengl` paremeter set to `true`.

Here's the code I'm using:

```
        Video.Initialize();

        Video.GLSetAttribute(OpenGLAttr.DoubleBuffer, 1);
        Video.GLSetAttribute(OpenGLAttr.SwapControl, 1);
        Video.GLSetAttribute(OpenGLAttr.RedSize, 8);
        Video.GLSetAttribute(OpenGLAttr.GreenSize, 8);
        Video.GLSetAttribute(OpenGLAttr.BlueSize, 8);
        Video.GLSetAttribute(OpenGLAttr.DepthSize, 16);

        Video.SetVideoMode(VideoInfo.ScreenWidth, VideoInfo.ScreenHeight, false, true, true, true);

```

If 4th parameter (`bool opengl`) is `false`, it works: a new fullscreen window is created and displayed (but I assume the `OpenGLAttr`'s set above are meaningless in this case).

If 4th parameter is `true`, nothing happens. A new window gets created (at least, it appears in the list of open windows) but I cannot alt-tab into it and nothing appears on the screen.

What am I doing wrong?

# Answer
> 1 votes
Okay, I see that the problem was, I didn't output anything on the screen - doing `Video.GLSwapBuffers()` made the black screen appear.

---
Tags: opengl, c#, sdl, vsync
---


title: Spliting up VAOs?

text:
# Question
Title: Spliting up VAOs?
At the moment I have one vertex/fragment shader, but I am looking to add another shader program to deal with shadow maps. In my "final" shader I have VAO which define positions, normals, texcoords, tangents, bitangents, etc and in my shadow map shader I only need the positions...

Final pass shader:

```
layout(location = 0) in vec3 vert_position;                                             \n \
layout(location = 1) in vec3 vert_normal;                                               \n \
layout(location = 2) in vec2 vert_texcoord;                                             \n \
layout(location = 3) in vec3 vert_tangent;                                              \n \
layout(location = 4) in vec3 vert_bitangent;                                            \n \

```

Shadow map shader:

```
layout(location = 0) in vec3 vert_position;                                             \n \

```

Code for creating VAOs

```
OpenGLRenderer::VAO SetupVAO(OpenGLMeshPtr mesh)
{
    OpenGLRenderer::VAO vao;

    GLCALL(glGenVertexArrays(1, &vao));

    GLCALL(glBindVertexArray(vao));
    GLCALL(glBindBuffer(GL_ARRAY_BUFFER, mesh->mVBO));
    GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->mIndexBuffer));

    GLCALL(glEnableVertexAttribArray(0));
    GLCALL(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0));
    GLCALL(glEnableVertexAttribArray(1));
    GLCALL(glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(mesh->mVertexDataSize)));
    GLCALL(glEnableVertexAttribArray(2));
    GLCALL(glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(mesh->mVertexDataSize + mesh->mNormalDataSize)));
    GLCALL(glEnableVertexAttribArray(3));
    GLCALL(glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(mesh->mVertexDataSize + mesh->mNormalDataSize + mesh->mTexCoordsSize)));
    GLCALL(glEnableVertexAttribArray(4));
    GLCALL(glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(mesh->mVertexDataSize + mesh->mNormalDataSize + mesh->mTexCoordsSize + mesh->mTangentsSize)));

    GLCALL(glBindBuffer(GL_ARRAY_BUFFER, 0));
    GLCALL(glBindVertexArray(0));

    return vao;
}

```

Thus my question is - should I create two VAOs per mesh, one for the shadow map and one for the final pass, or should I use the same VAO in both shaders, leaving all but position parameters unused but avoid creating/binding a new VAO? Does it have any implications doing so?

Thanks

EDIT: In short, is it detrimental to performance to supply the 5 attribute indices and their data to my shadowmap shader but only use the positions?

# Answer
With regard to the VAOs, it's quite possible that the driver will internally disable attributes that aren't used by the vertex shader, so it may or may not make any difference. The only way to tell is to measure it using timer queries.

Another thing you might consider is splitting the VBOs as well, to put positions all in one VBO (packed tightly together) and all the other attributes in a second VBO (interleaved). This improves cache locality when fetching the positions in the shadow pass, which can improve performance since shadow rendering is often vertex-bound. Again, YMMV and you'll have to measure to see if you got any perf gain by doing this.
> 1 votes

---
Tags: opengl, c++
---


# Question
Title: Difference between texture.Load() and texture.Sample() methods in DirectX?
The question is simply that: What is the difference between texture.Load() and texture.Sample() in DirectX?

I've used a Texture2D to store the depth in a pass of a DirectX Shader (with SharpDX), and now that I want to extract the depth from the texture I'm not sure which of the two methods I should use

# Answer
> 14 votes
The `Sample` method accepts a UV coordinate (where the texture covers the \[0, 1\] range), does mipmap selection based on the UV derivatives, applies addressing modes (clamp, wrap, border) and does filtering (bilinear, trilinear, aniso).

The `Load` method accepts a texel coordinate in the \[0, textureWidth - 1\] x \[0, textureHeight - 1\] range, and the desired mip level, and simply loads a single texel. Coordinates outside the texture's range just return zero, and no filtering is done.

When trying to map a texture 1:1 to the screen, it's convenient to combine `Load` with the `SV_Position` input semantic in a pixel shader, as they're in the same units. So you can do this:

```
void ps_main(float4 screenPos : SV_Position, ...)
{
    float depth = depthTexture.Load(int3(screenPos.xy, 0));
    ...
}

```

That way you don't need to calculate any UVs. However, this only works if the texture is the same size as the screen; so you can't load half-res or quarter-res textures this way. For those, you'd have to calculate UVs and use `Sample`.

---
Tags: textures, directx, shaders, directx11, sharpdx
---


# Question
Title: Are ambient, diffuse and specular light or material properties?
Are ambient, diffuse and specular properties of light or material?

I am doing ray casting in OpenGL, I've managed to create lit sphere using formula

I = L Ka + L Kd (n . l) + L Ks (r . v)^n

but I entered values manually, now I'd like to create objects for light and sphere, but I don't know which of these properties (Ka-ambient, Kd-diffuse, Ks-specular) should be within the light object and which within the material (sphere) object

# Answer
They are properties of both lights and materials. Typically, materials have a diffuse color and a specular color. Lights just have a light color. When shading a surface, you would multiply the light color componentwise with the material's diffuse and specular colors to arrive at the Kd and Ks values for that equation.

Thus you could have various colors of materials, illuminated by various colors of lights, and have them combine appropriately.

As for ambient, it's not really a separate material property, more like a separate light source that fills the world and applies to every surface. It's a very simple stand-in for global illumination (multi-bounce light). Like other light sources, it has a color. Technically the ambient light should produce both diffuse and specular reflections on the surface, just like any other light. In practice, with this kind of very simple lighting model, you can often just use the material diffuse color and multiply it by the global ambient light color to get Ka in the lighting equation.
> 3 votes

---
Tags: opengl, graphics, lighting, raycasting, glut
---


# Question
Title: How does the fragment shader get data from the vertex shader?
How can any interactions between these two shaders work? I mean the vertex shader sends a vertex's color to the fragment shader, but that's only one fragment, what about all the other ones between the vertices?

Does the fragment shader get called a lot more than the vertex shader?

I mean the fragment-to-vertex ratio is pretty high in most games, given that a fragment is a pixel, right?

# Answer
> 5 votes
Vertex shaders gets called a lot less than fragment shaders. It's because the fragments get generated from the vertices with a process that is called rasterization. Rasterization basically generates fragments using the triangle's corners and give each fragment an interpolated value using the values in the vertices, produced by a vertex shader.

Let's say that you have a triangle `ABC` like this:

```
a = 0,0,0
b = 1,0,0
c = 1,1,0

```

Depending on the resolution, this generates some amount of fragments covering the whole triangle.

This will produce a triangle which covers half of the screen, which at 1920x1200 resolution will be `1920*1200/2` fragments. The amount of fragments increase with every triangle you draw.

A fragment is not a pixel. It is much more.

---
Tags: opengl, graphics, lwjgl, graphics-programming
---


# Question
Title: What is the difference between shader uniforms and attributes in OpenGL?
I don't fully understand the differences between uniforms and attributes. To be honest, I probably haven't even used attributes.

Can uniforms change for each vertex? I mean to calculate the vertex's position in screen space I just multiply the vertex's local position by the model matrix, then by the view matrix and then by the projection matrix.

Projection is constant throughout the whole scene, view is constant throughout one frame, but the model matrix changes with every object. Meaning the uniform I supply to the vertex shader as the model matrix changes a lot of times per frame. Is that good? I mean I don't see another way of transforming the object...

# Answer
uniforms will remain the same for all vertices (this is why they are called uniforms)

if you want to change it you need to call gldraw\* twice and set the new uniform between them:

```
glUniformMatrix4fv(mvpMatLoc, 1, false, mvp1);
glDrawArrays(mode, off1, count1);
glUniformMatrix4fv(mvpMatLoc, 1, false, mvp1);
glDrawArrays(mode, off2, count2);

```
> 3 votes

---
Tags: opengl, shaders, graphics, lwjgl, graphics-programming
---


# Question
Title: How to print Depth to a Texture2D and then read it in the next pass on a shader in DirectX11
I'm programming a two-pass effect in DirectX 11 (SharpDX). It's supposed to write the depth to a texture in the first pass and then use that texture to extract data on the second one in the pixel shader.

What I get is a white screen, with nothing but the interface and I don't know why nothing is being printed. What could be the problem? I would say I should get at least something from the Depth Texture.

This is how I'm setting the depth texture values:

```
this.depthBuffer = new Texture2D(device, new Texture2DDescription()
        {
            Format = Format.R32_Typeless,
            ArraySize = 1,
            MipLevels = 1,
            Width = (int)host.ActualWidth,
            Height = (int)host.ActualHeight,
            SampleDescription = new SampleDescription(1, 0),
            Usage = ResourceUsage.Default,
            BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
            CpuAccessFlags = CpuAccessFlags.None,
            OptionFlags = ResourceOptionFlags.None,
        });

this.depthBufferShaderResourceView = new ShaderResourceView(this.device, this.depthBuffer, new ShaderResourceViewDescription()
        {
            Format = Format.R32_Float,
            Dimension = ShaderResourceViewDimension.Texture2D,
            Texture2D = new ShaderResourceViewDescription.Texture2DResource()
            {
                MipLevels = 1,
                MostDetailedMip = 0,
            }
        });
var depthStencilDesc = new DepthStencilStateDescription()
        {
            DepthComparison = Comparison.LessEqual,
            DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All,
            IsDepthEnabled = true,
        };

```

And here is how I sample the depth in the .fx file:

```
int3 posTex = int3(input.p.xy, 0);
float depthPixel = DepthTexture.Load(posTex);
float4 color = float4(depthPixel, depthPixel , depthPixel, 1.0f );
return color;

```

And here the way I'm now setting the Depth Buffer stencil view as a Render Target in 2 passes. In the first I try to set the depthstencilview as a target. In the second pass I'm trying to set teh depth texture as a shader resource to read from it.

```
this.device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0));

// PASS 0
this.device.ImmediateContext.OutputMerger.SetTargets(depthBufferStencilView);
this.device.ImmediateContext.ClearDepthStencilView(this.depthBufferStencilView,     DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
this.technique.GetPassByIndex(0).Apply(this.device.ImmediateContext);
this.device.ImmediateContext.DrawIndexed(this.geometry.Indices.Length, 0, 0);

// PASS 1
this.device.ImmediateContext.OutputMerger.ResetTargets(); // unbinding the depthStencilView

this.device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0));
this.depthStencilShaderResourceVariable = effect.GetVariableByName("DepthTexture").AsShaderResource();
this.depthStencilShaderResourceVariable.SetResource(this.depthBufferShaderResourceView);
this.technique.GetPassByIndex(1).Apply(this.device.ImmediateContext);
this.device.ImmediateContext.DrawIndexed(this.geometry.Indices.Length, 0, 0);

```

Finally, this is how I set the two passes in the .fx file:

```
technique11 RenderMyTechnique
{
pass P0
{

SetDepthStencilState( DSSDepthLessEqual, 0 );
SetVertexShader     ( CompileShader( vs_4_0, VShader() ) );
    SetHullShader       ( NULL );
    SetDomainShader     ( NULL );
    SetGeometryShader   ( NULL  );
SetPixelShader      ( NULL );
}

pass P1
{
SetDepthStencilState( DSSDepthLessEqual, 0 );
SetVertexShader     ( CompileShader( vs_4_0, VShader() ) );
    SetHullShader       ( NULL );
    SetDomainShader     ( NULL );
    SetGeometryShader   ( CompileShader( gs_4_0, GShader() ) );
SetPixelShader      ( CompileShader( ps_4_0, PShader() ) );
}
}

```

# Answer
> 1 votes
My guess would be that you've bound the texture for reading and writing at the same time (i.e. it's the current depth buffer). DX11 won't let you do that (the debug runtime should give you an error message about it).

Also note that it decides what the current depth buffer is at the time you bind the shader resource, and not at draw call time so you want to bind the correct set of render targets before binding any shader resources.

There are three solutions:

1. Unbind the depth buffer while reading from it in a shader. This assumes you don't need depth testing.
2. Copy the depth buffer at some point, and read from the copy. This is clearly the slowest option.
3. Bind the depth buffer as read only. This won't work on 10.0 or 10.1 hardware.

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


# Question
Title: adapting a Unity gravitational script to allow moons
I'm using this script: http://wiki.unity3d.com/index.php/Simple\_planetary\_orbits

to get a solar system going in Unity, but it doesn't seem to support creating bodies that orbit other moving bodies (or I am using it incorrectly).

Any idea about how to modify it so that it does (or just use it correctly)? I've been beating my head against this problem for a couple hours, and I really don't feel like I have any idea what I'm doing.

Thanks in advance.

# Answer
By the look of things you should be able to apply this script to your moon and simply point to the planetary object you want it to orbit. However given the fact that your planet is moving, it looks like your moons will probably be playing catch up to the planets orbiting the sun. You should be able to fix this with a simple hierarchy change.

```
 - Sun Container Object (Parent)
   - Sun Model          (Child)
   - Planet Container Object 1
     - Planet Model 1
     - Moon Container Object 1
       - Moon Model
     - Moon Container Object 2 (if your planet has two or more moons)
       - Moon Model
     ...
   - Planet Container Object 2
     - Planet Model 2
     ...

```

The important thing to notice is that by parenting your moon objects to your planet objects they will gain the benefit of the planets orbit for free. Then they just have to adjust themselves for their localized planetary orbit. Also be sure to make your models children of empty container objects, this way you can have them rotate without messing up the orbits of the their child celestial objects.
> 2 votes

# Answer
It seems that the property

var orbitAround : Transform;

is a stationary object. You'll need to modify the code to allow this to be updated, so as your planet moves around the sun, it's moons have to revolve around the center of the planet.
> 0 votes

---
Tags: unity, orbit
---


# Question
Title: Scalability of multi-threading in game server
What is a reasonable number of threads for a simple 2D mmo in Java? Is it reasonable to have two threads per connection, one for the input stream and one for the output stream?

The reason I ask is because I use a blocking method on the input stream, and a workaround seems unnecessarily complex if I were to try to get around it without adding threads.

This is mostly for my own edification; I don't expect to have 5 million people playing it ever, or even 5, but I'm wondering what a good scalable solution is, and if this is reasonable for a small server (\<30 connections).

# Answer
> 1 votes
I think the better solution is to not reinvent the wheel here. Many Java libraries have been created to handle java networking & scalability, for example Netty or KryoNet. Another thing you either failed to consider or list was what kind of server architecture are you building out? Is this distributed, centralized, what? There is different approaches for different architectures, but these libraries are a good starting point.

Sorry if this doesn't answer "how many threads should I use", but these libraries will take care of all of this for you and it's really the better approach.

# Answer
> 0 votes
To quote coding horror: "Everything is fast for small N". Your N is small enough to make it really not matter just about anything should work. Your approach isn't memory efficient so it isn't going to scale to thousands of users.

---
Tags: java, server, multithreading
---


title: Syncing world in a multiplayer

text:
# Question
Title: Syncing world in a multiplayer
I have been working on a client-server architecture for my multiplayer game.

The server is used for communication between Clients. There is no cheat control because I trusting all clients :) I don't want to control any Physics, Cheats in the server.

My game/connection structure is like:

```
Client 1 (Admin/Host) <---> Server <---> Client 2

Moving Client 1: sending positon every frame - broadcast to Client 2
Moving Client 2: sending positon every frame - broadcast to Client 1

```

The movements is interpolated and Client 1 can move smooth in Client 2 screen, Client 2 can move smooth in Client 1 screen.

There is 200-300 ms delay in clients but movements working perfectly.

There is no any problem so far. But... **How to SYNC World/Level objects?**

I should SYNC World / Level objects because world objects (pushing box) is out-of-sync after few movements. But how I can SYNC it?

I tried, send world object positions from Client 1 to Client 2 every frame. Update world objects in Client 2. But not working, objects is unstable and jumping because 200-300 ms delay in Clients.

I searched solution from http://www.gabrielgambetta.com/fpm3.html but I can't figure out it.

# Answer
> 2 votes
Your best bet is really to just add the physics and game logic to the server. You could write the server in Flash via Adobe AIR, I believe, if you want to reuse code.

One option if you really want to keep the physics in the clients is to do a combination of prediction and "client as authoritative host" logic. The former means that clients not only move smoothly on each others' screens but that they are roughly in the same position. A dead-reckoning approach is a good way to do this on simpler games. Send over position and velocity for each object. Take into account RTT estimation to adjust position by velocity * RTT/2 when receiving it. That is, if you have 300ms latency, then the position of an object received over the network will be set to the sent position plus the sent velocity times 150ms. Without this you'll end up with a lot of glitches in the second part.

Next you'll want to make objects authoritatively owned by one of the clients. Not all objects need to be owned by one client; they can distribute the objects' ownership however you want. The physics for an object is performed solely by the owner of that object (along with the simulated character position). For instance, if player A's client owns box C then player A's client is responsible for moving box C when player B runs into it. Player B's client will never try to move box C unless told to do so by client A. This is essentially making your clients act like authoritative hosts. This is much easier if the server does everything since your clients don't need lots of checks for "do I own this object" all over the place, but it works.

You can alternatively just make one client authoritative over everything, even movement of other players. This essentially has almost all the advantages of having a central host server. The only potential issue is that the "host" player has an unfair advantage in that he has no latency and could in theory cheat.

You can with either of the second approachs allow "host migration." That is, if Player A is the host but quits mid-game, Player B takes over ownership of all objects. When you have more than two players you need some system for determining who the host player is. One good option is for every player to "bid" on being the host based on who has the least latency to the server (and hence will cause the least latency for other players). The server can be authoritative for this one thing easily enough.

---
Tags: box2d, flash, multiplayer
---


# Question
Title: How do I handle cyclic dependencies, in an entity/components system?
I built a standard C++ entity/component system, a bit like the one from this question). Components can access other components through their associated `Entity`. This is usually done by getting some kind of reference/pointer once, during component initialization. For example, a `Jetpack` component can access a `RigidBody` component, and use it to apply force to the entity. Components can be removed, during a scene, but most often, they don't. Subsystems, like `Renderer`, `PhysicsEngine`, and `InputManager` each listen for specific types of components, and processes them during each frame.

---

How should these components access each other? I see several solutions, but no good ones.

---

These are the potential solutions:

* Raw pointers: Fast, but violates the idea of RAII. How do I check, if a component is deallocated? It feels like an unsafe path.
* `shared_ptr`: This seems to work rather safely. I can live with the fact that it is a little slow, due to reference counting; the pointers are usually only setup during initialization, anyway. What about cyclic references? If two components reference each other, they'll never be deallocated. This can be remedied by manually clearing the `shared_ptr`s in some kind of `Component::terminate()`, that is called when the component is removed from the scene. The idea of "cleaning up", manually, seems to defeat the purpose of using smart pointers in the first place. Also, making sure `terminate()` is called at the right time adds complexity, as I cannot use the destructor - it's never called, due to the cyclic refs.
* `shared_ptr` and `weak_ptr`: Internally, in the engine, components are stored as `shared_ptr`s; but the outside (i.e. components) can only get `weak_ptr`s. The downside, here, is that all components have to call `weak_ptr::lock()` each time they want to access another component, which could be several times each frame. This is also true for components that use components that are known to exist throughout the entire scene, and thus don't need an existence check. Contrary to the `shared_ptr` solution, this performance penalty is incurred every frame, instead of only at initialization. Maybe it is worth it overall, but it just seems clumsy, and potentially very slow.
* Avoiding direct access: By adding a level of indirection between components, via a message system of some sort, the problem of cyclic dependencies may never emerge in the first place. I haven't experimented with this, as it seems to be overly complicated. *Could* this be overly complicated?
* Avoiding cyclic deps: I'm not quite sure how do it, but maybe you could just forbid cyclic `shared_ptr`s altogether, in some way.

---

Can the downside of these solutions be remedied, or are there better ways to handle cyclical dependancies in an entity/component system?

# Answer
> Raw pointers: Fast but violates the idea of RAII. How to check if a component is deallocated? It feels like a scary unsafe path

Raw pointers are a perfectly valid choice. All that using a smart pointer would do is move all of the ownership and dependency logic out of the component code into member variables, convoluting your ownership structure significantly and adding some minor performance overhead. There's little reason to add this complexity and bad design just to protect a programmer from a rare, easily diagnosed bug.

Raw pointers from component A to component B are perfectly valid so long as you know that component B lives past the use of said pointers. You can achieve this in a number of ways. One good way is to simply make your component system express dependencies explicitly. If the object code knows that component A depends on component B then it can disallow the removal of B until A is removed. Destruction of objects should simply not use the pointers so that destruction order is unimportant (which is easy and logical to achieve; you really don't need other components during destruction in any sane component).

If you are worried about components having optional dependencies just be sure to have an `OnAddedComponent` and `OnRemovedComponent` method or your components so they are notified when other components on the same object come or go. You can hook up or null out component pointers here.

Your components should not have too many dependencies to worry about, either. There's a few places dependencies make sense. For the other cases, either decouple components entirely, merge components that depend on each other, or use messages to make dependencies weak (messages allow all kinds of other benefits like observability to outside systems, too).
> 4 votes

# Answer
One way is to store actions in the data. This might only be a theoretical idiom which can be combined with messaging to be more practical in some situations. As a rule of thumb, you might use messaging when just the occurrence of an event matters, and data members every once there is information attached to an event.

In your example, add a member to the rigid body type holding the onetime acceleration. The physics component would add this vector to the body's acceleration and set it back to zero afterwards, on every update.

```
rigidbody->speed += rigidbody->acceleration;
rigidbody->acceleration = vec3(0, 0, 0);

```

Other components, like your jetpack component could then add some amount of acceleration to a rigid body.

```
rigidbody->acceleration += vec3(12.3, 4.5, -0.3);

```

This approach though requires all your data to be global or at least accessible from within all components. You could then write components that are both, completely stateless and independent of each other, which might be valuable.

You might also want to read Component based game engine and dependencies which has already been asked here.
> 0 votes

---
Tags: c++, entity-system, component-based
---


# Question
Title: How can I remove branches from a fragment shader function?
I have a fragment shader, when I've carefully managed to remove most branching decisions, as I have found out through research here that they are bad.

But I have one function that I just can't work out how to do it without them.

The function takes in a HSV vector, and 'expands' it. By that I mean any Value (V of HSV) from `0.0` to `0.5` gets expanded to `0.0` to `1.0`. Any Value from `0.5` to `1.0` gets de-saturated, so that it becomes more white. At `V=1.0` any input colour is white.

Here is my working function. Can anyone help me de-'if' it?

```
//expand doubles the level up to 0.5=> 1.0
//for over 0.5 then the saturation is reduced from where it is now (V=0.5) to 0.0 (v=1.0)
vec3 expand() {
    vec3 expanded;
    float newSaturation;
float newValue;

//HSV = rgb2hsv(inputColor);
if (HSV.z < 0.5) { //x = Hue,y = Sat,z = Val ,w= bugger all
    newValue = HSV.z * 2.0; //double value 0.0 to 0.5 => 0.0 to 1.0
    //no need to touch saturation
    newSaturation = HSV.y;
} else {
    newValue = 1.0; //value is max
    //need to de-saturate proportional to level over 0.5 : (1.0 - ((v - 0.5) * 2)) * s
    newSaturation = (1.0 - ((HSV.z - 0.5) * 2.0)) * HSV.y;
}

expanded = hsv2rgb(vec3(HSV.x, newSaturation, newValue));
return expanded;
}

```

# Answer
You can do it easily with a couple of saturates:

```
newValue = saturate(HSV.z * 2.0); //double value 0.0 to 0.5 => 0.0 to 1.0
newSaturation = (1.0 - (saturate(HSV.z - 0.5) * 2.0)) * HSV.y;

```

The first line is relatively simple to understand. Saturate will clamp the result to the 0-1 range so values bigger than 0.5 will end up as 1.0 which is exactly what you get in the second half of the conditional.

You can also see that for the case of `HSV.z < 0.5` the expression `(1.0 - (saturate(HSV.z - 0.5) * 2.0))` will always end up as 1.0, which won't change HSV.y when multiplied by it.
> 4 votes

# Answer
**For PC and console GPUs, branches aren't bad; they can often improve performance.** Typically, for a simple branch like this, the hardware will just run both sides for each pixel and then pick the result. Unless your shader is ALU bound (most are texture-bound), you will see absolutely zero performance from removing branches.

For a more complex/longer branch, or a branch which samples textures, the compiler may choose to use a dynamic branch. The way GPUs work is that they run many (as many as 32-64) shader cores at once, running the same instruction on different data. This group is called a "Warp" (NVIDIA) or "Wavefront" (AMD). If *any* of the fragments in a wavefront want to take that path, then every single fragment in that wavefront takes the branch. So if one pixel out of those 64 needs the then part, and the other 63 need the else part, both sides will still be executed. Same thing happens with (non-unrolled) loops. If most pixels want to execute a loop 3 times, but there's one that needs to execute it 8 times, the hardware will execute the loop 8 times for every single pixel in that wavefront.

The best practice for PC/console applications is simply to write the shaders clearly and let the compiler and user-mode driver optimize it. Then, you can use a profiler (such as GPUPerfStudio) to help find out what needs to be optimized. Sometimes this will include removing branches, but in certain cases it could be better to add them, especially if you have large clumps of pixels where much of the shader is unused (for example, smooth shadows -- most pixels are either entirely shadowed or entirely un-shadowed, so you only want to do complex smoothing at the shadow edges).

Mobile GPUs work very differently, so if you're designing your game for phones or tablets, you might want to look into best practices for those things.
> 3 votes

---
Tags: shaders, optimization, fragment-shader
---


title: Roguelike Map Structure

text:
# Question
Title: Roguelike Map Structure
I'm working on a roguelike and would like to know how to structure my map data. I suppose this question could also be extended to any sort of top down 2d game. Anyways! My game will contain object types like terrain, doors, switches, monsters, and items. How should the objects be stored within a map?

Some ideas I've gathered online:

1. The map is a 2d array. Each cell in the array can store multiple references to objects occupying it.
2. The map contains several layers of 2d arrays, and each layer stores references to objects of a specific type.
3. Like 1. but only store static terrain information in the 2d array. The rest of the objects are dynamic and stored in lists for each type.

# Answer
Answering specifically for classic-style roguelikes:

Option 3 is hands-down the most efficient choice in terms of memory usage and implementation simplicity. You could store all objects in a multi-map keyed on their coordinates. You might have different data structure for items vs mobs or the like.

Option 1 requires a bunch of data for each tile to hold the lists that will always be empty for the vast majority of tiles. Option 2 duplicates even more data (the whole array) for each object type, and sounds rather inflexible.

The only thing you need for objects in the map is a fast way to query "give me everything at position `(X,Y)`. Using some kind of map/dictionary/table works perfectly.

You may need a data structure capable of more spatial queries for more visually rich roguelikes with a lot of objects on screen at once. In this case, a quadtree (sized by tiles) would likely be better, but I've not personally ever hacked on such a roguelike. You're basically in regular 2D game territory at that point, though.
> 1 votes

---
Tags: tiles, maps, architecture
---


title: Angle Adjustment on the Y Axis

text:
# Question
Title: Angle Adjustment on the Y Axis
I just started learning 2D game development using CreateJS and I was reading this article about angular velocity to learn how to correctly move a sprite in both x and y axis.

I understand most of it except the angle adjustment.

I learned that mostly, in games, (0,0) starts at the upper left part of the screen rather than the bottom left that we are familiar with in Math. I also learned that postive y means moving down rather than up.

Is the angle adjustment related to those? Why is the value -90 degrees?

# Answer
> 1 votes
As it says:

```
// Angle adjustment to make 0 up to match how our sprite was drawn.
var angleAdjustment = -90;

```

Likely that means the sprite was created with the plane facing right. This adjusts it to face "up". The angle doesn't have any thing to do with the coordinates system.

Remember that you can always use the coordinate system you're familiar with and convert to screen coordinates at render time (but that's a different question).

---
Tags: angles
---


# Question
Title: Problems about oriented bounding boxes collision detection
I get a question for the following code which detects if two OOBs collide by SAT. The OBBs struct is also listed below.

```
struct OBB {
Point c; // OBB center point
Vector u[3]; // Local x-, y-, and z-axes
Vector e;  // Positive halfwidth extents of OBB along each axis
}

int TestOBBOBB(OBB &a, OBB &b)
{
float ra, rb;
Matrix33 R, AbsR;
// Compute rotation matrix expressing b in a’s coordinate frame
for(inti=0;i<3;i++)
   for(intj=0;j<3;j++)
      R[i][j] = Dot(a.u[i], b.u[j]);
//Compute translation vector t
Vector t = b.c - a.c;
// Bring translation into a’s coordinate frame
t = Vector(Dot(t, a.u[0]), Dot(t, a.u[2]), Dot(t, a.u[2]));

// Compute common subexpressions. Add in an epsilon term to
// counteract arithmetic errors when two edges are parallel and
// their cross product is (near) null (see text for details)
for(inti=0;i<3;i++)
    for(intj=0;j<3;j++)
        AbsR[i][j] = Abs(R[i][j]) + EPSILON;

// Test axes L=A0,L=A1,L=A2
for(inti=0;i<3;i++) {
    ra = a.e[i];
    rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2];
    if (Abs(t[i]) > ra + rb) return 0;
}

// Test axes L=B0,L=B1,L=B2
for(inti=0;i<3;i++) {
    ra = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i];
    rb = b.e[i];
    if (Abs(t[0] * R[0][i] + t[1] * R[1][i] + t[2] * R[2][i]) > ra + rb) return 0;
}

// Test axis L=A0xB0
ra = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0];
rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1];
if (Abs(t[2] * R[1][0] - t[1] * R[2][0]) > ra + rb) return 0;

//reset code are omitted

```

For the part "Test axes L=A0,L=A1,L=A2", why do we multiply each `b.e[i]` by the component from each axis in `a`'s coordinate frame then add the result together? I know this part want to project the half positive extents onto each axis in `a`'s coordinate frame, but it should do the dot product with the `b.e` vector and the projected axis, am I wrong? (that is `b.e[0] * AbsR[0][i] + b.e[1] * AbsR[1][i] + b.e[2] * AbsR[2][i]`)

For the part "Test axes L=B0,L=B1,L=B2", It seems `a.e` vector is multiplied by each axis in `a`'s coordinate frame, why don't transform the `a.e` vector into the b's coordinate frame since they are not at the same coordinate frame?

For the part "Test axis L=A0xB0", Why can we get `ra` and `rb` values by that arithmetic operation? What does `Abs(t[2] * R[1][0] - t[1] * R[2][0]` mean?

# Answer
> -1 votes
A good resource for answering your questions can be found here: http://www.stanford.edu/class/cs273/refs/obb.pdf

What you are talking about mostly is a change of 'basis' or as you say 'coordinate frame'. At the top of the function you see that there is a matrix multiply of basis A to the transpose of basis B, because in an orthonormal basis the inverse = transpose. 'Compute rotation matrix expressing b in a's coordinate frame' The entire set of equations are derived in A's basis.

The axis t is multiplied by the transpose of the relative matrix R in the 3 B's test because it was pretransformed at the top of the function into A's basis and why the A and B multiplied by AbsR are transposed (questions 1 and 2). The last 9 tests are edges of A cross product edges of B. There are lots of terms that cancel out in the derivation(question 1,2,3). I suggest you derive one A test, one B test, and one Edge Pair test so you are sure you understand what is going on.

Ps. In section 7.1 of the paper it specifically says the computation is numerically stable (the edge-on case is a non issue). The Epsilon term should be added to one side of the inequality, not the matrix elements. though it appears the effect is the same.

Essentially, your bug is in here:

```
t = Vector(Dot(t, a.u[0]), Dot(t, a.u[2]), Dot(t, a.u[2]));

```

Don't know about the rest but it looks about right.

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: How to allow other games to communicate with my Lua scripts?
I am planning some small games that will all rely on a single system of Lua scripts to manage some unified data about:

1. Some achievements that are common to each game.
2. The player's progress in completing the achievements.

Players would need to have these three parts on their system to play:

* This small set of three unifying Lua scripts.
* A single data file containing a list of challenges and the status of the player's progress in completing each.
* At least one of the small games.

The three Lua scripts manage the player's progress data file:

1. One script tells the game which challenge the player needs to complete next.
2. Another script updates the data file with information about the player's progress.
3. A final script calculates statistical information about the player's progress. A game can check use this script and decide which of this information it will show to the players.

So far, I am having the games execute the Lua scripts and using `stdout` to communicate information between the games and Lua scripts placed in a `bin` directory, which seems to work well on Linux, but I need a solution that works equally on Windows, OS X, and mobile devices and that will not be a challenge for players to install. Is this a more preferred method?

* Other developers using different programming languages should be able to easily connect their games to this system.
* Everything is stored locally, nothing uses the Internet.

# Answer
I understand you want to provide a local system for challenges and achievements.

Usually this type of functionality is managed by servers which require the games to exchange data across the internet. I would recommend going this way too.

But you will always need to keep thing locally when the connection is down or when you need to cache the data. Usually you build a library which will provide this cache in a file.

---

If you really want to keep this functionality local (on the computer) then you could try using a standard data storage system (file or SQLite) in a default location and write the data from each game to the storage.

---

If you want to handle some logics on the receiving end and you don't want to do this from your games, then indeed, you will have to run your service.

If you want a multi platform solution you will need a library to abstract the communication across processes.

In that case you are looking for a cross platform IPC library like boost::interprocess. If one day you need to run the main component as a server you will want to switch to boost::asio.

Also if you want to make the dev of your apps simpler by decoupling the different parts I would look at Google's Protocol Buffers. It makes IPC much simpler as the messaging protocol of your main app can evolve without breaking compatibility with the other apps.
> 1 votes

---
Tags: scripting, lua
---