# Question
Title: XNA: "TextureCoordinate0" missing, but I'm not using textures
I'm trying to create a voxel game using XNA, but I'm getting a somewhat bizarre error when calling `DrawIndexedPrimitives()`:

```
InvalidOperationException was unhandled
The current vertex declaration does not include all the elements required by the
current vertex shader. TextureCoordinate0 is missing.

```

Which makes *some* sense, as it's true my vertex data structure (`VertexPositionColorNormal` as shown in this Riemers tutorial) does not contain texture data.

However, the effect *shouldn't* require texture data - I made it a point to set `drawingEngine.TextureEnabled = false;` in my graphics setup method. So why is this exception being thrown? And what can I do about it?

For some context, here's my draw method:

```
public void Draw(SpriteBatch drawer)
{
    drawingEngine.View = player.createViewMatrix();

    Vector3 direction = player.getDirection();

    for (int x = 0; x < mapSize; x++)
    {
        for (int z = 0; z < mapSize; z++)
        {
            Chunk drawee = map.get(new IntVector3(x, mapCenter, z));
            if (drawee == null)
                continue;
            if(drawee.isTransparent())
                continue;
            #region chunkdrawer

            DynamicVertexBuffer vertexBuffer = drawee.getVertexBuffer();
            int numVertices = drawee.getNumVertices();
            DynamicIndexBuffer indexBuffer = drawee.getIndexBuffer();
            int numIndices = drawee.getNumIndices();

            graphics.SetVertexBuffer(vertexBuffer);
            graphics.Indices = indexBuffer;

            foreach (EffectPass p in drawingEngine.CurrentTechnique.Passes)  //Not sure I entirely understand this
            {
                graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numIndices / 3);
            }
            #endregion chunkdrawer
        }
    }
    drawer.End();
    drawer.Begin();
}

```

And here is the graphics setup method:

```
void graphicsNonsense()
{
    drawingEngine = new BasicEffect(graphics);

    drawingEngine.World = world;
    drawingEngine.Projection = projection;

    drawingEngine.TextureEnabled = false;
    drawingEngine.VertexColorEnabled = true;

    drawingEngine.EnableDefaultLighting();
    drawingEngine.SpecularColor= new Vector3(0, 0, 0);
}

```

# Answer
> 1 votes
Try calling p.Apply() in your drawing code to set the effect correctly on the GPU before drawing.

```
foreach (EffectPass p in drawingEngine.CurrentTechnique.Passes)
{
    p.Apply(); // this will set the effect
    graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numIndices / 3);
}

```

---
Tags: xna, 3d, textures
---


# Question
Title: Directional lights (not) rotating with camera (opposite problem)
I am trying to implement a shader for directional lights correctly, but I am bit confused as to why it works when it shouldn't and vice versa.

People usually encounter problem with lights changing direction with camera. This is corrected by multiplying normals with model(view) matrix.

But my problem is opposite.

When I don't multiply normals with model(view) matrix then it works and when I try to use (supposedly) correct version it is having that "lights rotating with camera" problem.

Any ideas?

Working vertex shader:

```
#version 330
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 texCoord;
layout (location = 2) in vec3 normal;

out vec2 texCoord0;
out vec3 normal0;

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;

void main()
{
    normal0 = normal;
    gl_Position = proj * view * model*  vec4(position, 1.0);
    texCoord0 = texCoord;
}

```

Fragment shader:

```
#version 330
in vec2 texCoord0;
in vec3 normal0;
out vec4 outColor;

struct BaseLight
{
    vec3 color;
    float intensity;
};

struct DirectionalLight
{
    BaseLight base;
    vec3 direction;
};

uniform vec3 baseColor;
uniform vec3 ambientLight;
uniform sampler2D sampler;
uniform DirectionalLight directionalLight;

vec4 calcLight(BaseLight base, vec3 direction, vec3 normal)
{
    float diffuseFactor = dot(normal, -direction);

    vec4 diffuseColor = vec4(0,0,0,0);

    if(diffuseFactor > 0)
    {
        diffuseColor = vec4(base.color, 1.0) * base.intensity * diffuseFactor;
    }

    return diffuseColor;
}

vec4 calcDirectionalLight(DirectionalLight directionalLight, vec3 normal)
{
    return calcLight(directionalLight.base, -directionalLight.direction, normal);
}

void main()
{
    vec4 totalLight = vec4(ambientLight,1);
    vec3 normal = normalize(normal0);
    totalLight += calcDirectionalLight(directionalLight, normal);
    outColor = texture(sampler, texCoord0.xy) * vec4(baseColor, 1) * totalLight;
}

```

Draw method:

```
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex::SIZE* 4, 0);
glVertexAttribPointer(1, 2, GL_FLOAT, false, Vertex::SIZE * 4, (const GLvoid*)12);
glVertexAttribPointer(2, 3, GL_FLOAT, false, Vertex::SIZE * 4, (const GLvoid*)20);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);

```

Matices:

```
ViewTranslate = glm::mat4(1.0f);
 cam->control(windowHandle, 0.01, 0.3, true, &ViewTranslate);
 cam->updateCamera(&ViewTranslate);

glm::mat4 Projection =
    glm::perspective(70.0f, 800.0f / 600.0f, 0.1f, 10000.0f);
glm::mat4 view = glm::lookAt(
    glm::vec3(0, 0, 1),
    glm::vec3(0.0f, 0.0f, 0.0f),
    glm::vec3(0.0f, 1.0f, 0.0f)
    );

shader->bind();
shader->setUniform("model", glm::value_ptr(ViewTranslate));
shader->setUniform("view", glm::value_ptr(view));
shader->setUniform("proj", glm::value_ptr(Projection));
shader->setUniform("ambientLight", ambientLight);

```

Not working shader code:

```
void main()
{
    normal0 = (model * vec4(normal, 0.0)).xzy;
    gl_Position = proj * view * model*  vec4(position, 1.0);
    texCoord0 = texCoord;
}

```

or

```
void main()
{
    normal0 = (model * view * vec4(normal, 0.0)).xzy;
    gl_Position = proj * view * model*  vec4(position, 1.0);
    texCoord0 = texCoord;
}

```

or

```
void main()
{
    normal0 = (model * view * vec4(normal, 1.0)).xzy;
    gl_Position = proj * view * model*  vec4(position, 1.0);
    texCoord0 = texCoord;
}

```

or

```
void main()
{
    normal0 = (transpose(inverse(model * view)) * vec4(normal, 1.0)).xzy;
    gl_Position = proj * view * model*  vec4(position, 1.0);
    texCoord0 = texCoord;
}

```

...

Any ideas how I should do this correctly?

# Answer
So, it seems that the light vector wasn't in the camera space.... so, be sure to transform lights into the camera space prior to sending to the shader
> -1 votes

---
Tags: opengl, matrix, glm
---


title: LibGdx Input data in a textfield

text:
# Question
Title: LibGdx Input data in a textfield
I have a textfield using scene2d but don't know how to save user input. this is what i have and it just draws the textfield.

```
     txtUsername = new TextField("", mSkin);
     txtUsername.setMessageText("test");
     txtUsername.setPosition(30, 30);
     mStage.addActor(txtUsername);

```

# Answer
TextField has a method called getText(), it may never be null but may return an empty string.

```
txtUsername = new TextField("", mSkin);
txtUsername.setMessageText("test");
txtUsername.setPosition(30, 30);
mStage.addActor(txtUsername);
String test = txtUsername.getText();
System.out.println(test);

```

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/TextField.html#text
> 4 votes

---
Tags: java, libgdx
---


# Question
Title: How to compute matrix transform local/world on OpenGL
I'm developing an **OpenGL** program where each object / entity contains **m\_WorldPosition, m\_WorldOrientation, m\_WorldScale and m\_WorldTransform** (Vector3, Quaternion, Vector3 and Matrix4f).

The problem is that these transformations are global. So I move, rotate and scale an object / entity I need to use a function that I did.

```
// C++
void HEntity::translate(const HVec3f& pos, const bool local)
{
    if(local) {
        m_WorldPosition += m_WorldOrientation.toMatrix3() * pos;
    } else {
        m_WorldPosition += pos;
    }

    m_NeedTransformUpdate = true;
}

```

I wanted to do the same as other software such as **Blender** or **Unity3D 3D** where each object / entity contains the variables **position, localPosition, rotation, localRotation**...

I want a similar system. Where I have the variables position, localPosition, orientation, localOrientation, scale, localScale. But I do not know how to apply it to matrix Each object / entity.

Below is the function to compute the matrix.

```
// C++
void HEntity::updateTransform()
{
    m_WorldTransform.identity();
    m_WorldTransform.setRotationAxis(m_WorldOrientation.getAngle(), m_WorldOrientation.getAxis());
    m_WorldTransform.scale(m_WorldScaling);
    m_WorldTransform.translate(m_WorldPosition);

    if(m_pParent) {
        m_WorldTransform =  m_pParent->m_WorldTransform * m_WorldTransform;
    }
}

```

And the game loop

```
// C++ - Game loop

HGameObject* object = NULL;
int index = 0;

for(; m_ObjectCount; index++)
{
    object = m_pObjectList[index];

    glMultMatrixf(object->m_WorldTransform.getTranspose());

    // Draw current object

    glPopMatrix();
}

```

# Answer
You should:

* bind the shader with the modelview matrix for transforming the first object
* bind the buffer with the vertex data for the first object
* draw
* bind the shader with the modelview matrix for transforming the second object (or use the same shader and change only matrix through uniform)
* bind buffer with the vertex data for the second object
* draw

similar question
> -1 votes

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


# Question
Title: Do google game services require the users to have a g+ account to enter lobby?
I've been reading Google Game Services (GGS) API about multiplayer lobby/rooms and the documentation doesn't make it very clear if the users are required to sign in with a Google+ account (which I don't want).

The web GGS SDK mentions this:

> The simplest way to add a sign-in button to your page is to implement the HTML-based sign-in button. For implementation details, see Adding the HTML sign-in button to your page on the Google+ Sign-In documentation.

What I am looking for is a simple way (service or library) to connect anonymous users together (matchmaking). My application being in Java, a Java compatible API is also needed.

**Can Google Game Services fit the bill or should I keep looking?**

# Answer
> 1 votes
Yes, they are required to sign in with a Google Plus account. It's possible to use the leaderboard without requiring users to sign in. You won't be able to connect players without them having accounts. The service is free because it allows Google to collect data on its users (play trends, in app payments, social sharing, etc.), thus it requires the users to sign in.

---
Tags: java, multiplayer, google-play-services, matchmaking
---


# Question
Title: Weird effect when generating gradients for height map
I am experimenting with generating height maps using radial gradients and perlin noise, using a technique I found here: http://www.reddit.com/r/gamedev/comments/1g4eae/need\_help\_generating\_an\_island\_using\_perlin\_noise/cagmlsi.

This is my code:

```
 public override void generate(int seed) {
        Random rand = new Random(seed);

        float[,] pixelMap = new float[gridSizeX, gridSizeY];

        // generate random starting points for the islands
        centers = new int[ISLAND_COUNT,2];
        for (int i = 0; i < ISLAND_COUNT; i++) {
            centers[i, 0] = rand.Next(0, gridSizeX - 1);
            centers[i, 1] = rand.Next(0, gridSizeY - 1);
        }

        float maxDistance = 0;
        for (int x = 0; x < gridSizeX; x++) {
            for (int y = 0; y < gridSizeY; y++) {
                // calculate the distance for each center node to the current coords.
                // pick the distance that is closest for the color value
                float distanceToCenter = 9999999; //artificially high number
                for (int i = 0; i < ISLAND_COUNT; i++) {
                    int centerX = centers[i, 0];
                    int centerY = centers[i, 1];
                    float localDistance;

                    //Simple squaring, you can use whatever math libraries are available to you to make this more readable
                    //The cool thing about squaring is that it will always give you a positive distance! (-10 * -10 = 100)
                    float testX = x;
                    float testY = y;

                    float distanceX = (centerX - testX) * (centerX - testX);
                    float distanceY = (centerY - testY) * (centerY - testY);

                    localDistance = (float)Math.Sqrt(distanceX + distanceY);

                    // let's see if the wrapped distance is shorter; if so use that.
                    // this allows our gradient to wrap along the X axis
                    if (x > centerX) {
                        testX = (gridSizeX - x) + centerX * 2;
                    } else {
                        testX = (gridSizeX + x);
                    }

                    distanceX = (centerX - testX) * (centerX - testX);
                    if (localDistance > (float)Math.Sqrt(distanceX + distanceY)) {
                        localDistance = (float)Math.Sqrt(distanceX + distanceY);
                    }

                    //is this closer than the last recorded distance? If so use it
                    if (localDistance < distanceToCenter) {
                        distanceToCenter = localDistance;
                    }

                    // record the maximum distance calculated
                    if (localDistance > maxDistance) {
                        maxDistance = localDistance;
                    }
                }

                // add the color to the pixel map, adjusted for an rgb between 0 and 255.
                pixelMap[x, y] = (distanceToCenter / gridSizeX) * 255 * 2;
            }
        }

        drawImage(pixelMap);

        // save image of final generation
        passOutput.Save(@"test.png", ImageFormat.Png);
    }

```

This code generates an image like this though:

the red dots (if you can see them) are diagnostics code I added to mark the center of the gradients.

I am completely stumped as to why these white borders are happening at the midway points between gradients. I feel like there is a simple solutions to this, but I have been at this for days and have been unable to fix it no mater what I try.

What I am expecting is something like this mockup made in Photoshop:

Notice how there are no sharp edges; all gradients int he image blend into each-other seamlessly.

Any ideas?

# Answer
> 3 votes
Here are four options that you can try:

**A) Scale & threshold existing output**

You can ensure that the gradient saturates at some maximum value before reaching any of the cell borders. This will tend to make small holes of uniform size, but you can introduce size variation by assigning a random scale factor to each seed point and scaling distances to that point before comparing with its neighbours.

**B) Blur existing output**

This is self-explanatory. With a wide enough blur kernel, you can smudge the sharp borders into smooth high regions like in your example. This may require some scaling/offsetting to maintain the desired contrast/mins/maxes.

**C) Smooth Voronoi**

Iñigo Quilez describes a method to generate a Voronoi pattern with smooth borders. The low-power exponential falloff shown in the top-left is fairly similar to your target example:

**D) Multiply all distances**

Rather than outputting the distance to the closest point, return the product of the distances to all of the points. This gradient still hits zero at each seed point, but has no first derivative discontinuities between them (unlike standard Worley F1 noise). This will require some scaling to keep in the desired brightness range.

---
Tags: mathematics, procedural-generation, image, heightmap
---


# Question
Title: Best practices for periodically saving game state to disk
I'm working on an MMO. All of the player and environment data lives on a server and is kept in memory. There's a "world" object which keeps track of all of the maps, characters, etc. and their relations to each other.

To avoid data loss in case of a crash, I've been periodically serializing the world to disk. The trouble is, this object can be quite large, so when the server starts writing, there's noticeable in-game slowdown for a few seconds, which I'd like to avoid.

Any pointers on how to go about this in a more efficient way?

# Answer
(1) Only save the really important bits, (2) only save them when they have changed since the last time they were saved, (3) save them individually, and (4) save them via an asynchronous system.

1. Much of the world is likely to be static - that data doesn't need to be serialised at all, as it probably already exists on disk in some form. At the other end of the scale, several variables are so transient that they don't need to be serialised either. An example would be hit points - it's hard to imagine a situation where your business is harmed if a server restarts and resets hit points to full, so don't save them.
2. Set a flag on each part of the data, set it to True when you perform an update or insert operation on that part of the data, and only save the data if that flag is True. Otherwise, leave the previously written version in place. (This requires that you're not just writing the whole thing as one lump - see the next section.)
3. You should separate the specific items that need saving and be able to save them individually. In some games, this is just players. Other games save items on the ground; some may save important NPCs too. Very few are saving absolutely everything. But when you can save things individually, you can easily save the world a bit at a time and make saves quicker.
4. If you use a database for your persistent data, these often provide an asynchronous interface which will return immediately while saving in the background. (But beware of error conditions that could potentially leave you without a valid save point.) Alternatively you can perform your writes in a background thread, providing you were able to make an in-memory copy of the relevant state first.
> 12 votes

# Answer
It wasn't clear to me from your question whether you're already doing this or not, but: do the save in a separate thread (or using asynchronous I/O, available in some OSes). Then your game code can continue to run while the save happens in the background. Of course, you'll have to snapshot the game state in memory so you're not updating state while you're in the middle of saving it. (Hopefully the state is not so large that making a copy of it in memory causes noticable lag!) Also, whether using threads or async I/O, there should be some sort of priority knob you can turn to prevent the background work from taking too much time away from the main game thread.
> 2 votes

# Answer
If your MMO server is running on a Linux/Unix OS, you might be able to take advantage of the inherent copy-on-write properties of vfork(). This trick is used by some database software such as Redis to make consistent point-in-time snapshots without stopping the server.

When you call vfork() the OS makes a clone of your process, however it does not copy the memory of that process. The clone will still share the same memory pages, as long as they are equal. The OS will create copies of pages as needed when they are modified by either of the process. Page sizes are usually 4kb in linux. If you think about it, this is your delta compression, except you don't have to write any code for it. The OS already does the dirty work for you (utilizing the hardware MMU, etc).

Once you call vfork(), your parent process can continue to operate as normal, and your child process, which is a clone of the game universe at the time of vfork(), should no longer process the game and instead take all its time writing out all of the object states. It can possibly use lower priority, throttle down the IO, etc. Once it finishes, it should exit.

The beauty of this is that all your game state is consistent to the exact point of the fork 'snapshot'. You are essentially making the OS do all the hard work for you of keeping dirty bits etc. You will not get into a situation where some of your objects got modified after you had begun saving the game, while others didn't.

This trick was used in the original Ultima Online, as some of the devs mentioned it in this discussion.
> 1 votes

# Answer
Base your game around Events, and log every single tiny Event. Whenever you need to load data or something, just iterate over the related Events and woila everything's back.

For Events, you can use either database, text files or whatever storage, it's basically a logging mechanism.

Then you can cache current Event state before moving Events to backup for like 1-3 times a day on a separate server or when the load time is less than `X`%. Caching works like restore point - if the player had 12313 Events in last 3 hours, that's a lot of loading time the next time he comes online, so, when it's cached, it would read the cached state from memory and log new Events, that would later also be re-cached and so on and so forth.

Only thing here is, you need a nice set of algorithms or something for Event state cache.

I'm in a hurry at the moment, will explain in detail later.
> 0 votes

---
Tags: mmo, data, savegame
---


# Question
Title: Texture organization and budgeting for a HD Sprite Based Game
I've been making a game that features 2 traditionally animated playable characters, hd backgrounds, props, and extra special effect animations. Things have gone well so far, but I have a few questions regarding HD animated sprites and the use of texture atlasing.

The first: **What are some best practices to determine the total texture budget of a modern 2d game?** So far, I have considered the following: The characters on their own take up roughly 256 x 256px worth of screen space, but of course that size will vary depending on the intended size of the character. I expect each character to have more than 10 - 12 unique animated sequences. The frames per animation will obviously vary as well depending on the animation length and level of detail. Assuming each animation has about 15 frames, that would mean that a single character's texture atlas could be something around the lines of 3072 x 3072px (or rounding up to the nearest power of two). Two characters would obviously require double the texture size in memory.

Basically, **how do I determine if a budget is "acceptable" for modern hardware? How can I tell if it's ok that, at worst, two characters require 6144x6144px worth of memory space?**

Secondly: **Is it better to load all of our sprite's resources on one huge atlas texture? Or separate textures for each animation?** For example, instead of one big "character.tga" file with every animation, you could have "character\_idle" and "character\_attack" and "character\_win" which could be loaded as separate resources. On one hand, it would probably both be slower to load and harder to manage if every animation was a separate texture resource. On the other hand, if you only needed to have a characters "idle" animation, you could choose to only load that animation.

# Answer
> What are some best practices to determine the total texture budget of a modern 2d game?

This likely depends on the *size of your target platforms RAM/VRAM*, and how much you'll *need to have loaded at one time*. It's probably something that you have to fine-tune. Another thing to consider is *non-volatile storage* (media/disk space, etc.).

> How can I tell if it's ok that, at worst, two characters require 6144x6144px worth of memory space?

Texture budget will depend on what hardware you're targeting, as each device will have a different *maximum texture size*. Look at the range of devices that you plan on supporting (mobile devices, consoles, PC hardware, etc.) and try to find out the lowest common denominator. If you have two characters, you probably don't want to have their sprites on the same atlas due to the fact that only one of them might be needed at a time.

> Is it better to load all of our sprite's resources on one huge atlas texture? Or separate textures for each animation?

It's a trade off. *Switching UV indices within a single texture is a lot faster than binding a different texture.* However, having textures that are too big or being forced to load more than you need at any given time is also not ideal and can bog down performance. It could be that the time to bind a different texture is relatively minimal, in which case multiple texture atlases might be the way to go. But if your character switches animations very frequently, and each animation is only a few frames, then you might find it works better to pack as many frames into your atlas as you can until you reach your decided max texture size.

Good luck.
> 1 votes

---
Tags: textures, animation, spritesheet, resource-management
---


# Question
Title: Where should I put code if I want it to run automatically?
I'm new to programming and I found an animation script that has code that is called in the `OnMouseDown` event, when the user clicks the object. I'd like the code to run automatically, instead of responding to an event. Where can I put code to be called automatically

# Answer
I'm not sure entirely what you mean by "code start automatically" or but I assume you want to make it so that the animations play immediately once the scene loads. If that is the case, all you need to do is call the "Play()" function inside the "Start()" function.

You should consider reading Unity's Documentation on the Monobehaviour Class. What you have right now works because it is, essentially, overloading a function in the base Monobehaviour class which recieves an event on click. If you wish to define different conditions which make the animations play or stop, you need to add a function overload or implement your own logic depending on the results you desire.

Lastly, since you've added that you are new to programming, I would suggest you read up more on object oriented design and coding fundamentals before continuing with Unity. You can get by with looking at pre-made code samples, but understanding the way programming works on a fundamental level will help you when it comes to reading API documentation and understanding the flow of programming.

I hope this helps, let me know if you were looking for something more specific.
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: How do I make my sprite freeze on a frame?
I'm trying to make a working duck animation but the animation keeps looping, how do I make it so that the duck animation freezes on a sertain frame?

Right now I use a variable to loop it so that it loads the animation over and over, but I want it to pause at the last frame at the moment the animation looks like this :

```
if (elapsed >= delay) {
    else if (count < 3 && twoFrames == true) {
        frames++;
        count++;
    }
    elapsed = 0;
    if (twoFrames == true) {
         sourceDuck = new Rectangle(50 * ducklist[frames], 0, 50, 43);
    }

```

Delay is set to 90f

# Answer
I would advise against coming up with your own logic like pausing at the last frame of animation, or such if you plan on doing more animations later. I've done this when I started and it can very quickly go out of hand.

You could accomplish this with a state machine. This is a simple yet very easily customizable way of doing animations in case you implement it well. This is used very often in game development. For example, you define a start state, "idle" where the standing animation plays. From there you could go into several states which have different rewuirements. For example, the ducking state has a requirement of inputting the down key. You could create three states: duckStart, duck, duckEnd.

DuckStart state: from idle state you could go to this state if you input down key (just an example). The animation where the character goes from standing, to ducking animation plays.

Duck state: you can go to this state, from duckStart state if the duckStart animation reached its last frame and you are still pressing down key.

DuckEnd state: you can go to this state from duckStart state, or the duck state if you cancel the down key press.

You could look up Finite State Machines for further information.
> 0 votes

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


# Question
Title: Mobile Game Development: Supporting Multiple Screen Resolution for iOS
**Questions**

1. When designing the graphics of the game (e.g. for iPhone): What is the resolution I should base it upon? Is it the smaller resolution (iPhone4 screen resolution) so that I could scale it bigger to bigger resolution devices later on or the bigger resolution (iPhone6+) so that I could scale it smaller for smaller resolution devices later on? Which solution would be the best to implement that will not distort the graphics?
2. I am creating a game now (endless runner type game) and I am using parallax backgrounds. What will be the best option in supporting multiple resolutions? Scale it so that it will look the same on every device but it might distort the image or reduces the viewing area of the game when scaled. Alternatively let the other parts of the background be seen on larger resolution devices making the graphics stay as it is but let users using larger resolution devices see objects that might not be seen on smaller devices. I am talking about the next part of the parallax background.

My question pertains to iPhone devices (iPhone 4/4s, iPhone 5, iPhone 5s, iPhone 5c, iPhone 6, iPhone 6 Plus) for now.

# Answer
1. The easiest solution would be to create the graphics at the size of the highest resolution, but older iPhones have little memory so this solution would only work (smoothly) on the newer models. Instead you should target 2 resolutions. 1920 x 1080 for the iPhone 6(+) and 1136 x 640 for the 5(S). In this way you will only have to downscale for the iPhone 6. This downscaling should not have a huge effect on performance since the hardware in the iPhone 6 is more than capable.
2. Generally you would want the experience to be the same across all devices. The iPhone 5 and up all have a 16:9 aspect ratio. Unfortunately the iPhone 4(S) doesn't. For these you will either have to downscale the content a little further and have an empty space on the top/side or have some content falling off. The latter probably isn't the best idea so downscaling and having a little extra space on top seems like the best solution.

The whole image is the screen of the iPhone 5(S), cut off area 2 and you get the screen of the iPhone 4(S). Now, if you want to have the same content visible on the iPhone 5 and 4 then you will need to keep the same aspect ratio. The 5 its aspect ratio is 16:9. When we apply this to the iPhone 4 then you will get area 1. The grey areas will not have any content. You can fill this up with a nice background or display an UI.
> 1 votes

# Answer
Before you do anything with your program, check which phone the app is on and edit the screen size based off that.

Apple Developer site --\> UIDevice class. this class lets you get software and hardware information about the specific device your running.

then do a series of if else if statements that 1 by 1 compare, when it matches, it sets the display, then you go into your program loop.
> 0 votes

---
Tags: graphics, iphone, mobile, resolution, parallax-scrolling
---


# Question
Title: Problem with preloading plist file in Cocos2d-x
I am using Cocos2d-x engine with 3.2 version.

In my splash screen I am prefeching a plist by below line

```
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("ui.plist");

```

Now inside game when I am creating a sprite I am getting an assert fail error

```
Sprite *ss = Sprite::createWithSpriteFrameName("pause.png");

```

> Assert failed: Invalid spriteFrameName: pause.png

Also when the splash screen is removed, I am getting the below line in console

> cocos2d: TextureCache: removing unused texture: D:/cocos2dx/projects/ABCD/Resources/mid/ui.png

Is there anything I need to add or something?
I was doing the same thing for 2.x and was working but not in 3.2

EDIT: In 3.x if you are calling this line `Director::getInstance()->purgeCachedData();`, remember that it will delete all textures from the cache memory. So handle all sprite-sheets manually.

# Answer
> 2 votes
Do you have a SpriteBatchNode object added to the scene? According to the cocos2d-x wiki:

> A SpriteBatchNode object contains the actual image texture of all the sprite frames. You must add it to a scene, even though it won’t draw anything itself; it just needs to be there so that it is part of the rendering pipeline. For example:

```
SpriteBatchNode* spritebatch = SpriteBatchNode::create("animations/grossini.png");

```

> Next, you need to use the SpriteFrameCache singleton to keep track how frame names correspond to frame bounds – that is, what rectangular area of the sprite sheet. Example:

```
SpriteFrameCache* cache = SpriteFrameCache::getInstance();
cache->addSpriteFramesWithFile("animations/grossini.plist");

```

> Once your sprite sheet and frames are loaded, and the sprite sheet has been added to the scene, you can create sprites that use these frames by using the createWithSpriteFrameName method, and adding it as a child of the sprite sheet:

```
m_pSprite1 = Sprite::createWithSpriteFrameName("grossini_dance_01.png");
spritebatch->addChild(m_pSprite1);
addChild(spritebatch);

```

If I use "createWithSpriteFrameName("sample.png")" my app crashes. But if I use "initWithSpriteFrameName("sample.png")" the app runs perfectly, I tested this just now before writing this. And I also call addSpriteFramesWithFile from every scene to deal with the unloading.

---
Tags: sprites, cocos2d-x
---


# Question
Title: How to avoid checking the same triangle twice in collision detection with spatial hashing
I'm implementing a spatial hashing system to speed up my collision detection, but I've run into a problem. Since a triangle can be hashed into multiple buckets, how do I ensure that I don't check the same triangle multiple times?

I've though about having each `struct Triangle` have a list of pointers to each triangle it has been checked against, as well as a `double lastTimeChecked`. That way, if the lastTimeChecked was less than the current time, I would know all that data was invalid. This seems inefficient because I am guessing I would have to have this list be a `std::vector` since I won't know ahead of time how big the list should be.

Then, each time I want to check one triangle against another, I check each triangle's list of triangles it has been checked against to see if either has been checked against the other. Is this the most efficient way to do it?

# Answer
Are you always doing triangle v triangle, or could it be triangle v sphere? Regardless, I think I would break it down into two problems: collecting candidate triangles for collision detection, and the detection itself. As you point out, when you hash into multiple buckets you need to identify and reject duplicates. I have two solutions, both of which I have used before. Both assume that the triangles in a given mesh are identified in the hash using a zero-based ID

1. Store a flag for each triangle in an array, associated with the mesh. This array is allocated once and owned by the mesh. When testing the triangle, use the triangle ID to first check the flag. If the flag is unset, add triangle ID to resulting list of candidates and set flag. Ignore triangles with flag already set. I encode this as a bitflag array so 8 triangles is 1 byte. I share this with all queries as long as it isn't multithreaded. Right before each search for triangles, I clear the array to zero. Performance is not bad.
2. Store a last\_search byte per triangle in an array, allocated once, associated with the triangle mesh. Have a static search\_number byte for all queries, again associated with the triangle mesh. Initialize each triangle byte to zero via memset(). Initialize the static to zero. On first search increment search\_number. Any triangle last\_search not equal test and set to new number. If search number, when incremented, is zero memset last\_search array to zero. Result is a clear every 254 searches.

Either work but one is less memory.

Does that help?
> 2 votes

# Answer
Is this actually a problem? How much overhead would you incur by allowing the same check to happen twice in these cases?

It is quite possible that the check would cause a bigger overhead than it saves.

If you need to eliminate double results from the final set of collisions, I suggest that you do so after you have found them. The set of actual collisions is usually much smaller that the set of collisions tested for, so the overhead of such a check will also be much smaller.
> 1 votes

---
Tags: c++, collision-detection
---


title: Can I make a mirror with Unity Free?

text:
# Question
Title: Can I make a mirror with Unity Free?
If I understand correctly, render textures are a feature of Unity Pro, and that is the best way to create mirrors, TV screens, and so forth. If I am wrong, please tell me. What I would like to know is if there is another, probably less-convenient, way to create a mirror with the free version of Unity. If I need to write a custom script, I would appreciate a basic outline of how to write it. Even better, if you know of a free script package that does this, please tell me.

# Answer
> 8 votes
You are correct in that render textures are the best way to do mirrors in Unity. Coincidentally, a game that I worked on recently required the use of mirrors (though our mirrors would also reflect things that may not exist in the world). We were also developing with Unity Free, so we had the same problem as you.

Our solution was as follows (recommended to us by a professional who works with Unity): write a script that copies a GameObject, and strips all Monobehaviour, Physics, etc. components off that object (as well as it's children). Basically all that should be left is the transform and the mesh/material data. Then, depending on the mirror location and orientation, you can change the transform of this shell object to the appropriate location on the other side of the mirror. We used a nifty parenting trick that I can't remember the exact code for.

For any dynamic objects, you'll have to write a script to update the 'mirror object' based upon the original object's location and animation. You could either store a reference to the original object in your mirror object, or vice versa. This is probably the hardest part of the process.

As for the mirror itself, you can apply any kind of transparent material to it in order to make it look a bit more like the surface you want.

The whole process itself sounds daunting but when it comes down to it, mirroring in this way isn't actually that bad. It's when you want different things happening in the 'mirror world' that it gets messy.

Hope this helps :)

# Answer
> 0 votes
Maybe an old topic, but for those unity devs out there... they are bringing the stencil buffer to free version in untiy 4.6, this way, you can make basic mirrors with the ability to cull objects out of the other side.

# Answer
> 0 votes
AFAIK You Cant make a perfect one, but if you make a cubemap of the room and set the shader of the mirror to Reflective/diffuse, then apply the room cubemap, you get a good feeling of a mirror. you just gotta tweak the cubemap to get it perfect and make the face sizes more than 64 or it will look blurry.

---
Tags: textures, unity, rendering
---


# Question
Title: 2D graphic over 3D perspective projection
To draw a 2D HUD (just a simple trianlge, for now) over 3D graphics in OpenGL I :

* draw all 3D objects, then
* call glDisable(GL\_DEPTH\_TEST) before drawing 2D HUD
* draw 2D triangle
* call glEnable(GL\_DEPTH\_TEST);

however it seems I am missing something and the triangle is only rendered when I set Model-View-Projection matrix to Identity :

```
DrawFrame() {
.
.. // Draw 3D objects
.
/*
*  Coordinates of 2D triangle
vert[0] = 0.0f; vert[1] = 0.5f; vert[2] = 0.0f;   // TOP
vert[3] = -0.5f; vert[4] = -0.5f; vert[5] = 0.0f;  // LEFT
vert[6] = 0.5f; vert[7] = -0.5f; vert[8] = 0.0f;   // RIGHT
*/

glDisable(GL_DEPTH_TEST);

glm::mat4 guiMVP = glm::mat4(1.0f);
//glm::mat4 guiMVP = Ortho * View * glm::mat4(1.0f);   // This does not render triangle
//glm::mat4 guiMVP = Projection * View * glm::mat4(1.0f);   // This DOES render triangle at its place but in 3D world
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &guiMVP[0][0]);
...
.. // render2D triangle
glEnable(GL_DEPTH_TEST);
}

OnSurfaceChanged(int width, int height) {

    glViewport(0, 0, width, height);

    aspect = (float) width / height;

    // Projection Matrix
    Projection = glm::perspective(45.0f, aspect, 0.1f, 10000.0f);
    // Orthographic Matrix for 2D HUD
    Ortho = glm::ortho(0.0f, (float)width, (float)height, 0.0f);
}

setCamera(float cameraX, float cameraY, float cameraZ, float cameraLX, float cameraLY, float cameraLZ) {
    // Camera/View matrix
    View = glm::lookAt(
        glm::vec3(cameraX, cameraY, cameraZ),     // Camera position
        glm::vec3(cameraLX, cameraLY, cameraLZ),     // pointing at
        glm::vec3(0, 1, 0)      // Angle
     );
}

```

here's my **Vertex shader :**

```
attribute vec3 in_Position;

uniform mat4 MVP;

void main(void) {
    vec4 v = vec4(in_Position, 1.0);

    gl_Position = MVP * v;

}

```

This is screenshot of what I want : I DO get this output by using an Identity MVP matrix for 2D graphics. I know this is an ugly hack that works for now.

**How to do this properly using Orthographic matrix ?**

# Answer
> 2 votes
When drawing 2D over 3D you don't need to apply view matrix. You only need to apply the orthographic projection.

Applying the view matrix dones't work because it changes the position and rotation of the objects relative to the camera you don't want that.

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


# Question
Title: Why is it Important to have render targets with the same bit size?
I am currently thinking of what type of GBuffer I'll need for deferred shading, hence I tried also to document myself online about the most common ones and their format.

Most of the GBuffer that I've seen used the same bit size for each render target, leading also often to unused channels. However, as first guess for my GBuffer, on paper, I need two 24 bit targets and two 32 ones or three 24 and one 32.

I understand that having the same "size" each attachment can be aligned better, but practically speaking is it better to waste channels (or reserve them for future use) and having all the RTs of the same size or I should use just what needed? In the former case, why it is such advantage, will the 24 bit ones be padded to 32 anyway?

# Answer
> 9 votes
> I understand that having the same "size" each attachment can be aligned better, but practically speaking is it better to waste channels (or reserve them for future use) and having all the RTs of the same size or I should use just what needed?

Having a unified 32bit aligned Render Targets is better, even if it means *"wasting"* some memory. This will be much faster than having a non 32bit aligned memory. Also you won't have the trouble of supporting multiple types of buffers, copying and combining buffers will be easier since you won't have to convert between multiple types.

32bit is the native for GPUs and CPUs, hence you will reduce the number of required cycles to read the memory. GPUs will naturally try to read 32bits, if you are trying to read unaligned memory address, such as 24 bits aligned, GPUs will read 32bits and then will shift out unwanted bytes.

Here is a detailed article of why memory alignment matters (eventhough it talks about CPUs not GPUs the high level concept still applies.)

> Will the 24 bit ones be padded to 32 anyway?

Some GPUs will pad it, but it can't be guaranteed, so it lays in the driver/GPU implementation area. So you have to profile and check the results.

PS: 32bit or 64bit depending on the architecture.

---
Tags: opengl, deferred-rendering, memory-efficiency, deferred-shading, multiple-render-targets
---


# Question
Title: Set a different animation rate for moving player NOT using a sprite
I am trying to start making a simple game using HTML5 with a canvas and some JS. I have a player whose movement I am comfortable with, but the rate at which the player animates when it moves is too fast.

Now the way I'm handling that animation ATM is that it does not use one image that gets positioned differently depending on movement, rather it alternates between two different images depending on which direction it is moving. It should become a bit more clear in the code. I imagine part of the solution might be handling the movement vs the alternating images in different sections, but I admit I'm not too familiar with this and its the first time I've made such a game.

```
$(document).ready(function(){

    //****************************************************//
    //******   Create and get Canvas and its info  *******//
    //****************************************************//
    var canvas = $("#canvas")[0];
    var ctx = canvas.getContext("2d");
    var w = $("#canvas").width();
    var h = $("#canvas").height();

    var score = 0;

    //the background, loaded and drawn onto canvas
    var FPS = 30;
    setInterval(function() {

        draw();
        update();

    }, 1000/FPS);

    //****************************************************//
    //**********  Load the images        *****************//
    //****************************************************//

    //not moving:
    var img = new Image();
    img.src = "still.png";

    //primary frames
    var img_down = new Image();
    img_down.src = "down.png";

    var img_up = new Image();
    img_up.src = "up.png";

    var img_left = new Image();
    img_left.src = "left.png";

    var img_right = new Image();
    img_right.src = "right.png";

    //secondary frames
    var img_down_b = new Image();
    img_down_b.src = "down_b.png";

    var img_up_b = new Image();
    img_up_b.src = "up_b.png";

    var img_left_b = new Image();
    img_left_b.src = "left_b.png";

    var img_right_b = new Image();
    img_right_b.src = "right_b.png";

    //****************************************************//
    //**********  Defining the Player object *************//
    //****************************************************//
    var player = {
        color: "#ff5050",
        //randomly place the player into the game field, within boundaries
        x: Math.floor((Math.random() * 991) + 1),
        y: Math.floor((Math.random() * 511) + 122),
        width: 32,
        height: 32,
        direction: 'S',
        isMoving: false,
        //Frame system: alternate along the following system:
        //  down:1      down_b:5
        //  up:2        up_b:6
        //  left:3      left_b:7
        //  right:4     right_b:8
        //  0 for stillness, or non-moving
        frame: 0,
        draw: function() {
                if (this.isMoving) {
                if (this.direction == 'S') {

                    if (this.frame == 1) {
                        ctx.drawImage(img_down, this.x, this.y, this.width, this.height);

                    }
                    else if (this.frame == 5) {
                        ctx.drawImage(img_down_b, this.x, this.y, this.width, this.height);

                    }
                }
                else if (this.direction == 'N') {

                        if (this.frame == 2) {
                        ctx.drawImage(img_up, this.x, this.y, this.width, this.height);

                    }
                    else if (this.frame == 6) {
                        ctx.drawImage(img_up_b, this.x, this.y, this.width, this.height);

                    }
                }
                else if (this.direction == 'E') {

                        if (this.frame == 4) {
                        ctx.drawImage(img_right, this.x, this.y, this.width, this.height);

                    }
                    else if (this.frame == 8) {
                        ctx.drawImage(img_right_b, this.x, this.y, this.width, this.height);

                    }
                }
                else if (this.direction == 'W') {

                        if (this.frame == 3) {
                        ctx.drawImage(img_left, this.x, this.y, this.width, this.height);

                    }
                    else if (this.frame == 7) {
                        ctx.drawImage(img_left_b, this.x, this.y, this.width, this.height);

                    }
                }
            } else {
                ctx.drawImage(img, this.x, this.y, this.width, this.height);
            }
        },

        move: function() {
            player.draw();
                if (!keydown.left && !keydown.right && !keydown.up && !keydown.down) {
                    player.color = "#ff5050";
                this.isMoving = false;
            } else {
                this.isMoving = true;
            }

            //simple moves: horizontal, vertical
            if (keydown.left) {
                if (player.frame != 3) player.frame = 3;
                else player.frame = 7;
                player.direction = 'W';
                player.x -= 3;
                player.color = "red";
            }

            if (keydown.right) {
                if (player.frame != 4) player.frame = 4;
                else player.frame = 8;
                player.direction = 'E';
                player.x += 3;
                player.color = "blue";
            }

            if (keydown.up) {
                if (player.frame != 2) player.frame = 2;
                else player.frame = 6;
                player.direction = 'N';
                player.y -= 3;
                player.color = "green";
            }

            if (keydown.down) {
                if (player.frame != 1) player.frame = 1;
                else player.frame = 5;
                player.direction = 'S';
                player.y += 3;
                player.color = "yellow";
            }

            //dual keypress up and down, left and right
            if (keydown.down && keydown.up) {
                player.color = "#ff5050";
            }

            if (keydown.left && keydown.right) {
                player.color = "#ff5050";
            }

            //combined moves: diagonal
            //up and left
            if (keydown.left && keydown.up && !keydown.right && !keydown.down) {
                player.color = "grey";
            }
            //up and right
            if (keydown.right && keydown.up && !keydown.left && !keydown.down) {
                player.color = "black";
            }
            //down and left
            if (keydown.left && keydown.down && !keydown.right && !keydown.up) {
                player.color = "white";
            }

            //down and right
            if (keydown.right && keydown.down && !keydown.left && !keydown.up) {
                player.color = "brown";
            }

            //quick-fix for combined keypressse down, left and right
            if (keydown.right && keydown.left && keydown.down) {
                    player.color = "yellow";
            }

            //checking player boundaries *~*~* DELETE IF NOT BEING USED
                    if (player.x <= 0) { player.x = 1; }
                    if (player.x >= w-player.width) { player.x = 991; }
                    if (player.y >= h-player.height) { player.y = 511-player.height; }
                    if (player.y <= 121) { player.y = 122; }
        }
    }

    //Snip...

    //****************************************************//
    //**********  The global Draw Method *****************//
    //****************************************************//
    function draw() {
                ctx.clearRect(0, 0, w, h);
        player.move();
        ctx.fillStyle = "#000";
        ctx.font = "20px Arial";
        ctx.fillText("Score: ", 10, 50);
        ctx.fillText(score.toString(), 75, 50);

        ctx.fillText("Moving:", 115, 50);
        ctx.fillText(player.isMoving.toString(), 185, 50);

        ctx.fillText("Frame:", 255, 50);
        ctx.fillText(player.frame.toString(), 335, 50);
        npcs.forEach(function(Npc) {
            Npc.draw();
        });
    };

```

})

# Answer
> 0 votes
From your code :

```
       if (keydown.right) {
            if (player.frame != 4) player.frame = 4;
            else player.frame = 8;
            player.direction = 'E';
            player.x += 3;
            player.color = "blue";
        }

```

I can tell that the images are switched every update as long as the key is down. There are all kinds of ways you could change the speed at which this happens, based on current speed of the character, or just by giving it a hard limit.

An easy way of doing this with a hard limit is as follows :

```
 //... SNIP ...

 //we need to count updates so we can switch frames every x updates
 currentFrame : 0,

 move: function() {
        player.draw();
        //update current frame counter
        currentFrame ++;
 //... SNIP ...

       //this example is only the 'move right'portion. you'll need to do this for the other directions / animations yourself.
        if (keydown.right)
        {
            //make sure we get the initial frame right if we just started moving right
            if (player.frame != 4 && player.frame != 8)
            {
               player.frame = 4;
            }
            //if the 'switch frames' timeout occurs (now hardcoded to ten updates)
            else if(currentFrame > 10)
            {
               //swap the current frame with the alternate frame
               if (player.frame != 4) player.frame = 4;
               else player.frame = 8;

               currentFrame = 0;
            }
            player.direction = 'E';
            player.x += 3;
            player.color = "blue";
        }

```

---
Tags: javascript, animation, html5, html-canvas
---


# Question
Title: Simulating aircraft movement with DirectX 9
How would I go about simulating a planes movement in DirectX 9 using transforms (i.e. matrices).

For example flying around an open space. When it moves it faces the direction it is going and stimulates flight semi-realistically.

# Answer
When using a R/H Cartesian coordinate system with the Y axis as vertical and row major matrix transforms (common for DX9), and you set your model in your world such that when rendered using an Identity matrix, the nose of the aircraft will be pointing down the -Z axis:

then the negate of the **third row of the transform matrix** can be used as a direction vector which when multiplied by a speed variable can be used as a velocity vector.

So as you rotate your matrix as the aircraft is turning, that 3rd row will always be reset to the new direction the tail of the aircraft is pointing (which is the negate of the direction the nose is pointing).

```
//rotate matrix using DX math to simulate turning
Vector3 direction = new Vector3(matrix.m31, matrix.m32, matrix.m33);//or however the data is presentable
Vector3 velocity = -direction * speedPerSecond * timeSinceLastFrame;

// translate matrix by velocity using DX math

```

This does not account for aerodynamic affect on the aircraft but will give a semi-realistic approximation of flight.
> 1 votes

---
Tags: mathematics, directx9, directxmath
---


title: Cocos Code IDE unable to find python

text:
# Question
Title: Cocos Code IDE unable to find python
I am trying to create a new `JavaScript` project on Cocos Code IDE but every time it immediately give me the error message:

> Unable to find python. Please, click the setting button to set the python path, then python 3.0 or later is not supported.

I click the button and I set the path to `C:\Python27` which is the folder of my python installation, and I try again but I get exactly the same error. The version of my python installation is **2.7.8**. I am using **Windows8.1**.

**EDIT:** It occurred to me that there is also another error message:

> ```
> the python's version must be greater than or equal to 2.7.5 and less than 3.0
>
> ```

But I cannot understand why it does not accept my version(**2.7.8**).

# Answer
> 0 votes
It seemed that the problem was fixed by using the **32-bit** version of python instead of the **64-bit**.

---
Tags: javascript, cocos2d, windows-8, cocos2d-x-js
---


# Question
Title: Do I still owe Epic royalties if I am not enrolled in the Unreal Engine subscription?
I have just started using Unreal Engine 4 and I have had a very good experience, though I have left the subscription now.

I've made an Android game with it and I am planning to release it, but I have some doubts about the license. Suppose I post my game on my own website for, say, $%, will I still have to give 5% of my income to Epic? How will they come to know that the game is made in Unreal Engine?

I am very confused in taking this step and I'm not really understanding what they mean by "5% gross revenue."

# Answer
I am not a lawyer, and you should seek out an actual lawyer for a proper legal consultation.

That said, the terms of the license seem pretty clear. You may cancel your subscription, at which point you are not entitled to future updates of the engine, but you can still use the version you have:

> After cancellation of your Subscription by either you or Epic, you will not be entitled to access or use future Versions of the Engine Code or Assets that Epic makes available under the License. However, cancellation of your Subscription will not affect your rights under the License with respect to any Licensed Technology you have already downloaded under the License.

However, your use of the existing version is still bound by the terms of the license, which further states that:

> You agree to pay Epic a royalty equal to 5% of all worldwide gross revenue actually attributable to each Product, regardless of whether such revenue is received by you or any other person or legal entity...

Thus, you still need to pay Epic the royalties you agreed upon the release of your game regardless of whether or not you are still paying for the subscription. This applies for all forms of distribution, including self-hosting the game and selling it from your website. Failure to pay Epic on time will result in late fees being incurred, and possibly eventual legal action.

The license spells out the particulars of the royalty arrangement, including when you have to pay them and when you don't. "Gross revenue" is *not* your profit, it is the total amount of money your product generates before subtracting out other third-party cuts, refunds you may need to issue, et cetera. The license even gives an example:

> The royalty is based on gross revenue from end users, regardless of whether you sell your Product to end users directly, self-publish via App Store, or work with a publisher. The following simplified example illustrates the application of the royalty to gross sales: if your Product earns $10 on the App Store, Apple may pay you $7 (having deducted 30% as a distribution fee), but your royalty to Epic would still be 5% of $10 (or $0.50).
> 26 votes

---
Tags: legal, licensing, unreal-4
---


# Question
Title: Implementing character movement using real physics
This is the first time I'm seriously developing a game so apologies if I'm missing the obvious.

In my 2D platformer I adopted Box2D since it seemed like a natural solution to model gravitational pull (player dropping off platforms) and jump arcs and in the process get collision detection for free. It was also a breeze to integrate with libgdx which I'm using as the main game engine.

One thing that I'm struggling with though is, ironically, the most simple thing: expressing player movement along the x axis using Box2D. Where previously it was as simple as translating position as a function of time, now I can only indirectly affect player position by applying a horizontal force to the rigid body representing the player, thus increasing its velocity.

I have multiple problems with this approach:

1. If I add friction to the platform fixtures, which seems natural, the user has to keep applying a force to the player for it to keep moving. However, my input system is based on the user pointing to a target platform or block upon which the character moves there, then stops.
2. If I remove the friction from any static objects the player steps on, then it's sufficient to apply force force once for the player to keep moving, but how do I tell it to stop at point x? I couldn't come up with a solution that does not feel convoluted or unnatural. I was thinking for instance to store the target position and then apply a balancing force in the opposite direction once the player reached it. Sounds complicated and prone to failure in corner cases though. I also thought about placing invisible geometry one unit ahead of the target position so that the player would collide with it and stop once reaching the position.

But seriously, both ideas sound complicated and kinda dumb. Am I missing the obvious?

I'm thinking already that maybe I should pursue a mixed approach of physics and direct controls, but I already tried that and Box2D does not like it if I set object positions manually, since this short circuits the computations behind the scenes?

# Answer
I was going to type up an answer, but then I found this article, which seems to be exactly what you need: http://www.iforce2d.net/b2dtut/constant-speed

I'll copy a few of the relevant bits. This assumes C++, but it's certainly applicable to any language.

> \[...\] in other situations you might want it to start and stop instantaneously. It is very tempting to use the SetLinearVelocity function to explicitly set the velocity for a body to accomplish this, and indeed it does get the job done, but this approach has its drawbacks. While it often looks fine on the screen, setting the velocity directly means the body is not correctly participating in the physics simulation.
>
> \[...\]
>
> **Using SetLinearVelocity**
>
> For many applications this may be good enough. Inside the Step() function, we will take whatever action is required each time step:
>
> ```
>     //inside Step()
>     b2Vec2 vel = body->GetLinearVelocity();
>     switch ( moveState )
>     {
>        case MOVE_LEFT:  vel.x = -5; break;
>        case MOVE_STOP:  vel.x =  0; break;
>        case MOVE_RIGHT: vel.x =  5; break;
>     }
>     body->SetLinearVelocity( vel );
>
> ```
>
> \[...\]
>
> **Using forces**
>
> Forces are more suited to the gradual acceleration, \[...\] but if we make the time span very short and the force very large, we can get the same effect as an impulse. First we need to do a little math...
>
> The relationship between force and acceleration is `f = ma` where `m` is the mass of the body we're moving, `a` is acceleration which is measured in "units per second per second", and `f` is the force we want to calculate. The acceleration could also be called "velocity per second", since velocity and "units per second" are the same thing. So we could write this as `f = mv/t` where `t` is the length of time the force will be applied.
>
> We can get `m` by using the body's GetMass() function. `v` will be the change in velocity we desire which is the difference between the maximum speed and the current speed. To get an instantaneous speed change effect, we would be applying the force for one time step or 1/60th of a second if using the default testbed framerate. Now we know everything except `f`, so we do something like this:
>
> ```
>     b2Vec2 vel = body->GetLinearVelocity();
>     float desiredVel = 0;
>     switch ( moveState )
>     {
>       case MOVE_LEFT:  desiredVel = -5; break;
>       case MOVE_STOP:  desiredVel =  0; break;
>       case MOVE_RIGHT: desiredVel =  5; break;
>     }
>     float velChange = desiredVel - vel.x;
>     float force = body->GetMass() * velChange / (1/60.0); // f = mv/t
>     body->ApplyForce( b2Vec2(force,0), body->GetWorldCenter() );
>
> ```
>
> This should give you the same behaviour as the SetLinearVelocity did, while still remaining a realistic physics scenario.
>
> **Using impulses**
>
> Astute readers will notice that the code immediately above is basically simulating an impulse. However since impulses already take into account the length of the simulation timestep, we can just take the time part out and get the same effect with ApplyLinearImpulse:
>
> ```
>     b2Vec2 vel = body->GetLinearVelocity();
>     float desiredVel = 0;
>     switch ( moveState )
>     {
>       case MOVE_LEFT:  desiredVel = -5; break;
>       case MOVE_STOP:  desiredVel =  0; break;
>       case MOVE_RIGHT: desiredVel =  5; break;
>     }
>     float velChange = desiredVel - vel.x;
>     float impulse = body->GetMass() * velChange; // disregard time factor
>     body->ApplyLinearImpulse( b2Vec2(impulse,0), body->GetWorldCenter() ); // because ApplyLinearImpulse knows the exact time factor
>
> ```
> 5 votes

---
Tags: movement, physics
---


title: Random Object in Array

text:
# Question
Title: Random Object in Array
I am using Unity. I have created eight different types of objects, stored in an array, and I am displaying them on the scene in a grid pattern with random order.

The first four objects in the array are red. The player needs to destroy all four red objects to go to the next level.

The code I've writted so far uses the `Random.Range` method, which chooses objects completely randomly. Sometimes it generates a grid that doesn't contain four red objects, so my player can't destroy them and proceed to the next level.

How do I randomly generate this grid so that it is guaranteed to have exactly four red objects?

Here is my code.

```
public int gridWidth = 0;
public int gridHeight = 0;
public GameObject[] facePrefab = new GameObject[8];

void Awake()
{
    gridHeight = Random.Range (3, 5);
    CreateGrid(gridWidth,gridHeight);
}
void CreateGrid(int numX, int numY)
{
    for (int x = 0; x < gridHeight; x++) {
        for (int y = 0; y < gridWidth; y++) {
            GameObject go = Instantiate (facePrefab[Random.Range(0,facePrefab.Length)]) as GameObject;
        }
    }
}

```

# Answer
As Savlon suggested in comments, **create the red objects first.**

You probably want to split your array into red prefabs and non-red prefabs. Your CreateGrid function will look like the following pseudocode:

1. Repeat four times: place a random red object at a random point on the grid.
2. Repeat for each grid square: if the grid square is empty (does not contain a red object), place a random non-red object.

This will guarantee that you have exactly four red objects in the grid, placed randomly, and that the rest of the grid is filled with a random assortment of non-red objects.
> 1 votes

---
Tags: unity, c#, procedural-generation
---


title: How can I support remappable controls?

text:
# Question
Title: How can I support remappable controls?
I am trying to allow players of my game to remap the controls (eventually from the menu). Currently, some of the buttons have been defined, but they can't be changed. They are hard-coded. For example, this is how I handle key events now:

```
    switch(e.getKeyCode())
    {
        case KeyEvent.VK_A:
            ...
            break;
        case KeyEvent.VK_D:
            ...
            break;
        ...et cetera...
    }
}

```

How can I build a system that allows the actual keys for various actions to be remapped by the user?

# Answer
In your keyPressed and keyReleased you can use a `Map<Integer, GameInput>` to map the `KeyEvent.VK_*` to `GameInput`

Make a new enum with the actions you want to be controllable

```
enum GameInput{
    FORWARD, LEFT, RIGHT, BACK,PAUZE,...
}

```

And in Controller you have a `Map<Integer, GameInput>` that you use:

```
public void keyPressed(KeyEvent e)
{
    game.setKeyDown(keyMap.get(e.getKeyCode()));
}

public void keyReleased(KeyEvent e)
{
    game.setKeyUp(keyMap.get(e.getKeyCode()));
}

```

Then reassigning the keys is a simple matter of refilling the `keyMap`.
> 6 votes

# Answer
# A summary

Instead of mapping the input direcly to the action (and using enums will keep doing that because you would still have to map the key to the enums), you should make the input consume a method it holds. If it was an X-Box, for example, the X button can perfom an action defined by the player

Use the inferface above to create something like bellow from Game Design Patterns, about Command, and read this book by the way ;)

# The Answer

I don't know java, but it seems to me that the Command pattern would help you. It is a behavirol pattern by the Gang of Four wich encapsulates your information to be executed, in your case this information is user input.

I'm copying/pasting wikipedia here

```
import java.util.List;
import java.util.ArrayList;

/* The Command interface */
public interface Command {
   void execute();
}

/* The Invoker class */
public class Switch {
   private List<Command> history = new ArrayList<Command>();

   public void storeAndExecute(Command cmd) {
      this.history.add(cmd); // optional
      cmd.execute();
   }
}

/* The Receiver class */
public class Light {

   public void turnOn() {
      System.out.println("The light is on");
   }

   public void turnOff() {
      System.out.println("The light is off");
   }
}

/* The Command for turning on the light - ConcreteCommand #1 */
public class FlipUpCommand implements Command {
   private Light theLight;

   public FlipUpCommand(Light light) {
      this.theLight = light;
   }

   public void execute(){
      theLight.turnOn();
   }
}

/* The Command for turning off the light - ConcreteCommand #2 */
public class FlipDownCommand implements Command {
   private Light theLight;

   public FlipDownCommand(Light light) {
      this.theLight = light;
   }

   public void execute() {
      theLight.turnOff();
   }
}

/* The test class or client */
public class PressSwitch {
   public static void main(String[] args){
      Light lamp = new Light();
      Command switchUp = new FlipUpCommand(lamp);
      Command switchDown = new FlipDownCommand(lamp);

      Switch mySwitch = new Switch();

      switch(args[0]) {
         case "ON":
            mySwitch.storeAndExecute(switchUp);
         break;
         case "OFF":
            mySwitch.storeAndExecute(switchDown);
         break;
         default:
            System.out.println("Argument \"ON\" or \"OFF\" is required.");
       }
   }
}

```

## Observation on Java

I was told that Java threats enums as classes so you could, in that language, keep using enums and combine it with the command pattern by passing references to the enum, I think ;)
> 4 votes

---
Tags: java, keyboard
---


# Question
Title: Missing texture coordinates for channel 0 Fbx and XNA 4.0
I'm getting this error while trying to load a model in XNA 4.0 : Error 2 The mesh "transform1", using SkinnedEffect, contains geometry that is missing texture coordinates for channel 0. The model was dxf format then I upload it to maya then I added some skeleton and some texture (viewed it on the UV) but I still get this error.

this is the load function.

```
    protected override void LoadContent()
    {
        // Load the model.
        currentModel = Content.Load<Model>("myModel");

        // Look up our custom skinning information.
        SkinningData skinningData = currentModel.Tag as SkinningData;

        if (skinningData == null)
            throw new InvalidOperationException
                ("This model does not contain a SkinningData tag.");

        // Create an animation player, and start decoding an animation clip.
        animationPlayer = new AnimationPlayer(skinningData);

        AnimationClip clip = skinningData.AnimationClips["Take 001"];

        animationPlayer.StartClip(clip);
    }

```

this is the draw function :

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice device = graphics.GraphicsDevice;

        device.Clear(Color.CornflowerBlue);

        Matrix[] bones = animationPlayer.GetSkinTransforms();

        // Compute camera matrices.
        Matrix view = Matrix.CreateTranslation(0, -40, 0) * // x, y, z
                      Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) * //rotate y
                      Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) * //rotate x
                      Matrix.CreateLookAt(new Vector3(0, 0, -cameraDistance),
                                          new Vector3(0, 0, 0), Vector3.Up);

        Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                                device.Viewport.AspectRatio,
                                                                1,
                                                                10000);

        // Render the skinned mesh.
        foreach (ModelMesh mesh in currentModel.Meshes)
        {
            foreach (SkinnedEffect effect in mesh.Effects)
            {
                effect.SetBoneTransforms(bones);

                effect.View = view;
                effect.Projection = projection;

                effect.EnableDefaultLighting();

                effect.SpecularColor = new Vector3(0.25f);
                effect.SpecularPower = 16;

            }

            mesh.Draw();
        }

        base.Draw(gameTime);
    }

```

PS : 1-My knowledge with Maya & XNA is very limited cause I used to use OpenGL/C++ for some time.

2-Also I change my Content Processor to SkinnedModelProcessor not Model - XNA Framework. thanks in advance.

# Answer
The error is clear. One of your meshes/vertices is missing a texture coordinate, which is the expectation in this case. In Maya, apply a texture channel to `transform1` mesh even if you have no intentions of assigning any textures to it.

Also, why do you have a mesh called "transform"? Are you sure you didn't mistakenly misname a bone as mesh or vice versa?
> 1 votes

---
Tags: xna, textures, xna-4.0, models, maya
---


# Question
Title: Is there a reason to keep maps in memory?
I've noticed for a *long* time that games (mostly FPSes) do not unload the map when the user has finished with it (aka, disconnecting from servers, server changing maps).

The result of this is that the maps are ***kept in memory***, which can lead to *colossal* memory usage in the region of 5GB for a 2 hour session of CoD:Black Ops 2 or around 8GB for a session of the same time of Crysis Wars.

Games most notable for this behaviour (that I've noticed) are the Crysis series and Call of Duty: Black Ops 2.

I've noticed this for years, but now as I am 'upgrading' Crysis Wars (fixing bugs, adding features, and porting it to my new multiplayer network) I have been able to unload maps when the game is done with them. As a result after two hours of playing the memory usage has dropped from an average of 8GB to just 2GB (I jumped between servers a few times when testing this out).

Is keeping maps in memory when the game doesn't need them anymore a bug, or is it purposeful? This 'memory-leak' exists in other Crysis games and also the Call of Duty series (also on consoles, although I'm not certain of this), so it seems to be purposeful rather than a bug.

I've also had a look at what is actually kept around after disconnecting from a server, and it seems that *all* entities are left behind but the terrain and hightmaps are removed. A similar thing probably happens with CoD:BO2 where I've also observed this.

Obviously I wouldn't want to purge the map from memory if there was a reason behind it, but however I've noticed no adverse effects so far in Crysis Wars.

# Answer
Yes, there's a reason to do this.

The user might want to play the map again, and if so having all (or at least most of) the map already resident in memory means it doesn't needed to be loaded from disk again, thus reducing load times in that (often typical) case.

Purging something from memory is not free, either, as there may be references to loaded that data need to be cleaned up, and so on. At the very least the OS needs to be informed that the relevant pages are now unused, and must update its internal bookkeeping.

Nobody can speak to the specific reasons that specific games choose to keep certain kinds of data resident in memory except the developers who made those decisions. But there *are* optimizations to be had. Games generally assume they have the user's sole focus and will thus attempt to maximize utilization of the machine while running.
> 4 votes

---
Tags: maps, memory-efficiency, memory, cryengine
---


title: Triangle-Triangle Intersection Code

text:
# Question
Title: Triangle-Triangle Intersection Code
Does anyone have experience implementing this triangle-triangle intersection code that I found online? I don't understand it. I made a post on Stack Overflow about this and got the advice that:

> From the sample code it seems like what it mean by an edge is the vector from the originating vertex to the end vertex. In the case of a triangle with three vertices C1, C2, C3, the two \>input edges would be P1 = C2-C1, P2=C3-C1

I tried feeding it my triangles like that, but ended up with a pretty wildly inaccurate false positive:

```
Triangle* triangle1 = new Triangle(glm::vec3(-0.323523998f, 1.68264794f, -1.20740700f),
        glm::vec3(-0.478354007f, 1.68264794f, -1.15484905f),
        glm::vec3(-0.465537012f, 1.80764794f, -1.12390494f));
Triangle* triangle2 = new Triangle(glm::vec3(1.00000000f, -0.682647943f, -0.999998987f),
        glm::vec3(1.00000000f, -2.68264794f, -1.00000000f),
        glm::vec3(-1.00000000f, -0.682647943f, -1.00000000f));
collisionDetector.checkForCollision(triangle1, triangle2)

```

returned true, with the collisionDetector being a wrapper for this function and checkForCollision defined as:

```
bool TriangleTriangleCollision::checkForCollision(Triangle* triangle1, Triangle* triangle2)
{
    return checkForCollision(triangle1->_vertex0, triangle1->_vertex1, triangle1->_vertex2,
        triangle2->_vertex0, triangle2->_vertex1, triangle2->_vertex2);
}

bool TriangleTriangleCollision::checkForCollision(glm::vec3 t1vert0, glm::vec3 t1vert1,
    glm::vec3 t1vert2, glm::vec3 t2vert0, glm::vec3 t2vert1, glm::vec3 t2vert2)
{
    double C1[3], P1[3], P2[3], D1[3], Q1[3], Q2[3];

    glmVecToArray(t1vert0, C1);
    glmVecToArray(t1vert1 - t1vert0, P1);
    glmVecToArray(t1vert2 - t1vert0, P2);

    glmVecToArray(t2vert0, D1);
    glmVecToArray(t2vert1 - t2vert0, Q1);
    glmVecToArray(t2vert2 - t2vert0, Q1);

    return (tr_tri_intersect3D(C1, P1, P2, D1, Q1, Q2) > 0);
}

void TriangleTriangleCollision::glmVecToArray(const glm::vec3 vector, double v[3])
{
    v[0] = vector.x;
    v[1] = vector.y;
    v[2] = vector.z;
}

```

unless I am wrong, these two triangles are not at all near each other.

If not, does anyone have any reliable triangle-triangle intersection code? I'm on a time crunch working on a collision detection system for a school project and spent all my time implementing the code to weed out triangle-triangle collision detection so I'm going to have to use some code from someone else and just cite it in my program.

# Answer
> 4 votes
I took a look at a number of implementations that are all based off of this paper:

http://home.arcor.de/philippe.guigue/triangle\_triangle\_intersection.htm

Here is one that I extracted and ran with your numbers - it returns no collision. You can look at main() to see the invocation with your test numbers. I have not done any more analysis than that. Good luck.

From https://github.com/benardp/contours/blob/master/freestyle/view\_map/triangle\_triangle\_intersection.c

```
/*
 *  Triangle-Triangle Overlap Test Routines
 *  July, 2002
 *  Updated December 2003
 *
 *  This file contains C implementation of algorithms for
 *  performing two and three-dimensional triangle-triangle intersection test
 *  The algorithms and underlying theory are described in
 *
 * "Fast and Robust Triangle-Triangle Overlap Test
 *  Using Orientation Predicates"  P. Guigue - O. Devillers
 *
 *  Journal of Graphics Tools, 8(1), 2003
 *
 *  Several geometric predicates are defined.  Their parameters are all
 *  points.  Each point is an array of two or three real precision
 *  floating point numbers. The geometric predicates implemented in
 *  this file are:
 *
 *    int tri_tri_overlap_test_3d(p1,q1,r1,p2,q2,r2)
 *    int tri_tri_overlap_test_2d(p1,q1,r1,p2,q2,r2)
 *
 *    int tri_tri_intersection_test_3d(p1,q1,r1,p2,q2,r2,
 *                                     coplanar,source,target)
 *
 *       is a version that computes the segment of intersection when
 *       the triangles overlap (and are not coplanar)
 *
 *    each function returns 1 if the triangles (including their
 *    boundary) intersect, otherwise 0
 *
 *
 *  Other information are available from the Web page
 *  http:<i>//www.acm.org/jgt/papers/GuigueDevillers03/
 *
 */

// modified by Aaron to better detect coplanarity

typedef float real;

#define ZERO_TEST(x)  (x == 0)
//#define ZERO_TEST(x)  ((x) > -0.001 && (x) < .001)

#include "stdio.h"

/* function prototype */

int tri_tri_overlap_test_3d(real p1[3], real q1[3], real r1[3],
                            real p2[3], real q2[3], real r2[3]);

int coplanar_tri_tri3d(real  p1[3], real  q1[3], real  r1[3],
                       real  p2[3], real  q2[3], real  r2[3],
                       real  N1[3], real  N2[3]);

int tri_tri_overlap_test_2d(real p1[2], real q1[2], real r1[2],
                            real p2[2], real q2[2], real r2[2]);

int tri_tri_intersection_test_3d(real p1[3], real q1[3], real r1[3],
                                 real p2[3], real q2[3], real r2[3],
                                 int * coplanar,
                                 real source[3],real target[3]);

/* coplanar returns whether the triangles are coplanar
 *  source and target are the endpoints of the segment of
 *  intersection if it exists)
 */

/* some 3D macros */

#define CROSS(dest,v1,v2)                       \
dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \
dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \
dest[2]=v1[0]*v2[1]-v1[1]*v2[0];

#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])

#define SUB(dest,v1,v2) dest[0]=v1[0]-v2[0]; \
dest[1]=v1[1]-v2[1]; \
dest[2]=v1[2]-v2[2];

#define SCALAR(dest,alpha,v) dest[0] = alpha * v[0]; \
dest[1] = alpha * v[1]; \
dest[2] = alpha * v[2];

#define CHECK_MIN_MAX(p1,q1,r1,p2,q2,r2) {\
SUB(v1,p2,q1)\
SUB(v2,p1,q1)\
CROSS(N1,v1,v2)\
SUB(v1,q2,q1)\
if (DOT(v1,N1) > 0.0f) return 0;\
SUB(v1,p2,p1)\
SUB(v2,r1,p1)\
CROSS(N1,v1,v2)\
SUB(v1,r2,p1) \
if (DOT(v1,N1) > 0.0f) return 0;\
else return 1; }

/* Permutation in a canonical form of T2's vertices */

#define TRI_TRI_3D(p1,q1,r1,p2,q2,r2,dp2,dq2,dr2) { \
if (dp2 > 0.0f) { \
if (dq2 > 0.0f) CHECK_MIN_MAX(p1,r1,q1,r2,p2,q2) \
else if (dr2 > 0.0f) CHECK_MIN_MAX(p1,r1,q1,q2,r2,p2)\
else CHECK_MIN_MAX(p1,q1,r1,p2,q2,r2) }\
else if (dp2 < 0.0f) { \
if (dq2 < 0.0f) CHECK_MIN_MAX(p1,q1,r1,r2,p2,q2)\
else if (dr2 < 0.0f) CHECK_MIN_MAX(p1,q1,r1,q2,r2,p2)\
else CHECK_MIN_MAX(p1,r1,q1,p2,q2,r2)\
} else { \
if (dq2 < 0.0f) { \
if (dr2 >= 0.0f)  CHECK_MIN_MAX(p1,r1,q1,q2,r2,p2)\
else CHECK_MIN_MAX(p1,q1,r1,p2,q2,r2)\
} \
else if (dq2 > 0.0f) { \
if (dr2 > 0.0f) CHECK_MIN_MAX(p1,r1,q1,p2,q2,r2)\
else  CHECK_MIN_MAX(p1,q1,r1,q2,r2,p2)\
} \
else  { \
if (dr2 > 0.0f) CHECK_MIN_MAX(p1,q1,r1,r2,p2,q2)\
else if (dr2 < 0.0f) CHECK_MIN_MAX(p1,r1,q1,r2,p2,q2)\
else return coplanar_tri_tri3d(p1,q1,r1,p2,q2,r2,N1,N2);\
}}}

/*
 *
 *  Three-dimensional Triangle-Triangle Overlap Test
 *
 */

int tri_tri_overlap_test_3d(real p1[3], real q1[3], real r1[3],

                            real p2[3], real q2[3], real r2[3])
{
    real dp1, dq1, dr1, dp2, dq2, dr2;
    real v1[3], v2[3];
    real N1[3], N2[3];

    /* Compute distance signs  of p1, q1 and r1 to the plane of
     triangle(p2,q2,r2) */

    SUB(v1,p2,r2)
    SUB(v2,q2,r2)
    CROSS(N2,v1,v2)

    SUB(v1,p1,r2)
    dp1 = DOT(v1,N2);
    SUB(v1,q1,r2)
    dq1 = DOT(v1,N2);
    SUB(v1,r1,r2)
    dr1 = DOT(v1,N2);

    if (((dp1 * dq1) > 0.0f) && ((dp1 * dr1) > 0.0f))  return 0;

    /* Compute distance signs  of p2, q2 and r2 to the plane of
     triangle(p1,q1,r1) */

    SUB(v1,q1,p1)
    SUB(v2,r1,p1)
    CROSS(N1,v1,v2)

    SUB(v1,p2,r1)
    dp2 = DOT(v1,N1);
    SUB(v1,q2,r1)
    dq2 = DOT(v1,N1);
    SUB(v1,r2,r1)
    dr2 = DOT(v1,N1);

    if (((dp2 * dq2) > 0.0f) && ((dp2 * dr2) > 0.0f)) return 0;

    /* Permutation in a canonical form of T1's vertices */

    if (dp1 > 0.0f) {
        if (dq1 > 0.0f) TRI_TRI_3D(r1,p1,q1,p2,r2,q2,dp2,dr2,dq2)
            else if (dr1 > 0.0f) TRI_TRI_3D(q1,r1,p1,p2,r2,q2,dp2,dr2,dq2)
                else TRI_TRI_3D(p1,q1,r1,p2,q2,r2,dp2,dq2,dr2)
                    } else if (dp1 < 0.0f) {
                        if (dq1 < 0.0f) TRI_TRI_3D(r1,p1,q1,p2,q2,r2,dp2,dq2,dr2)
                            else if (dr1 < 0.0f) TRI_TRI_3D(q1,r1,p1,p2,q2,r2,dp2,dq2,dr2)
                                else TRI_TRI_3D(p1,q1,r1,p2,r2,q2,dp2,dr2,dq2)
                                    } else {
                                        if (dq1 < 0.0f) {
                                            if (dr1 >= 0.0f) TRI_TRI_3D(q1,r1,p1,p2,r2,q2,dp2,dr2,dq2)
                                                else TRI_TRI_3D(p1,q1,r1,p2,q2,r2,dp2,dq2,dr2)
                                                    }
                                        else if (dq1 > 0.0f) {
                                            if (dr1 > 0.0f) TRI_TRI_3D(p1,q1,r1,p2,r2,q2,dp2,dr2,dq2)
                                                else TRI_TRI_3D(q1,r1,p1,p2,q2,r2,dp2,dq2,dr2)
                                                    }
                                        else  {
                                            if (dr1 > 0.0f) TRI_TRI_3D(r1,p1,q1,p2,q2,r2,dp2,dq2,dr2)
                                                else if (dr1 < 0.0f) TRI_TRI_3D(r1,p1,q1,p2,r2,q2,dp2,dr2,dq2)
                                                    else return coplanar_tri_tri3d(p1,q1,r1,p2,q2,r2,N1,N2);
                                        }
                                    }
};

int coplanar_tri_tri3d(real p1[3], real q1[3], real r1[3],
                       real p2[3], real q2[3], real r2[3],
                       real normal_1[3], real normal_2[3]){

    real P1[2],Q1[2],R1[2];
    real P2[2],Q2[2],R2[2];

    real n_x, n_y, n_z;

    n_x = ((normal_1[0]<0)?-normal_1[0]:normal_1[0]);
    n_y = ((normal_1[1]<0)?-normal_1[1]:normal_1[1]);
    n_z = ((normal_1[2]<0)?-normal_1[2]:normal_1[2]);

    /* Projection of the triangles in 3D onto 2D such that the area of
     the projection is maximized. */

    if (( n_x > n_z ) && ( n_x >= n_y )) {
        // Project onto plane YZ

        P1[0] = q1[2]; P1[1] = q1[1];
        Q1[0] = p1[2]; Q1[1] = p1[1];
        R1[0] = r1[2]; R1[1] = r1[1];

        P2[0] = q2[2]; P2[1] = q2[1];
        Q2[0] = p2[2]; Q2[1] = p2[1];
        R2[0] = r2[2]; R2[1] = r2[1];

    } else if (( n_y > n_z ) && ( n_y >= n_x )) {
        // Project onto plane XZ

        P1[0] = q1[0]; P1[1] = q1[2];
        Q1[0] = p1[0]; Q1[1] = p1[2];
        R1[0] = r1[0]; R1[1] = r1[2];

        P2[0] = q2[0]; P2[1] = q2[2];
        Q2[0] = p2[0]; Q2[1] = p2[2];
        R2[0] = r2[0]; R2[1] = r2[2];

    } else {
        // Project onto plane XY

        P1[0] = p1[0]; P1[1] = p1[1];
        Q1[0] = q1[0]; Q1[1] = q1[1];
        R1[0] = r1[0]; R1[1] = r1[1];

        P2[0] = p2[0]; P2[1] = p2[1];
        Q2[0] = q2[0]; Q2[1] = q2[1];
        R2[0] = r2[0]; R2[1] = r2[1];
    }

    return tri_tri_overlap_test_2d(P1,Q1,R1,P2,Q2,R2);

};

/*
 *
 *  Three-dimensional Triangle-Triangle Intersection
 *
 */

/*
 This macro is called when the triangles surely intersect
 It constructs the segment of intersection of the two triangles
 if they are not coplanar.
 */

#define CONSTRUCT_INTERSECTION(p1,q1,r1,p2,q2,r2) { \
SUB(v1,q1,p1) \
SUB(v2,r2,p1) \
CROSS(N,v1,v2) \
SUB(v,p2,p1) \
if (DOT(v,N) > 0.0f) {\
SUB(v1,r1,p1) \
CROSS(N,v1,v2) \
if (DOT(v,N) <= 0.0f) { \
SUB(v2,q2,p1) \
CROSS(N,v1,v2) \
if (DOT(v,N) > 0.0f) { \
SUB(v1,p1,p2) \
SUB(v2,p1,r1) \
alpha = DOT(v1,N2) / DOT(v2,N2); \
SCALAR(v1,alpha,v2) \
SUB(source,p1,v1) \
SUB(v1,p2,p1) \
SUB(v2,p2,r2) \
alpha = DOT(v1,N1) / DOT(v2,N1); \
SCALAR(v1,alpha,v2) \
SUB(target,p2,v1) \
return 1; \
} else { \
SUB(v1,p2,p1) \
SUB(v2,p2,q2) \
alpha = DOT(v1,N1) / DOT(v2,N1); \
SCALAR(v1,alpha,v2) \
SUB(source,p2,v1) \
SUB(v1,p2,p1) \
SUB(v2,p2,r2) \
alpha = DOT(v1,N1) / DOT(v2,N1); \
SCALAR(v1,alpha,v2) \
SUB(target,p2,v1) \
return 1; \
} \
} else { \
return 0; \
} \
} else { \
SUB(v2,q2,p1) \
CROSS(N,v1,v2) \
if (DOT(v,N) < 0.0f) { \
return 0; \
} else { \
SUB(v1,r1,p1) \
CROSS(N,v1,v2) \
if (DOT(v,N) >= 0.0f) { \
SUB(v1,p1,p2) \
SUB(v2,p1,r1) \
alpha = DOT(v1,N2) / DOT(v2,N2); \
SCALAR(v1,alpha,v2) \
SUB(source,p1,v1) \
SUB(v1,p1,p2) \
SUB(v2,p1,q1) \
alpha = DOT(v1,N2) / DOT(v2,N2); \
SCALAR(v1,alpha,v2) \
SUB(target,p1,v1) \
return 1; \
} else { \
SUB(v1,p2,p1) \
SUB(v2,p2,q2) \
alpha = DOT(v1,N1) / DOT(v2,N1); \
SCALAR(v1,alpha,v2) \
SUB(source,p2,v1) \
SUB(v1,p1,p2) \
SUB(v2,p1,q1) \
alpha = DOT(v1,N2) / DOT(v2,N2); \
SCALAR(v1,alpha,v2) \
SUB(target,p1,v1) \
return 1; \
}}}}

#define TRI_TRI_INTER_3D(p1,q1,r1,p2,q2,r2,dp2,dq2,dr2) { \
if (dp2 > 0.0f) { \
if (dq2 > 0.0f) CONSTRUCT_INTERSECTION(p1,r1,q1,r2,p2,q2) \
else if (dr2 > 0.0f) CONSTRUCT_INTERSECTION(p1,r1,q1,q2,r2,p2)\
else CONSTRUCT_INTERSECTION(p1,q1,r1,p2,q2,r2) }\
else if (dp2 < 0.0f) { \
if (dq2 < 0.0f) CONSTRUCT_INTERSECTION(p1,q1,r1,r2,p2,q2)\
else if (dr2 < 0.0f) CONSTRUCT_INTERSECTION(p1,q1,r1,q2,r2,p2)\
else CONSTRUCT_INTERSECTION(p1,r1,q1,p2,q2,r2)\
} else { \
if (dq2 < 0.0f) { \
if (dr2 >= 0.0f)  CONSTRUCT_INTERSECTION(p1,r1,q1,q2,r2,p2)\
else CONSTRUCT_INTERSECTION(p1,q1,r1,p2,q2,r2)\
} \
else if (dq2 > 0.0f) { \
if (dr2 > 0.0f) CONSTRUCT_INTERSECTION(p1,r1,q1,p2,q2,r2)\
else  CONSTRUCT_INTERSECTION(p1,q1,r1,q2,r2,p2)\
} \
else  { \
if (dr2 > 0.0f) CONSTRUCT_INTERSECTION(p1,q1,r1,r2,p2,q2)\
else if (dr2 < 0.0f) CONSTRUCT_INTERSECTION(p1,r1,q1,r2,p2,q2)\
else { \
*coplanar = 1; \
return coplanar_tri_tri3d(p1,q1,r1,p2,q2,r2,N1,N2);\
} \
}} }

/*
 The following version computes the segment of intersection of the
 two triangles if it exists.
 coplanar returns whether the triangles are coplanar
 source and target are the endpoints of the line segment of intersection
 */

int tri_tri_intersection_test_3d(real p1[3], real q1[3], real r1[3],
                                 real p2[3], real q2[3], real r2[3],
                                 int * coplanar,
                                 real source[3], real target[3] )

{
    real dp1, dq1, dr1, dp2, dq2, dr2;
    real v1[3], v2[3], v[3];
    real N1[3], N2[3], N[3];
    real alpha;

    // Compute distance signs  of p1, q1 and r1
    // to the plane of triangle(p2,q2,r2)

    SUB(v1,p2,r2)
    SUB(v2,q2,r2)
    CROSS(N2,v1,v2)

    SUB(v1,p1,r2)
    dp1 = DOT(v1,N2);
    SUB(v1,q1,r2)
    dq1 = DOT(v1,N2);
    SUB(v1,r1,r2)
    dr1 = DOT(v1,N2);

    if (((dp1 * dq1) > 0.0f) && ((dp1 * dr1) > 0.0f))  return 0;

    // Compute distance signs  of p2, q2 and r2
    // to the plane of triangle(p1,q1,r1)

    SUB(v1,q1,p1)
    SUB(v2,r1,p1)
    CROSS(N1,v1,v2)

    SUB(v1,p2,r1)
    dp2 = DOT(v1,N1);
    SUB(v1,q2,r1)
    dq2 = DOT(v1,N1);
    SUB(v1,r2,r1)
    dr2 = DOT(v1,N1);

    if (((dp2 * dq2) > 0.0f) && ((dp2 * dr2) > 0.0f)) return 0;

    // Permutation in a canonical form of T1's vertices

    //  printf("d1 = [%f %f %f], d2 = [%f %f %f]\n", dp1, dq1, dr1, dp2, dq2, dr2);
    /*
     // added by Aaron
     if (ZERO_TEST(dp1) || ZERO_TEST(dq1) ||ZERO_TEST(dr1) ||ZERO_TEST(dp2) ||ZERO_TEST(dq2) ||ZERO_TEST(dr2))
     {
     coplanar = 1;
     return 0;
     }
     */

    if (dp1 > 0.0f) {
        if (dq1 > 0.0f) TRI_TRI_INTER_3D(r1,p1,q1,p2,r2,q2,dp2,dr2,dq2)
            else if (dr1 > 0.0f) TRI_TRI_INTER_3D(q1,r1,p1,p2,r2,q2,dp2,dr2,dq2)

                else TRI_TRI_INTER_3D(p1,q1,r1,p2,q2,r2,dp2,dq2,dr2)
                    } else if (dp1 < 0.0f) {
                        if (dq1 < 0.0f) TRI_TRI_INTER_3D(r1,p1,q1,p2,q2,r2,dp2,dq2,dr2)
                            else if (dr1 < 0.0f) TRI_TRI_INTER_3D(q1,r1,p1,p2,q2,r2,dp2,dq2,dr2)
                                else TRI_TRI_INTER_3D(p1,q1,r1,p2,r2,q2,dp2,dr2,dq2)
                                    } else {
                                        if (dq1 < 0.0f) {
                                            if (dr1 >= 0.0f) TRI_TRI_INTER_3D(q1,r1,p1,p2,r2,q2,dp2,dr2,dq2)
                                                else TRI_TRI_INTER_3D(p1,q1,r1,p2,q2,r2,dp2,dq2,dr2)
                                                    }
                                        else if (dq1 > 0.0f) {
                                            if (dr1 > 0.0f) TRI_TRI_INTER_3D(p1,q1,r1,p2,r2,q2,dp2,dr2,dq2)
                                                else TRI_TRI_INTER_3D(q1,r1,p1,p2,q2,r2,dp2,dq2,dr2)
                                                    }
                                        else  {
                                            if (dr1 > 0.0f) TRI_TRI_INTER_3D(r1,p1,q1,p2,q2,r2,dp2,dq2,dr2)
                                                else if (dr1 < 0.0f) TRI_TRI_INTER_3D(r1,p1,q1,p2,r2,q2,dp2,dr2,dq2)
                                                    else {
                                                        // triangles are co-planar

                                                        *coplanar = 1;
                                                        return coplanar_tri_tri3d(p1,q1,r1,p2,q2,r2,N1,N2);
                                                    }
                                        }
                                    }
};

/*
 *
 *  Two dimensional Triangle-Triangle Overlap Test
 *
 */

/* some 2D macros */

#define ORIENT_2D(a, b, c)  ((a[0]-c[0])*(b[1]-c[1])-(a[1]-c[1])*(b[0]-c[0]))

#define INTERSECTION_TEST_VERTEXA(P1, Q1, R1, P2, Q2, R2) {\
if (ORIENT_2D(R2,P2,Q1) >= 0.0f)\
if (ORIENT_2D(R2,Q2,Q1) <= 0.0f)\
if (ORIENT_2D(P1,P2,Q1) > 0.0f) {\
if (ORIENT_2D(P1,Q2,Q1) <= 0.0f) return 1; \
else return 0;} else {\
if (ORIENT_2D(P1,P2,R1) >= 0.0f)\
if (ORIENT_2D(Q1,R1,P2) >= 0.0f) return 1; \
else return 0;\
else return 0;}\
else \
if (ORIENT_2D(P1,Q2,Q1) <= 0.0f)\
if (ORIENT_2D(R2,Q2,R1) <= 0.0f)\
if (ORIENT_2D(Q1,R1,Q2) >= 0.0f) return 1; \
else return 0;\
else return 0;\
else return 0;\
else\
if (ORIENT_2D(R2,P2,R1) >= 0.0f) \
if (ORIENT_2D(Q1,R1,R2) >= 0.0f)\
if (ORIENT_2D(P1,P2,R1) >= 0.0f) return 1;\
else return 0;\
else \
if (ORIENT_2D(Q1,R1,Q2) >= 0.0f) {\
if (ORIENT_2D(R2,R1,Q2) >= 0.0f) return 1; \
else return 0; }\
else return 0; \
else  return 0; \
};

#define INTERSECTION_TEST_VERTEX(P1, Q1, R1, P2, Q2, R2) {\
  if (ORIENT_2D(R2,P2,Q1) >= 0.0f)\
    if (ORIENT_2D(R2,Q2,Q1) <= 0.0f)\
      if (ORIENT_2D(P1,P2,Q1) > 0.0f) {\
        if (ORIENT_2D(P1,Q2,Q1) <= 0.0f) return 1; \
        else return 0;} else {\
        if (ORIENT_2D(P1,P2,R1) >= 0.0f)\
          if (ORIENT_2D(Q1,R1,P2) >= 0.0f) return 1; \
          else return 0;\
        else return 0;}\
    else \
      if (ORIENT_2D(P1,Q2,Q1) <= 0.0f)\
        if (ORIENT_2D(R2,Q2,R1) <= 0.0f)\
          if (ORIENT_2D(Q1,R1,Q2) >= 0.0f) return 1; \
          else return 0;\
        else return 0;\
      else return 0;\
  else\
    if (ORIENT_2D(R2,P2,R1) >= 0.0f) \
      if (ORIENT_2D(Q1,R1,R2) >= 0.0f)\
        if (ORIENT_2D(P1,P2,R1) >= 0.0f) return 1;\
        else return 0;\
      else \
        if (ORIENT_2D(Q1,R1,Q2) >= 0.0f) {\
          if (ORIENT_2D(R2,R1,Q2) >= 0.0f) return 1; \
          else return 0; }\
        else return 0; \
    else  return 0; \
 };

#define INTERSECTION_TEST_EDGE(P1, Q1, R1, P2, Q2, R2) { \
if (ORIENT_2D(R2,P2,Q1) >= 0.0f) {\
if (ORIENT_2D(P1,P2,Q1) >= 0.0f) { \
if (ORIENT_2D(P1,Q1,R2) >= 0.0f) return 1; \
else return 0;} else { \
if (ORIENT_2D(Q1,R1,P2) >= 0.0f){ \
if (ORIENT_2D(R1,P1,P2) >= 0.0f) return 1; else return 0;} \
else return 0; } \
} else {\
if (ORIENT_2D(R2,P2,R1) >= 0.0f) {\
if (ORIENT_2D(P1,P2,R1) >= 0.0f) {\
if (ORIENT_2D(P1,R1,R2) >= 0.0f) return 1;  \
else {\
if (ORIENT_2D(Q1,R1,R2) >= 0.0f) return 1; else return 0;}}\
else  return 0; }\
else return 0; }}

int ccw_tri_tri_intersection_2d(real p1[2], real q1[2], real r1[2],
                                real p2[2], real q2[2], real r2[2]) {
    if ( ORIENT_2D(p2,q2,p1) >= 0.0f ) {
        if ( ORIENT_2D(q2,r2,p1) >= 0.0f ) {
            if ( ORIENT_2D(r2,p2,p1) >= 0.0f ) return 1;
            else INTERSECTION_TEST_EDGE(p1,q1,r1,p2,q2,r2)
                } else {
                    if ( ORIENT_2D(r2,p2,p1) >= 0.0f )
                        INTERSECTION_TEST_EDGE(p1,q1,r1,r2,p2,q2)
                        else INTERSECTION_TEST_VERTEX(p1,q1,r1,p2,q2,r2)}}
    else {
        if ( ORIENT_2D(q2,r2,p1) >= 0.0f ) {
            if ( ORIENT_2D(r2,p2,p1) >= 0.0f )
                INTERSECTION_TEST_EDGE(p1,q1,r1,q2,r2,p2)
                else  INTERSECTION_TEST_VERTEX(p1,q1,r1,q2,r2,p2)}
        else INTERSECTION_TEST_VERTEX(p1,q1,r1,r2,p2,q2)}
};

int tri_tri_overlap_test_2d(real p1[2], real q1[2], real r1[2],
                            real p2[2], real q2[2], real r2[2]) {
    if ( ORIENT_2D(p1,q1,r1) < 0.0f )
        if ( ORIENT_2D(p2,q2,r2) < 0.0f )
            return ccw_tri_tri_intersection_2d(p1,r1,q1,p2,r2,q2);
        else
            return ccw_tri_tri_intersection_2d(p1,r1,q1,p2,q2,r2);
        else
            if ( ORIENT_2D(p2,q2,r2) < 0.0f )
                return ccw_tri_tri_intersection_2d(p1,q1,r1,p2,r2,q2);
            else
                return ccw_tri_tri_intersection_2d(p1,q1,r1,p2,q2,r2);

};

int main()
{
    float p1[3] = { -0.323523998f, 1.68264794f, -1.20740700f };
    float p2[3] = { -0.478354007f, 1.68264794f, -1.15484905f };
    float p3[3] = { -0.465537012f, 1.80764794f, -1.12390494f };

    float q1[3] = { 1.00000000f, -0.682647943f, -0.999998987f };
    float q2[3] = { 1.00000000f, -2.68264794f, -1.00000000f };
    float q3[3] = { -1.00000000f, -0.682647943f, -1.00000000f };

    int i = tri_tri_overlap_test_3d( p1, p2, p3, q1, q2, q3 );
    printf( "Result = %d\n", i );
    return 0;
}

```

---
Tags: c++, collision-detection, intersection
---