# Question
Title: What does 'Discretizing Space' mean in the context of paper prototyping
I was browsing some lecture slides by Eric Anderson for his Cornell course CS 4154 (Analytics-driven Game Design). In a series of slides he mentions discretizing space as a way of paper prototyping action games. As an example he illustrates with a screen shot of Super Mario with a grid overlay (shown below). Unfortunately the slides do not expound on *how* this technique is used.

How is discretizing space used to prototype platform games or action games generally?

# Answer
> 2 votes
Discretization in general means to split a while into discrete parts. Discrete parts refers to the notion that they have a size -- as opposed to differential parts which do not have a finite size in math.

Often, people use discretizing space to refer to splitting the region into a regular grid which can be indexed in 2d or 3d.

In this paper it appears that each discretization's behavior is evaluated independently of what is around it. In the picture, the pipe is considered as a pipe and its functionality is tested without regard to what is around it. Only the player and the pipe would be tested without regards to the coins or other platforms.

My 2 cents.

\**** Addition \****

He may have had something like movement in mind. In discrete space and time, the player would move from one grid square to the next in "turns." Each turn can be thought of as a span of time. This idea of playing the game with turns helps create the logic required to move the character and interact with the environment.

This seems to be a very abstract, high level presentation.

---
Tags: game-design, prototyping
---


# Question
Title: Is using Game in libGDX for more than just switching screens a bad practice?
I'm the process of refactoring the prototype of my game to use multiple screens using the Game - Screens model. I found some information (I think in more than one place) that the Game class should be used only to switch screens. I've checked some libGDX demos and they indeed follow that pattern.

Initially I wanted to do it the same way, but then I found more and more problems with this approach. AssetManager is the best example I think. Since there is only one instance of it and I would like to use it in more than on screen why not use the Game object to store it? Same thing with Viewport for example or Camera, if I'm happy with just one. What about single instances of my own classes, that I need throughout the whole game, why not to use Game for that?

I know that there are different ways to achieve what I wrote above. I can use static methods like here or create my own class to store all the needed objects and pass its instance between screens, but since I'm already passing instance of Game, what's the point?

To summarize: is using Game to anything else than to switch screens a bad practice? If so, why?

# Answer
Idea behind screens, is to separate logic between different context. However, those screens can still share data and have references to some classes that were originally initialized at original game class. If you don't use screens, you will have to dump all the code to main game class. Even if you try to hide logic behind different classes, you still end up having pile of mess.

Example: You could separate levels of your game to own screens. When starting new level, you could pass gameManager or whatever class to it. Then, when the level is done, you can just remove the screen and let the garbage collector handle the rest.

Example2: You could have GUI screen, that handles drawing GUI. That screen does indeed need THE reference to games engine or logic unit, so it can draw game related stuff.

So, it's perfectly fine to share data between screens and pass data to new screens.

EDIT: i just Re-read you question. If you use game class like that, i don't see it really violating anything. Just try to separate contextually different stuff. Game class is just a class, treat it like that and don't clutter it with everything. Design nice screen loader and just put all the levels in collection, like list or stack. Make screen set it's state to "IsFinished = true" and check for that and remove it from collection and from game and let the next screen start and get the update, input and draw.
> 1 votes

# Answer
You can use Game for everything you like. Game is just class that implements ApplicationListener and supports screen switching, nothing more. So design you code as you wish. Just be sure that your Game class doesn't become dump.
> 0 votes

---
Tags: libgdx
---


title: OpenGL: Draw an arrow

text:
# Question
Title: OpenGL: Draw an arrow
I'd like to know how to draw an arrow to represent a vector position, length and direction.

The issue is that I can't quite find an easy way to know the location and rotation of the triangle representing the arrow head.

If it can help, I'm using OpenGL/OpenTK(wrapper for C#).

# Answer
> 1 votes
What I'd do:

Have your standard arrow draw from (0, 0, 0) to (1, 0, 0) (using a line) and the tip of the arrow be a triangle at the end (using a triangle, points at (0.95, 0, +/-0.025) and (1, 0, 0)). Then resize your arrow to the size you need with a scale matrix (since it's a unit vector, it's easy to have it the desired size) and then move your arrow to wherever you need it with a translation and a rotation matrix.

And you can reuse it wherever you like!

Of course, you have to decide where you want it first, and remember that it is pointing in x+ when moving it around..!

---
Tags: c#, opengl, opentk
---


# Question
Title: Defining collision response in an Entity system
I'm building a really simple top-down 2d shooter which uses an Entity Component pattern.

I've added several different entities to a level and given them different collision groups. I have an entity to represent a teleporter (assigned to collision group A), a player entity (group B), and a bunch of enemies (Group C).

I understand that the actual collision response should be decided in the collision System based on the groups that the colliding entities belong to. What I can't figure out is how to define the specifics of a collision.

For example, if a player collides with a teleporter I need to move the player across the level. Where do I store the target location? I'd assume in a component on the teleporter. Should I create a whole new component just for that data? I feel it should be stored in the teleporters collision component but no all entities that use the collision component will require this data.

Could someone please try to enlighten me?

Thanks

# Answer
> 1 votes
An entity is just going to be a thing. It's an empty thing. The components you would add are its location, it's collision area, and a script saying where to move the collider if the collision area is hit. So you are definitely on the right track.

# Answer
> 1 votes
You're thinking is correct, the target location should be stored within a separate component attached to a Teleporter entity. This does two things:

Attaching a TeleporterComponent to an entity effectively makes the entity a teleporter. You could now conceivably make any game object act as a teleporter just by attaching the TeleporterComponent. This is a major strength of ECS.

As evorlor mentioned, you are now able to write a short script/system that fires when a teleporter collides and handles the logic for teleporting the collider. This way, all the other collision response logic does not have to be concerned with target locations.

---
Tags: entity-system, collision-resolution
---


# Question
Title: How can I rotate a Transform over a specified time in a single line of code?
**How can I rotate a `Transform` over a specified time in a single line of code?**

I have had a lot of trouble with this in the past. I wrote a script which rotates a `Transform` by a specified rotation over n seconds, or rotates a `Transform` towards a `Vector3` over n seconds, in a one liner. I hope it helps others in the future. See below.

# Answer
> 1 votes
Create a script called `TransformExtentions`. Paste the code into that script.

You can call `Transform.RotateTowardsOverTime(Vector3, float)` on your `Transform` where the `Vector3` is the target you want to rotate towards and the `float` is the number of seconds you want it to take.

You can call `Transform.RotateOverTime(Vector3, float)` on your `Transform` where the `Vector3` is the rotation you want to apply and the `float` is the number of seconds you want it to take. You can apply rotations greater than 360 degrees or less than -360 degrees.

Calling `Transform.RotateTowardsOverTime(Vector3, float)` or `Transform.RotateOverTime(Vector3, float)` will cancel out any active rotation calls on the `Transform`.

If you pass in 0 seconds, the `Transform` will rotate infinitely. If you pass in negative seconds, the `Transform` will rotate in reverse.

```
using UnityEngine;
using System.Collections;
using System;

public static class TransformExtensions
{
    /// <summary>
    /// Rotates the transform to a specified rotation over a set number of seconds.
    /// For an infinite rotation, multiply the degrees by a float to adjust the speed, and set the duration to 0 seconds.
    /// Calling RotateOverTime() or RotateTowardsOverTime() will cancel any pending rotations on this transform.
    /// </summary>
    public static void RotateTowardsOverTime(this Transform transform, Vector3 degrees, float seconds)
    {
        Vector3 rotationToBeMade = degrees - transform.rotation.eulerAngles;
        if (degrees.z > 270.0F && transform.rotation.eulerAngles.z < 90.0F)
        {
            rotationToBeMade.z = -(360.0F - degrees.z + transform.rotation.eulerAngles.z);
        }
        if (transform.rotation.eulerAngles.z > 270.0F && degrees.z < 90.0F)
        {
            rotationToBeMade.z = 360.0F - transform.rotation.eulerAngles.z + degrees.z;
        }
        RotateOverTime(transform, rotationToBeMade, seconds);
    }

    /// <summary>
    /// Rotates the transform by a specified number of degrees over a set number of seconds.
    /// For an infinite rotation, multiply the degrees by a float to adjust the speed, and set the duration to 0 seconds.
    /// Calling RotateOverTime() or RotateTowardsOverTime() will cancel any pending rotations on this transform.
    /// </summary>
    public static void RotateOverTime(this Transform transform, Vector3 degrees, float seconds)
    {
        RotateOverTime[] oldRotateOverTimeComponents = transform.gameObject.GetComponents<RotateOverTime>();
        foreach (RotateOverTime oldRotateOverTimeComponent in oldRotateOverTimeComponents)
        {
            GameObject.Destroy(oldRotateOverTimeComponent);
        }

        RotateOverTime rotateOverTimeComponent = transform.gameObject.AddComponent<RotateOverTime>();
        rotateOverTimeComponent.hideFlags = HideFlags.HideInInspector;
        rotateOverTimeComponent.Degrees = degrees;
        rotateOverTimeComponent.Seconds = seconds;
    }

class RotateOverTime : MonoBehaviour
{
    public Vector3 Degrees { get; set; }
    public float Seconds { get; set; }

    private Vector3 rotationCompleted = Vector3.zero;
    private Vector3 speed;
    private Vector3 startRotation;

    void Start()
    {
        speed = GetBalancedRotationSpeeds(Degrees, Seconds);
        startRotation = transform.eulerAngles;
    }

    void FixedUpdate()
    {
        UpdateRotation();
        if (IsRotationComplete())
        {
            Destroy(this);
        }
    }

    private Vector3 GetBalancedRotationSpeeds(Vector3 degrees, float seconds)
    {
        if (seconds == 0)
        {
            seconds = 1;
        }
        float degreesWeight = (Degrees.x + Degrees.y + Degrees.z) / 3;
        float speedModifier = degreesWeight / seconds;
        float totalChangeInDegrees = Math.Abs(degrees.x) + Math.Abs(degrees.y) + Math.Abs(degrees.z);
        float xWeight = Math.Abs(degrees.x) / totalChangeInDegrees;
        float yWeight = Math.Abs(degrees.y) / totalChangeInDegrees;
        float zWeight = Math.Abs(degrees.z) / totalChangeInDegrees;
        float xSpeed = xWeight * speedModifier * 3;
        float ySpeed = yWeight * speedModifier * 3;
        float zSpeed = zWeight * speedModifier * 3;
        return new Vector3(xSpeed, ySpeed, zSpeed);
    }

    private void UpdateRotation()
    {
        rotationCompleted += Time.deltaTime * speed;
        Vector3 rotation = Quaternion.Euler(rotationCompleted + startRotation).eulerAngles;
        bool rotationIsValid = !(float.IsNaN(rotationCompleted.x) || float.IsNaN(rotationCompleted.y) || float.IsNaN(rotationCompleted.z) && float.IsNaN(startRotation.x) || float.IsNaN(startRotation.y) || float.IsNaN(startRotation.z) || float.IsNaN(rotation.x) || float.IsNaN(rotation.y) || float.IsNaN(rotation.z));
        if (!rotationIsValid)
        {
            Destroy(this);
        }
        transform.eulerAngles = rotation;
    }

    private bool IsRotationComplete()
    {
        bool xRotationIsComplete = Math.Abs(rotationCompleted.x) >= Math.Abs(Degrees.x);
        bool yRotationIsComplete = Math.Abs(rotationCompleted.y) >= Math.Abs(Degrees.y);
        bool zRotationIsComplete = Math.Abs(rotationCompleted.z) >= Math.Abs(Degrees.z);
        return xRotationIsComplete && yRotationIsComplete && zRotationIsComplete && Seconds != 0;
    }
}

```

---
Tags: unity, rotation, transformation
---


# Question
Title: How do game companies handle DLL resources?
This question is based solely on curiosity. I have played a great many games on my PC over the years, and just now realized a trend across all games(most if not all). In the resources of the game, or in other words, next to the executable that runs the game, there are never DLL(Dynamic Link Library) binaries. This means that those games are created by statically linking to source files and dumping them all into the primary executable. I am certain that most of these game projects: Call of Duty, World of Warcraft, Splinter Cell, and \[Include other arbitrary examples here\], are utterly massive by scale and have hundreds of smaller children projects. I would probably not be wrong, either, in assuming that those same projects(such as API's, etc) could be packaged into a DLL instead of the obvious static linking. I apologize if it seems like I am rambling, but there is a point to this; it will be coming up soon. Next, I wanted to address the use of the games graphics API. Most games use DirectX, why is not relevant to this question; instead, it is how. Would I be safe to assume that said games are also statically linking to DirectX? And more importantly, why? Is there a logistical reasoning behind this inherently-conventional trait? Do game companies statically link all of their resources? And just again, why? Why not use DLLs instead?

Hopefully someone can answer this question, having been present or currently are present, working for an actual game company. Oh and I typed this all on my phone so I apologize for any errors.

# Answer
Well, for the first part a lot of modern games are coded in C++, which supports namespaces. Namespaces allow you to group a collection of related code within part of a whole. So you could have a collection of namespaces such as 'Render', 'Input', 'AIProcessor', etc (note: I am making these up)

Building these subprojects into the main project allows all of them to be shipped without forgetting to include a DLL in the installer (imagine the controversy if a developer forgot to include a subproject DLL in the installer upon release - the game wouldn't work for the end users until the developers released a patch with the missing DLL!)

Now, I only work with a small fledgling indie studio, but we have namespaces such as 'RenderEngines', 'SystemEngines', 'Interfaces', etc. in our game. Its far easier to include these in as namespaces instead of exporting them out to their own DLL, especially when I ship the next build to the team - I have enough problems with missing content files every now and then.

As for DirectX, often when installing (going from watching installers) they ask if you want to install the specific version of DirectX the game was built with. This gets installed to a predefined location on your computer, and the game loads the DirectX DLL's when you run it.
Even if you don't install the specific version, the DirectX install is smart enough to reference another version and use that. I have had problems previously with a game before requiring a very specific set of DirectX versions to work properly, otherwise it would crash if I started fiddling around with the graphics settings.
> 4 votes

# Answer
DirectX is a windows API with a corresponding DLL somewhere in your C:\windows directory, similarly with opengl32.dll. Check with dependency walker in you don't believe me.

The rest is probably handled through scripts which don't have to be DLLs and just reside in the rest of the assets.
> 1 votes

# Answer
Capsuling game modules in shared libraries has the benefit of reduced compile times during development. If the API between modules is carefully designed, it will not change often. This allows you to recompile only the module you are working on.

Shared libraries also allow to be shared by multiple Applications, thus saving disk space (and for a certain degree also memory when loaded by multiple application). They can also be distributed independently of the application which uses them.

But packaging your game modules in shared libraries has also draw backs. The main reason for games in my opinion: performance. Calling shared library functions involves a slight overhead to calling normal functions (a additional look up in a function address table). Linking dynamically also prevents global optimization. If you setup your build so that the compiler sees all source files it can perform optimization more aggressively. This requires static linking.

There are more arguments pro/con shared libraries, some of them have been mentioned in the other answers. But these are the main ones in my opinion.
> 1 votes

# Answer
Shared libraries such as DirectX have their DLLs installed under DirectX, not in the game folder.

Many game projects are divided up into multiple modules, particularly for different types of resources, but possibly also for modules or libraries. Breaking them up is useful for reducing patch sizes, for one thing. However, modules for a particular game are rarely if ever going to overlap with modules for any other game, and rarely will a game installer attempt to use the same module used by some other game installation, again unless it's a shared library such as DirectX. Otherwise there could be some dependency incompatibilities between versions - you wouldn't want updating game B to possibly mess with game A - you wouldn't want to have to even think about that possibility.

Usually DirectX is also backwards-compatible (so you can only have DirectX 10 installed and games written for DirectX 9 will work), though I think that has sometimes eroded a bit in practice.
> 0 votes

---
Tags: game-design
---


title: SDL2 - Inconsistent FPS with VSYNC

text:
# Question
Title: SDL2 - Inconsistent FPS with VSYNC
I'm working on a game using SDL2. Today I noticed the game has some jolty issues when not fullscreened so I made an extremely simplified program that simply moves a square from left to right to see if the result is the same.

I expected the squares movement to be very smooth but instead it's very jolty/laggy (when not fullscreened).

At first I thought it was to do with how I was calculating the time between each frame but after outputting the 'ftime' I can see the time each frame takes ranges from 13 to 30(ish) as opposed to a consistent 16/17.

Here's the code:

```
#include <iostream>
#include <SDL.h>

const int GAME_WIDTH = 1920;
const int GAME_HEIGHT = 1080;

//frame independent movement variables
double old_time = 0;
double current_time = 0;
double ftime = 0;

#undef main
int main(int argc, char** argv)
{
    SDL_Window* mainWindow;
    SDL_Renderer* mainRenderer;

    SDL_Init(SDL_INIT_EVERYTHING);

    mainWindow = SDL_CreateWindow("MiracleSquare", 50, 50, GAME_WIDTH, GAME_HEIGHT, 0);
    mainRenderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_PRESENTVSYNC);

    SDL_Rect miracleRect; //creating the SDL square
    miracleRect.x = 0;
    miracleRect.y = 400;
    miracleRect.w = 100;
    miracleRect.h = 100;

    bool running = true;

    while (running)
    {
        old_time = current_time;
        current_time = SDL_GetTicks();
        ftime = current_time - old_time;

        std::cout << ftime << std::endl;

        SDL_Event e; //stops crashing on input
        if (SDL_PollEvent(&e))
        {
            switch (e.type)
            {
            case SDL_KEYDOWN:
                break;
            default:
                break;
            }
        }

        miracleRect.x += (ftime / 1000.0f) * 100.0f;
        if (miracleRect.x> 1920) miracleRect.x = 0;

        SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
        SDL_RenderClear(mainRenderer);
        SDL_SetRenderDrawColor(mainRenderer, 255, 255, 255, 255);
        SDL_RenderDrawRect(mainRenderer, &miracleRect);
        SDL_RenderPresent(mainRenderer);
    }

    return 0;
}

```

Am I doing something wrong? As far as I can tell this should produce a smooth movement.

Any help would be greatly appreciated!

Edit: Since posting this I've figured out it has something to do with my use of dual monitors. If, for example, I have a video playing on chrome on my secondary monitor, the lag issue is very prominent. I'm now looking into if this issue is avoidable, or if I'll just have to ignore it.

# Answer
> 1 votes
Which platform are you running on? If it's Windows, then there are chances that the window manager or another application interferes with your graphical updates. I tried to diagnose some stuttering problems in window mode. In one scenario I found a background application messing with graphical settings. In other situations I isolated the problem to a resource conflict between the desktop window manager and the application. Sometimes (for reasons I didn't manage to find out) the desktop window manager will lock the graphical device just long enough for the application to miss the frame.

If this hits you there's not much you can do in my opinion. You can go full screen, or try disable window composition. See these answers from me on how to disable window composition, or how to diagnose stuttering on your own:

https://stackoverflow.com/questions/18182016/strange-opengl-rendering-stutter/21663076#21663076 https://stackoverflow.com/questions/21356302/linear-movement-stutter/21367858#21367858

---
Tags: sdl2
---


title: How to implement CMAA

text:
# Question
Title: How to implement CMAA
First, here's the link to the actual article that describes CMAA and how to do it. https://software.intel.com/en-us/articles/conservative-morphological-anti-aliasing-cmaa-update

My problem is that I can barely understand the steps involved. Either the wording is bad or my reading comprehension is bad, English not being my native language.

Could someone put it in simpler terms (Or maybe pseudocode if it's easier for you) so I can understand and implement it?

Specifically the steps 1 through 4.

# Answer
Article is written very well, you are simply nowhere near to understand math and process involved, keep learning... also given the fact the there is link for source code in the article it makes me think you simply didnt even read it properly.

Link: https://software.intel.com/sites/default/files/managed/53/c8/CMAA1.3\_26March2014.7z
> 1 votes

---
Tags: antialiasing
---


# Question
Title: Server Side Speed Hack Detection Techniques
I have a client side speed hack detection that initiates a timer on both the client and server on connection. When the difference becomes too much the client gets detected as using speed hack.

But I have one problem, they found a way to run a speed hack program and close it but keeping the speed hack activated on the game client (odd) which made the counter on the client run normally even with speed hack enabled.

So I added detection to the server by using the movement packets and checking the time difference between 2 different movement packets come in. The design was okay, it did detect the speed hack by checking that the difference is not less than `50ms` but when someone was lagging (queued movement packets) it also detected it as speed hack.

So I improved this by considering a factor of how fast it would process each packet that arrived in bulk which means microseconds. Now I adjusted the detection to `less than 50ms but greater than 1ms`. This was better it didn't detect lagging too much but it still did.

Now my problem is how can I implement this in a way that I can still check how fast the packets are coming in but not detect the people that are experiencing lag falsely. Or should I just keep adjusting the parameters for detection until I get to the sweet spot?

# Answer
> 1 votes
With a proper netcode design, speedhack detection shouldn't be necessary in the first place, because the server only receives *requests* to perform a given action, calculates all game mechanics itself and then sends the clients a response whether or not they can do that right now. The client sends a "I start moving into direction X:Y" message and the server then calculates the movement and keeps the clients updated about the progress until the client sends a "I stop moving" message.

But when you still want to go for a netcode design where the client can do whatever it wants to do without supervision (bad idea, because it allows a lot more ways to cheat), you could try to detect speedhacking by taking the average of many measurements over a longer timeframe.

You could take a measurement of how far their position changed each second, and then calculate the average movement speed over several seconds. When the player is supposed to have a movement speed of 5 m/s and after 5 seconds they have traveled over 100m, they are obviously speedhacking more than could be explained with lag...

...or are using some legitimate game mechanic which allows them to travel faster than usual (teleporters, jump pads, vehicles, rocket jumping etc.) - when you have something like this, remember to account for it by adjusting or ignoring any speed measurements which were made while the player-character was affected by one of these features.

---
Tags: mmo, anti-cheat
---


# Question
Title: Moving OBB vs. triangle intersection test
**Requirements**: to write a test function that, given a moving OBB (oriented bounding box) and a triangle, returns `true` whenever the OBB hits the triangle.

The OBB is described by its half extents (`h1, h2, h3`), principal axes (`a1, a2, a3`) and center point `C(cx,cy,cz)`. The triangle is described by its three vertices (`U1, U2, U3`). The OBB moves with the velocity `V` over a period of time of 1 second (hence `V` is also the displacement the OBB undergoes).

**Question**: I have already read Dave Eberly's mini-paper on the matter and made an attempt at an implementation. Also related to this paper, I have a question regarding the `w` projection of the `W` velocity: - is `w` equal to `dot(W, L)`, where `L` is one of the 13 possible separating axes he considered in that paper?

# Answer
> 1 votes
Although not 100% accurate, in the sense that it may report intersections even when the objects do not actually collide (but for that a more complex solution like GJK could be easily used), here's the solution I came up with after reading Dave Eberly's original paper on OBB vs moving triangle intersection test.

In that paper, the intersection test is performed between a triangle, described by vertices `(U0, U1, U2)` and edges `E0 = U1 - U0, E1 = U2 - U0, E2 = E1 - E0`, and an OBB, given through its center, `C`, principal axes, `A0, A1, A2` and half extents, `ha0, ha1, ha2`.

The triangle is assumed to be displaced along a direction `W`. The `W` axis, in this case, is not assumed to be normalized, but has a magnitude equal to the total displacement the triangle is subjected to.

The problem is not to find an actual intersection point, but to decide whether the OBB and triangle might overlap. For this, Eberly conceived a series of 13 separating axis tests. In summary, the separating axis test works by starting with a *candidate* axis, `L`, and checks whether the projections of the boundaries of the OBB and of the swept triangle volume (in this case, an oblique triangular prism) overlap as intervals. The origin of the `L` axis is assumed to be at the center `C` of the OBB. Refer to the picture below for a better understanding

After implementing the test in the article, I found it to perform very poorly for the case where the triangle was actually moving. In 50% of the cases, no separating axis candidate was able to separate the objects, although they were clearly not going to collide. Thus, I replaced those candidates with the following set of 7 axes, which worked reliably as an *early out* test in 93% of the cases:

* `L = W.cross(Ei)`, `i = 0:2`
* `L = W.cross(Ai)`, `i = 0:2`
* `L = W`

The first six cases are actually less numerically demanding due to the fact that `L` is by definition perpendicular to `W` (it helps with avoiding to compute some dot products since they're 0). In the last case, things are a bit more complicated, but that's why I left it as a last resort test before deciding the objects might indeed overlap. Although not represented in this figure, `D = U0 - C` is one of the vectors involved in computing the projection of the triangle onto the `L` axis.

To efficiently compute the amounts (cross and dot products) needed for this test, I wrote a small python script to generate the first 6 cases:

```
def symCross(i, j):
    k = {0, 1, 2}.difference({i, j})
    k = next(iter(k))
    if (i == 0 and j == 1) or (i == 1 and j == 2) or (i == 2 and j == 0):
        return k
    else:
        return -k

WcrossAi = set()
WcrossEi = set()
WcrossEidotAj = set()
WdotAi = set()

print "Real p0, p1, p2, R; \n";

# L = WxAi
for i in range(0,3):
    print "// L = WcrossA%d" % (i);
    L = "WcrossA" + `i`
    if L not in WcrossAi:
        WcrossAi.add(L)
        print "    Vector4 WcrossA"+`i` + "; WcrossA"+`i` +".setCross(W,a"+`i`+");"
    if "WcrossE0" not in WcrossEi:
        WcrossEi.add("WcrossE0")
        print "    Vector4 WcrossE0; WcrossE0.setCross(W, E0);"

    if "WcrossE1" not in WcrossEi:
        WcrossEi.add("WcrossE1")
        print "    Vector4 WcrossE1; WcrossE1.setCross(W, E1);"

    if "WcrossE0dotA{0}".format(`i`) not in WcrossEidotAj:
        WcrossEidotAj.add("WcrossE0dotA"+`i`);
        print "    Real WcrossE0dotA"+`i`+ " = WcrossE0.dot3(a"+`i`+");"

    if "WcrossE1dotA{0}".format(`i`) not in WcrossEidotAj:
        WcrossEidotAj.add("WcrossE1dotA"+`i`);
        print "    Real WcrossE1dotA"+`i`+ " = WcrossE1.dot3(a"+`i`+");"

    print "    p0 = WcrossA{0}.dot3(D);".format(`i`)
    print "    p1 = p0 - WcrossE0dotA{0};".format(`i`)
    print "    p2 = p0 - WcrossE1dotA{0};".format(`i`)
    # R
    R = "    R = "
    for k in range(0,3):
        if i != k:
            l = {0, 1, 2}.difference({i, k})
            l = next(iter(l))
            if "WdotA"+`l` not in WdotAi:
                WdotAi.add("WdotA"+`l`)
                print "    Real WdotA"+`l`+" = W.dot3(a"+`l`+");"
            R += "+ha"+`k`+"*fabs(WdotA"+`l`+") "
    R += ";"
    print R

    #heredoc test
    print '''
    if (ProjectedDistanceOveralp(p0, p1, p2, R) == false)
    {
        return false; // no intersection
    }
'''

# L = WxEi
for i in range(0,3):
    print "// L = WcrossE"+`i`
    if "WcrossE"+`i` not in WcrossEi:
        WcrossEi.add("WcrossE"+`i`)
        print "    Vector4 WcrossE{0}; WcrossE{0}.setCross(W,E{0});".format(`i`)
    print "    p0 = WcrossE{0}.dot3(D);".format(`i`)
    p1 = "    p1 = p0"
    p2 = "    p2 = p0"
    if i == 0:
        p1 += ";"
        p2 += " + WdotN;";
    elif i == 1:
        p1 += " - WdotN;"
        p2 += ";"
    else:
        p1 += " - WdotN;"
        p2 += " - WdotN;"
    print p1
    print p2
    R = "    R = ";
    for k in range(0,3):
        if "WcrossE{0}dotA{1}".format(`i`,`k`) not in WcrossEidotAj:
            WcrossEidotAj.add("WcrossE{0}dotA{1}".format(`i`,`k`))
            print "    Real WcrossE{0}dotA{1} = WcrossE{0}.dot3(a{1});".format(`i`, `k`)
        R += " + ha{1} * fabs( WcrossE{0}dotA{1} ) ".format(`i`,`k`)
    R += ";"
    print R
        #heredoc test
    print '''
    if (ProjectedDistanceOveralp(p0, p1, p2, R) == false)
    {
        return false; // no intersection
    }
'''

```

For testing whether the projected bodies overlap, I've written two SIMD friendly functions in c++:

```
bool ProjectedDistanceOveralp(Real p0, Real p1, Real p2, Real R)
{
    Vector4 p012; p012.set(p0, p1, p2);
    Vector4 Rplus; Rplus.setAll(R);
    Vector4 Rminus; Rminus.setAll(-R);
    Mask4 greaterThanR = p012.greater(Rplus);
    Mask4 lessThanR = p012.less(Rminus);
    return !(greaterThanR.getMask() == Mask4::MASK_XYZ || lessThanR.getMask() == Mask4::MASK_XYZ);
}

bool ProjectedDistanceOveralpWithW(Real p0, Real p1, Real p2, Real R, Real w)
{
    Vector4 p012; p012.set(p0, p1, p2);
    Vector4 Rplus; Rplus.setAll(R);
    Vector4 Rminus; Rminus.setAll(-R - w);
    Mask4 greaterThanR = p012.greater(Rplus);
    Mask4 lessThanR = p012.less(Rminus);
    return !(greaterThanR.getMask() == Mask4::MASK_XYZ || lessThanR.getMask() == Mask4::MASK_XYZ);
}

```

Finally, the `L=W` axis test can be written as:

```
// L = W
            Real WdotW = W.dot3(W).getReal();
            p0 = W.dot3(D).getReal();
            p1 = p0 + W.dot3(E0).getReal();
            p2 = p0 + W.dot3(E1).getReal();
            R = ha0 * fabs(WdotA0) + ha1 * fabs(WdotA1) + ha2 * fabs(WdotA2);
            if (ProjectedDistanceOveralpWithW(p0, p1, p2, R, WdotW) == false)
            {
                return false; // no intersection
            }

```

# Answer
> 2 votes
An oriented bounding box is delimited by six planes (one for each face). A triangle is also delimited by three lines (one for each sides). A naive implementation (which often a good idea to start with) is thus to compute the intersection of any triangle edge with any plane and to check whether at least one intersection occur within an edge of a triangle and within a face of the OOB.

```
for each edge E of the triangle,
    let L be the line of direction obtained by extending E
    for each face F of the OOB,
        let P be the plane obtained by extending F.
        let q be the intersection of L and P.
        if q exists and q is within E and q is within F, then
            An intersection occurred.

```

It's probably easier to use a local reference frame so the OBB becomes an AABB. Then you can start to optimize.

---
Tags: collision-detection, physics, geometry, intersection
---


# Question
Title: What is better? Lots of small TCP packets, or one long one?
I am sending quite a bit of data to and from a server, for a game I'm making.

I currently send location data like this:

```
sendToClient((("UID:" + cl.uid +";x:" + cl.x)));
sendToClient((("UID:" + cl.uid +";y:" + cl.y)));
sendToClient((("UID:" + cl.uid +";z:" + cl.z)));

```

Obviously it is sending the respective X, Y, and Z values.

Would it be more efficient to send data like this?

```
sendToClient((("UID:" + cl.uid +"|" + cl.x + "|" + cl.y + "|" + cl.z)));

```

# Answer
A TCP segment has quite a lot of overhead. When you send a 10 byte message with one TCP packet you actually send:

* 16 bytes of IPv4 header (will increase to 40 byte when IPv6 becomes common)
* 16 bytes of TCP header
* 10 bytes of payload
* additional overhead for the data-link and physical layer protocols used

resulting in 42 bytes of traffic for transporting 10 byte of data. So you only make use of less than 25% of your available bandwidth. And that does not yet account for the overhead which the lower-level protocols like Ethernet or PPPoE consume (but these are hard to estimate because there are so many alternatives).

Also, many small packets put more strain on routers, firewalls, switches and other network infrastructure equipment, so when you, your service provider and your users don't invest in high-quality hardware, this might turn into another bottleneck.

For that reason you should try to send all data you have available at once in one TCP segment.

**Regarding handling packet loss**: When you use TCP you don't need to worry about that. The protocol itself ensures that any lost packets are resent and packets are processed in order, so you can assume that all packets you send will arrive at the other side, and they will arrive in the order you send them. The price for this is that when there is packet loss, your player will experience considerable lag, because one dropped packet will halt the whole data-stream until it was re-requested and received.

When this is a problem, you can always use UDP. But then you need to find your own solution for lost and out-of-order messages (it at least guarantees that the messages which *do* arrive, arrive complete and undamaged).
> 30 votes

# Answer
One large one (within reason) is better.

As you said, packet loss is the main reason. Packets are generally sent in frames of a fixed size, so it is better to take up one frame with a big message than 10 frames with 10 small ones.

However with standard TCP, this isn't really an issue, unless you disable it. (It is called Nagle's algorithm, and for games you should disable it.) TCP will wait for a fixed timeout or until the package is "full". Where "full" is would be some slightly magic number, determined in part by the frame size.
> 10 votes

# Answer
All the previous answers are incorrect. In practice, it doesn't matter whether you issue one long `send()` call or several small `send()` calls.

As Phillip states, a TCP segment has some overhead, but as an application programmer, you have no control over how segments are generated. In simple terms:

> One `send()` call does not necessarily translate to one TCP segment.

The OS is completely free to buffer all of your data and send it in one segment, or take the long one and break it into several small segments.

This has several implications, but the most important one is that:

> One `send()` call, or one TCP segment does not necessarily translate to one successful `recv()` call on the other end

The reasoning behind this is that TCP is a **stream** protocol. TCP treats your data as a long stream of bytes, and has absolutely no concept of "packets". With `send()` you add bytes to that stream, and with `recv()` you get bytes off the other side. TCP will aggressively buffer and split your data wherever it sees fit to make sure your data gets to the other side as fast as possible.

If you want to send and receive "packets" with TCP, you have to implement packet start markers, length markers and so on. How about using a message oriented protocol like UDP instead? UDP guarantees one `send()` call translates to one sent datagram and to one `recv()` call!

> *When all you have is TCP, everything looks like a stream*
> 6 votes

# Answer
Many small packages is fine. In fact, if you are worried about TCP overhead, just insert a `bufferstream` that collect up to 1500 chars (or whatever your TCP MTUs is, best to request it dynamically), and deal with the problem in one place. Doing so spares you the overhead of ~40 bytes for every extra package you would otherwise have created.

That said, it's still better to send less data, and building larger objects help there. Ofcourse it's smaller to send `"UID:10|1|2|3` than to send `UID:10;x:1UID:10;y:2UID:10;z:3`. In fact, also at this point you should not be reinventing the wheel, use a library like **protobuf** that can decrease data like that to a 10 byte string or less.

Only thing you should not forget is to insert a `Flush` commands on your stream at relevant locations, because as soon as you stop adding data to your stream, it might wait infinite before it send anything. Really problematic when your client is waiting for that data, and your sever wont send anything new until the client send the next command.

Package loss is something you can affect here, marginally. Every byte you send can potentially be corrupted, and TCP will automatically request a retransmission. Smaller packages means a lower chance for every single package to be corrupted, but because they add up on the overhead, you send even more bytes, increasing the odds of a lost package even more. When a package is lost, TCP will buffer all succeeding data until the missing package is resend and received. This result in a large delay (ping). While the total loss in bandwidth because of package loss might be negligible, the higher ping would be undesirable for games.

**Bottom line:** Send as little data as possible, send large packages, and do not write your own low level methods to do so, but rely on well known libraries and methods like `bufferstream` and protobuf to handle the heavy lifting.
> 3 votes

# Answer
Although being a neophyte to network programming myself, I would like to share my limited experience by adding a few points:

* TCP does imply an overhead - you must measure the relevant statistics
* UDP is the *de facto* solution for networked gaming scenarios, but all implementations that rely on it have an extra, CPU-side algorithm to account for packets being lost or being sent out of order

Concerning measurements, the metrics that should be considered are:

As mentioned, if you find out that you're not limited in a sense and could use UDP, go for that. There are some UDP-based implementations out there, so you don't have to reinvent the wheel or work against years of experience and proven experience. Such implementations worth mentioning are:

Conclusion: since a UDP implementation could outperform (by a factor of 3x) a TCP one, it makes sense to consider it, once you've identified your scenario to be UDP friendly. Be warned! Implementing the full TCP stack on top of UDP is always a bad idea.
> 2 votes

---
Tags: networking
---


# Question
Title: Unity 5 How Do I Set Text of Text Component of Input Field
How do I set the text of the new Input Field's Built In Text UI Object in Unity 5+?

```
 myInputFieldText.text = "Text Value I Want";

```

The code above does not work to set the text inside of a InputField's Text. Thanks

# Answer
> 0 votes
Turns out that the Text component of a InputField can be used to easily read the text, but setting the value of the text requires more than just changing the InputField's Text.text. The fastest way to set an InputField's Text's text is actually to go right to the InputField itself and to set it's Text that will automatically update the InputField's text component.

So:

```
myInputField.text = "Text Value I Want";

```

Will also set myInputFieldText.text to the same value

---
Tags: c#, unity
---


# Question
Title: A* pathfinding for grid with direction-dependent nodes?
I'm trying to understand if the A\* algorithm is a possible pathfinding solution for my game.

I have a simple grid of nodes that an enemy can move around on, but the nodes represent traversable terrain at different heights in my game world. So although an enemy might be able to "jump down" from Node A to Node B (where Node A is much higher than Node B), it could not do the reverse and "climb up" from Node B to Node A. In other words, whether the A\* algorithm can travel from one node to another depends on the direction of travel. It may be possible in one direction but not the other.

Can A\* handle a situation like this, or do I need a different pathfinding algorithm?

# Answer
AStar is a suitable algorithm and can easily accomplish what you're describing.

It all comes down to either applying a set of rules or costs to the various connections between the nodes in your world(graph).

For example you could just have a bit of logic code in your TryGetNeighbours function call in each step of your pathfinding algorithm \[untested code example\] :

```
void Search(Node start, Node goal) {
    // ...
    Node[] neighbours = new Node[];
    if(TryGetNeighbours(currentNode, out neighbours) {
        foreach(var node in neighbours) {
            // do pathfinding calcs i.e. f = g + h. etc
        ...
        }
    }
    // ...
}

bool TryGetNeighbours(Node current, out Node[] neighbours) {
    Node neighbour;
    for(int x = 0; x < 4; x++) {
        // determine neighbouring node by Vector addition etc
        neighbour = current.pos + x
        if(neighbour.CanTraverse(current) {
            neighbours[x] = neighbour;
        }
    }
    if(neighbours[0] != null) return true;
    return false;
}

```
> 2 votes

# Answer
Yes it can.

You just have to create a method like "CanIMoveFrom1to2(currentNode, targetNode)". Then in A\*, before analyzing that node any further, just check if its walkable from this node, if not, discard it, if yes then add it to open list.
> 2 votes

---
Tags: path-finding
---


# Question
Title: (DX11.1) CreateSwapChainForHwnd fails with E_NOINTERFACE when using Graphics Diagnostics
The CreateSwapChainForHwnd fails with E\_NOINTERFACE "No such interface supported" when I use the Graphics Diagnostics on Visual Studio 2013 Update 4 on Windows 7 sp1 under DirectX 11.1. The program runs fine in debug mode. Has anyone come across this problem before or know of a solution?

Here is the initialisation code:

```
#include <d3d11_1.h>

// Set feature levels supported by our application
D3D_FEATURE_LEVEL eFeatureLevel1[] =
{
    D3D_FEATURE_LEVEL_11_1,
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_3,
    D3D_FEATURE_LEVEL_9_2,
    D3D_FEATURE_LEVEL_9_1
};

D3D_FEATURE_LEVEL           eReturnedFeatureLevel;

D3D11CreateDevice(nullptr,                  // default adapter
    D3D_DRIVER_TYPE_HARDWARE,
    0,                          // no software device
    uiCreateDeviceFlags,
    eFeatureLevel1,
    ARRAYSIZE(eFeatureLevel1),
    D3D11_SDK_VERSION,
    &m_spDeviceOld,
    &eReturnedFeatureLevel,
    &m_spContextOld);

if (eReturnedFeatureLevel < D3D_FEATURE_LEVEL_11_0)
{
    //MessageBox fails silently here!!!
    return false;
}

// Fetch the underlying interfaces and store them:
m_spDeviceOld.As(&m_spD3DDevice);
m_spContextOld.As(&m_spD3DImmediateContext);

SETPRIVATEDATA(m_spDeviceOld, "CD3DObject::m_spDeviceOld");
SETPRIVATEDATA(m_spContextOld, "CD3DObject::m_spDeviceOldspContextOld");

// This is the earliest the Debug Layer can be created
MyDebugLayer.CreateD3DDebugLayer();

SETPRIVATEDATA(m_spD3DDevice, "CD3DObject::m_spD3DDevice");
SETPRIVATEDATA(m_spD3DImmediateContext, "CD3DObject::m_spD3DImmediateContext");

m_spD3DDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM,
                                            4,
                                            &m_ui4xMsaaQuality);

assert(m_ui4xMsaaQuality > 0);

DXGI_SWAP_CHAIN_DESC1 stSwpChainDesc = { 0 };
stSwpChainDesc.Width = 0;
stSwpChainDesc.Height = 0;
stSwpChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
stSwpChainDesc.Stereo = false;
stSwpChainDesc.SampleDesc.Count = 1;
stSwpChainDesc.SampleDesc.Quality = 0;
stSwpChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
stSwpChainDesc.BufferCount = 1;                                 // Used to be 1
stSwpChainDesc.Scaling = DXGI_SCALING_STRETCH;
stSwpChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
stSwpChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

// Use 4X MSAA?
if (m_bEnable4xMsaa)
{
    stSwpChainDesc.SampleDesc.Count = 4;
    stSwpChainDesc.SampleDesc.Quality = m_ui4xMsaaQuality - 1;
}
// No MSAA
else
{
    stSwpChainDesc.SampleDesc.Count = 1;
    stSwpChainDesc.SampleDesc.Quality = 0;
}

Microsoft::WRL::ComPtr<IDXGIDevice1> spDXGIDevice;
m_spD3DDevice.As(&spDXGIDevice);

IDXGIAdapter1* pDxgiAdapter = 0;
spDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&pDxgiAdapter);

IDXGIFactory2* pDxgiFactory = 0;
pDxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&pDxgiFactory);

// Create DXGI swap chain targeting a window handle (the only Windows 7-compatible option)
HRESULT MyHr = pDxgiFactory->CreateSwapChainForHwnd((ID3D11Device*)m_spD3DDevice.Get(), m_hMainWnd, &stSwpChainDesc, nullptr, nullptr, &m_spSwapChain);

//MessageBox fails silently here!!!
//MessageBox(m_hMainWnd, _com_error(MyHr).ErrorMessage(), "Error Caputed", MB_OK);

ReleaseCOM(pDxgiAdapter);
ReleaseCOM(pDxgiFactory);
spDXGIDevice->Release();

```

Why does the code fail when I use the graphics diagnostics tool and not normally? Basically the main window appears then the application shuts down. Also any calls to MessageBox(\[NULL/or not\]) fails silently too.

Supplemental: m\_spDeviceOld and m\_spContextOld are ID3D11Device and ID3D11DeviceContext used for getting the 11.1 interface they then are detached at exit and the 11.1 interfaces are released instead.

Thanks in advance for your indelible advice.

# Answer
> 0 votes
Found it...

Simple typo:

```
IDXGIAdapter1* pDxgiAdapter = 0;
spDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&pDxgiAdapter);

IDXGIFactory2* pDxgiFactory = 0;
pDxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&pDxgiFactory);

```

Should have been (with Chuck Walbourn's 'ComPtr suggestions):

```
Microsoft::WRL::ComPtr<IDXGIAdapter2> spDxgiAdapter;
HR(spDXGIDevice->GetParent(__uuidof(IDXGIAdapter2), (void**)&spDxgiAdapter));

Microsoft::WRL::ComPtr<IDXGIFactory2> spDxgiFactory;
HR(spDxgiAdapter->GetParent(__uuidof(IDXGIFactory2), (void**)&spDxgiFactory));

```

I had not upgraded my uuidof(...) interface IDs. It's so easy to leave of the correct numerical suffix to these things. Thanks for your resposes :)

---
Tags: directx
---


# Question
Title: What is the difference between .obj files and Collada files?
I am currently making a game in java using LWJGL 2.9 and I am wondering what the difference between the .obj format and .dae format is. Currently I can load .obj files and would like to load .dae files as well.

Any information on .dae files would be great.

# Answer
Your basic OBJ, or Object Wavefront file only contains geometry data - vertices, normals, texture co-ords, and optionally material data in an second file. It does not contain any sort of skeletal structure or motion data. Collada on the other hand contain both geometry data and optionally skeletal structure and motion data, along with scene information (eg light sources, camera), and a texture and material atlas.
Both file formats are regarded as interchange formats for transfering model data between modelling programs and to/from game SDK's.

Format wise, both are a plain text file format, with the OBJ file having one entry per line, making it easy to be read a parsed. If you know what section you are reading, you can process the line appropriately. Collada has a much more complex XML based structure that is much more difficult to parse.
However, due to their plain text format, and the fact they need to be processed, loading them is generally rather slow when compared to a binary optimized file format. \**

In terms of writing parsers for the OBJ and Collada file formats, Wikipedia describes the format well enough that with a simple sample file you can write a loader. Collada, on the other hand, is much more complex. The best information I have found on loading Collada files is this tutorial by Wazim. A bit more information on Collada can be found on Wikipedia, mainly the links to various libraries capable of loading and parsing Collada files. There may also be a link to the spec somewhere in there as well.
However, unless you want the challenge of both writing a Collada importer, and supporting it for the minor variations that different programs produce, your probably better off using a library with an established importer.

\** I managed to go from a 1 minute load using raw .obj files to \<1 second using a custom binary format that mapped directly to my games Scene object, not to mention the files were about 25% +/- 5% of the size of the original OBJs. I haven't done profiling on Collada yet.
> 4 votes

---
Tags: java, lwjgl
---


# Question
Title: A* pathfinding not finding shortest path with weird behavior
*NOTE* I have read through this thread and have tried the implemented answer

The A\* pathfinding algorithm works fine most of the time but in some specific cases, it seems to not use the shortest path.

For example,

Legend

* N = Start point
* E = Endpoint
* | = obstacle
* (-) supposed movement path
* > = How it moves
* D = move down
* U = move up

```
         _ _ _ _
         |     |
         |   | |
  N(-)(-)(-)U|E
  D         U|
  D         U|
  D > > > >>U|

```

End of diagram and assume that all the other paths are blocked and that the three (-) (-) (-) direction is the shortest path to the end. In this specific instance, it chooses to take the longer path represented by \>\>\>\>\> UUUUU instead of (-)x3.

```
    func startPathfinding(startPoint:CGPoint, endPoint:CGPoint) {
    var layer : TMXLayer = map.layerNamed("World1")
    var currentTile = layer.tileAt(startPoint)
    var initialPosition = getTileCoordinate(startPoint)//layer.coordForPoint(startPoint) //startPoint
    var endPosition = getTileCoordinate(endPoint)//layer.coordForPoint(endPoint)             //endPoint

    self.openList = []
    self.closedList = []
    var tempGScore = 0

    insertInOpenSteps(ShortestPathStep(loc: initialPosition))
    var nodesProcessed = 0

    if isValidTile(startPoint) == false || isValidTile(endPoint) == false {
        println("BUG!")
        return
    }
    do {
        if nodesProcessed > 3000 {
            println("Stopping!")
            break
        }

        var currentStep = openList.objectAtIndex(0) as ShortestPathStep
        println(currentStep.position)
        closedList.addObject(currentStep)
        openList.removeObjectAtIndex(0)
        if CGPointEqualToPoint(currentStep.position, endPosition) {
            println("I found a path")
            constructPathAndStartAnimationFromStep(currentStep)
            var tmpStep: ShortestPathStep! = currentStep
            do {
                tmpStep = tmpStep.parent
            } while tmpStep != nil
            self.openList = []
            self.closedList = []
            break
        }
        var adjacentTiles = walkableAdjacentTiles(currentStep.position)
        for adjacentNodes in adjacentTiles {
            nodesProcessed = nodesProcessed + 1
            var step : ShortestPathStep! = ShortestPathStep(loc: adjacentNodes.CGPointValue())
                if closedList.containsObject(step)   {
                    //   step = nil
                    continue
            }
            var moveCost = costToMoveFromStep(currentStep as ShortestPathStep, toAdjacentStep: step)

            var index = openList.indexOfObject(step)
            if index == Foundation.NSNotFound {

                step.parent = currentStep as ShortestPathStep
                step.gScore = currentStep.gScore + moveCost
                step.hScore = computeHScoreFromCoord(step.position, toCoord: endPosition)
                insertInOpenSteps(step)

            }

            else {
                step = openList.objectAtIndex(index) as ShortestPathStep

                if (currentStep.gScore + moveCost) < step.gScore {

                    step.gScore = currentStep.gScore + moveCost
                    openList.removeObjectAtIndex(index)
                    insertInOpenSteps(step)

                }
            }
        }

    } while openList.count > 0

    }

    func walkableAdjacentTiles(tileLoc:CGPoint) -> NSMutableArray {
    var tmp : NSMutableArray = [] // 0 = not walkable 1 = walkable  (left,right,up,down)
    var layer : TMXLayer = map.layerNamed("World1")
    var position = tileLoc
    var right: Bool = isValidTile(CGPoint(x: position.x + 1, y: position.y))
    var left: Bool = isValidTile(CGPoint(x: position.x - 1, y: position.y))
    var up: Bool = isValidTile(CGPoint(x: position.x , y: position.y - 1))
    var down: Bool = isValidTile(CGPoint(x: position.x, y: position.y + 1))
    var p : CGPoint

    if left {
        p = CGPointMake(position.x - 1, position.y)
        tmp.addObject(NSValue(CGPoint: p))
    }
    if right {

         p = CGPointMake(position.x + 1, position.y)
        tmp.addObject(NSValue(CGPoint: p))

    }
    if up {
        p = CGPointMake(position.x, position.y - 1)
        tmp.addObject(NSValue(CGPoint: p))
    }
    if down {
        p = CGPointMake(position.x, position.y + 1)
         tmp.addObject(NSValue(CGPoint: p))

    }
    return tmp
     }
    func insertInOpenSteps(step: ShortestPathStep) {
    var stepFScore = step.fScore()

    var count = openList?.count
    var i = 0

    for i; i < count; i++ {
        var test = self.openList.objectAtIndex(i) as ShortestPathStep
        if stepFScore <= self.openList.objectAtIndex(i).fScore() {
            break
        }
    }
    self.openList?.insertObject(step, atIndex: i)
    }
    func computeHScoreFromCoord(fromCoord:CGPoint,toCoord:CGPoint) -> Int {

    var x = abs(toCoord.x - fromCoord.x)
    var y = abs(toCoord.y - fromCoord.y)
    var hScore = x + y
    return Int(hScore)
    }
    func costToMoveFromStep(fromStep: ShortestPathStep, toAdjacentStep: ShortestPathStep) -> Int {
    return 1
    }

```

# Answer
> 0 votes
Cant comment so Ill leave as answer instead. I like the implementation of A\* from this page: http://www.redblobgames.com/pathfinding/a-star/introduction.html. It goes step by step on how to build a path finding algorithm from the simplest and gradually increases complexity.

I scanned over your implementation and it is not clear to me where the bug is. But however, you should not use arrays for your openlist and closedlist. Because array.removeAtIndex() and array.getLowestPriority() is a O(n) operation. The openlist should be a priority queue data structure and closeList should be a set or hashmap. Otherwise you will get a big speed hit. The bug you are facing might be due to your openlist not properly returning the lowest value, or perhaps when the goal tile is reached the algorithm did not pick the correct behaviour. I suggest rewrite your function entirely, the A\* really isnt that hard, from the link above, it is basically this:

```
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
cost_so_far = {}
came_from[start] = None
cost_so_far[start] = 0

while not frontier.empty():
   current = frontier.get()

   if current == goal:
      break

   for next in graph.neighbors(current):
      new_cost = cost_so_far[current] + graph.cost(current, next)
      if next not in cost_so_far or new_cost < cost_so_far[next]:
         cost_so_far[next] = new_cost
         priority = new_cost + heuristic(goal, next)
         frontier.put(next, priority)
         came_from[next] = current

```

---
Tags: algorithm, path-finding
---


# Question
Title: Why aren't all public methods BlueprintCallable by default?
Considering the entire point of public/protected/private encapsulation is to abstract the class so it's easy to use, why does the programmer also have to decide if a method is callable from blueprints? Shouldn't all public methods/variables be visible in blueprints?

How should I determine if a member should be visible in blueprints? Should I only add the macro when they're strictly needed? Should I aim to make blueprint interfaces even more abstract than the corresponding C++ interface?

# Answer
> Shouldn't all public methods/variables be visible in blueprints?

The point of encapsulation is not only ease of use, but also to decouple parts to create a more robust and maintainable system. The idea to only expose certain parts of your code to others has proven to be one of the best practices in software development, so I think it is only natural for EPIC to unclude such a mechanism into their c++-blueprint system.

The other reason I can think of is that the Unreal Engine was built to be used in really big dev teams, with a lot of code. And maybe it is only me, but I find the "create a new blueprint node" popup very cluttered as it is. Adding hundreds of additional variables and methods might not be a good idea.

> How should I determine if a member should be visible in blueprints? Should I only add the macro when they're strictly needed?

I don't think there is a general answer to that, just do what feels right for you and your team. I personally try to only expose stuff to blueprints or c++ if it is absolutely needed, but sometimes I expose my stuff anyway out of lazyness ;)
> 2 votes

---
Tags: c++, unreal-4
---


title: Unity messes up the fileIDs

text:
# Question
Title: Unity messes up the fileIDs
I'm working in a team of three people on a 2D game, and Unity recently has been messing up the `fileID` on many sprites:

```
-  m_Sprite: {fileID: 21300000, guid: 6186fa4d068aae8418d9520f658d1ee6, type: 3}
+  m_Sprite: {fileID: 21300002, guid: 6186fa4d068aae8418d9520f658d1ee6, type: 3}

```

The `guid` stays the same, but the `fileID` changes, and the sprite goes missing. If one member fixes it, it becomes broken for one or both the others.

What can we do to fix that?

"reimport" didn't work. Prefabbing them didn't work. Deleting the whole project and re-downloading it didn't work either.

We are using 4.6.0f3, and before that we were using 4.6.0b17 IIRC. "Force Text" is already selected.

Here's `.gitignore`:

```
Build/
Design/

# project trashable
obj
Temp
*.tmproj
*.csproj
*.unityproj
*.sln
*.suo
*.user
*.pidb
*.userprefs
*.link
*.pyc

# library trashable
Library/cache/*
Library/shadercache/*
Library/metadata/*
Library/previews/*
Library/ScriptAssemblies/*
Library/*.log
Library/ShaderCache.db
Library/ShaderCache
Library/shadercompiler-1.log

# various
AnnotationManager
AssetImportState
AssetServerCacheV3
AssetVersioning.db
AudioManager.asset
BuildPlayer.prefs
BuildSettings.asset
CurrentLayout.dwlt
CurrentMaximizeLayout.dwlt
DynamicsManager.asset
EditorUserBuildSettings.asset
FailedAssetImports.txt
InspectorExpandedItems.asset
MonoManager.asset
NetworkManager.asset
ScriptMapper
assetDatabase3
assetservercachev3
expandedItems
guidmapper
CurrentMaximizeLayout.dwlt

```

I've just noticed I also have a global gitignore, which the others might not have:

```
*~
.DS_Store

```

I'm wondering if such a thing mess up the fileIDs? I.e. **if someone has a DS\_Store file and someone else does not, can this be a problem?**

*(btw what's the point of fileIDs, if there already are guids? Doesn't they defeat the purpose of having guids in the first place?)*

# Answer
> 0 votes
In order to get rid of this, we had *everyone* delete and re-download the project from git. Only then the problem disappeared.

# Answer
> 1 votes
I imagine you got this problem after a merge. You can rollback to when everything was correct, find who is the origin of the problem, and maybe find why it occured.

In any cases I think you will have to ask your team member to force update / pull the latest version.

Probably not related but remember to always set Asset Serialization to "Force Text" and Version Control to "Visible Meta Files" in Edit \> Project Settings \> Editor.

---
Tags: unity
---


# Question
Title: How can I prevent seams when attempting to create a skybox for Unity5?
After following the documentation for how to create a skybox, seams are appearing around all sides of my 6 textures (sorry for faintness of image):

There are no active lights in my scene. **What am I doing wrong and how can I prevent this?** Any skybox creation methodology suggestions would be much appreciated.

# Answer
I figured it out. I forgot to set the "wrap mode" for each of the 6 textures to "clamp" rather than repeat. This seems to make all the difference when preventing seams for the skybox material.
> 2 votes

---
Tags: unity, textures, skybox
---


title: unity2D Top-Dow Mobile rigibody2D

text:
# Question
Title: unity2D Top-Dow Mobile rigibody2D
im using this code for my 2D TopDown mobile player movement.but when i move player With UI Image buttons player keep moving.it didnt stop.and also player starting of move he is very slow. the he accelerate his speed.how can i fix this.

i add BoxCollider 2D and Rigibody2D my sprite.the set Gravity to 0.

this is my code.

```
    public class PlayerScript : MonoBehaviour {
public float speed = 150f;
float hInput ;
void FixedUpdate()
{
    Move (hInput);

}

public void Move(float horizontalInput){
    if (horizontalInput.Equals(1)) {
                    rigidbody2D.AddForce (Vector2.right);

    }if (horizontalInput.Equals(2)) {
        rigidbody2D.AddForce (-Vector2.right);
    }if(horizontalInput.Equals(3)) {
        rigidbody2D.AddForce (Vector2.up);
    }
    if(horizontalInput.Equals(4)) {
        rigidbody2D.AddForce (-Vector2.up);
    }
    }

    public void StartMoving(float horizontalInput){
    hInput = horizontalInput;
    }
    }

```

# Answer
It does not stop, if you don't have friction and gravity, that in normal world slow you down. When applying force, you are really not adding force at all and in fact i am bit surprised that it actually moves at all.

You should apply more force, to get your object moving. Try something like this.

* Vector2.right = Thats the direction of the force
* Multiply by speed = takes your wanted speed to calculations
* Time.deltaTime = makes your character to move based on time ( even thou you are using fixedUpdate, so that should not matter )

`rigidbody2D.AddForce (Vector2.right * speed * Time.deltaTime);`

Remember to set some values to drag,friction,gravity and something like that, so physicsEngine actually stops your movement also. If its moving too fast, check the speed variable and playe with masses.
> 1 votes

# Answer
Consider reading books about realworld physics. "In physics, a force is any interaction which tends to change the motion of an object." - Wikipedia. So... By applying force you make it accelerate and decelerate. You need to have friction or don't use physics at all to make it stop at the end of button press.
> 1 votes

---
Tags: unity, c#, physics, rigid-body-dynamics
---


# Question
Title: Unity3d webplayer failed to download data file
When testing my game web builds on localhost, I get the error "Failed to download data file". The game data file is correctly placed, and the page loads fine, it just wont download the plugin, or prompt me to do so.

I tried the following things: Add MIME Types to IIS 7.5:

1. Open IIS Manager
2. Double click "MIME Types" in the IIS section.
3. Click Add on the right side "Actions" menu.
4. File name extension: = .unity3d
5. MIME type: application/unity3d
6. click ok
7. Restart the server (right side "Actions" menu)

That didn't work for me specifically because it turned out I was using IIS Express, so I did the following:

If Windows 7, browse to 'C:\Users\\Documents\IISExpress\config\\' and open the file: ApplicationHost.config.

Search for 'staticContent' and add the following before the closing tag:

However, again, it didn't work..

# Answer
The solution in my situation was to add a web.config file and place it in the same directory as the WebPlayer.html and 'gamename'.unity3d files.

The content of the web.config:

```
<configuration>
    <system.webServer>
        <staticContent>
           <mimeMap fileExtension=".unity3d" mimeType="application/vnd.unity" />
        </staticContent>
    </system.webServer>
</configuration>

```
> 1 votes

---
Tags: unity
---


title: Random, Infinite Terrain Generation

text:
# Question
Title: Random, Infinite Terrain Generation
I'm trying to generate random terrain for my game (In Unity3D, C#). All I need is water and grass. No height to it (no mountains or hills.) I'd preferably like to do it by placing individual cubes. On top of that the terrain needs to be infinite.

I've searched every where for even a hint on how to do it, but everything I found had either height to it, didn't use individual cubes (edited the terrain as a whole), or wasn't infinite.

Any help would be much appreciated! :)

EDIT: I'm looking for something somewhat similar to a game called Factorio. Here's a screenshot: http://i.ytimg.com/vi/Uns15OfPWbo/maxresdefault.jpg As you can see there is a big body of water, and a ton of land. I want to create something that randomly does that every time (random bodies of water and random land shapes). Something like Minecraft without all the height.

I've heard about something called Perlin noise, but because of a lack of tutorials and documentation, I can't figure out for the life of me on how to use it to generate random terrain.

# Answer
> 2 votes
Check noise generation algorithms like simplex or perlin noise(http://en.wikipedia.org/wiki/Perlin\_noise). By combining them you can create intricate fractal noise and by additional processing(like cutting by threshold) you will create distinctive feature maps for grass and lakes(and height maps. So you will definitely accomplish both tasks) to sample against by coordinates which is very handy if you are working with discrete elements like cubes or tiles. More information: https://stackoverflow.com/questions/6091468/how-is-a-3d-perlin-noise-function-used-to-generate-terrain There is nice question too about 2D noise generation: https://stackoverflow.com/questions/8659351/2d-perlin-noise

Btw, things can't be infinite because computing is limited by storage space and datatype resolution used by coordinate system.

---
Tags: c#, unity, terrain
---


# Question
Title: Moving a Sprite using Mouse in SFML (setOrigin logic needed)
I trying to make a card game using SFML. I want to move the card relative to the position the player selects on the card. I managed to check if the card is pressed. However, when I click and drag, the top-left (the origin) of the card is immediately moved to where the mouse is. I tried to set the origin, in the process\_events function, to 'event.mouseButton' (both x and y) each time the card is pressed but it moves to the top-left corner of the screen. I spent a lot of time on this. I hope you guys will help me out.

```
const int card_width = 79;
const int card_height = 123;

Game::Game()
: window(sf::VideoMode(1024, 800), "SFML")
, frame_rate(sf::seconds(1.f / 60.f))
, card(card_sheet, sf::IntRect(0, 0, card_width, card_height))
// 'card' is an sf::Sprite object pointing to an sf::Texture object that holds the sprite sheet.
, selected(false)
{
    card.setPosition(500.f, 400.f);
    card.setOrigin(card_width / 2, card_height / 2);
    // I tried to set the origin to the center of the card.
    // Still doesn't look nice.
}

void Game::process_events()
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type)
        {
            case sf::Event::Closed:
                window.close();
            break;
            case sf::Event::MouseButtonPressed:
                if (event.mouseButton.button == sf::Mouse::Left)
                    if (card.getGlobalBounds().
                                   contains(sf::Mouse::getPosition(window).x,
                                            sf::Mouse::getPosition(window).y))
                    {
                        // the problem is here
                        card.setOrigin(event.mouseButton.x, event.mouseButton.y);
                        selected = true;
                    }

            break;
            case sf::Event::MouseMoved:

                if (selected)
                {
                    // stuff might need to be added here too
                    card.setPosition(sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y);
                }
            break;
            case sf::Event::MouseButtonReleased:
                selected = false;
            break;
            default: break;
        }
    }
}

void Game::update(sf::Time dt)
{
}

void Game::render()
{
    window.clear();
    window.draw(card);
    window.display();
}

void Game::run()
{
    sf::Clock clock;
    while(window.isOpen())
    {
        sf::Time dt = clock.restart();
        process_events();
        update(dt);
        render();
    }
}

```

# Answer
> 1 votes
When you set the origin you have to take into account the position of the card and its previous origin.

```
card.setOrigin(event.mouseButton.x - (card.getPosition().x - card.getOrigin().x),
               event.mouseButton.y - (card.getPosition().y - card.getOrigin().y));

```

I don't really know how to explain, I will try with a drawing.

Your card is the red rectangle: its position is the dark green arrow and its origin is the light green arrow. The position of the click is the blue arrow.

So, when you subtract the light green arrow to the dark green arrow you get the purple arrow. So the purple arrow is `card.position - card.origin`.

Then you subtract that purple arrow to the blue arrow, and you get the pink arrow `mouse.position - (card.position - card.origin)`. And the pink arrow in the new origin of the card, it is at the position where the player clicked with coordinates that are local to the card. i.e. on a card that is at position (0,0) and origin (0,0).

I hope that makes sense.

---
Tags: sprites, sfml
---


# Question
Title: How can I remove Magic Pink from an image at runtime using GraphicsDevice?
In XNA 4.0, I want to load all my textures at runtime, which means I will not be able to take advantage of the content processor. (This is fine because it would allow people to change graphics and other elements without having to have XNA installed to compile them into .xnb)

Suppose that I can't (or don't want to) use premultiplied alpha on my images, and instead rely on the classic magic pink (255, 0, 255) method:

How can I turn it into a `Texture2D` object and convert the pink to be transparent using `GraphicsDevice`? It is trivial to iterate the data with GetData() and SetData(), but this uses the processor, rather than the graphics card.

# Answer
> 8 votes
I would imagine a custom pixel Shader for the SpriteBatch would be the fastest method here.

Using something like this:

```
// WARNING! UNTESTED CODE FOLLOWS
void SpriteVertexShader(inout float4 color : COLOR0, inout float2 texCoord : TEXCOORD0,
                        inout float4 position : POSITION0)
{
    if (color == float4(1, 1, 0, 1)
        color = float4(0, 0, 0, 0)
}

```

In a custom effect passed to your SpriteBatches Begin() method, it should make every pixel with an ARGB value of OxFFFF00FF transparent while keeping any pixel with a different color the same.

I haven't done much work with 2d shaders apart from Post Processing effects, so I'm not exactly sure what values you'll need to pass to Begin() to get transparency working correctly.

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


title: Unity 5 missing Standard Assets

text:
# Question
Title: Unity 5 missing Standard Assets
I have Unity 5 and when I make a new project, there are no assets that are usually there (Character Controller, Terrain, etc.). How do I fix that?

# Answer
Go to http://unity3d.com/get-unity/download?ref=personal click on "ADDITIONAL DOWNLOADS FOR WINDOWS" and select "Standard Assets".
> 3 votes

# Answer
Select `Window` from the top menu, and open the `Asset Store`. On the right hand side of the page there is a list of categories. Select the `Unity Essentials` category. This category contains a number of asset packages published by Unity Technologies. Included in this pack is the `Standard Assets` package.

You'll also find a number of other packages that have great quality assets and they're all free.
> 3 votes

---
Tags: unity, assets
---


title: Tile Map Shader?

text:
# Question
Title: Tile Map Shader?
I'm trying to write a shader in unity that will take tiles from a sprite sheet and draw them onto a tile map.

I'm new to shaders so this might be totally wrong, I think it might just be a math error on my part, but maybe I'm misunderstanding how shaders work.

Here's my Shader:

```
    Shader "Custom/TileMapShader" {
Properties {
    _TileSheet ("Tile_Sheet", 2D) = "white" {}
}
SubShader {
    Pass {
        CGPROGRAM

        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        uniform sampler2D _TileSheet;
        uniform float2 _MapSize;

        struct vertexInput {
            float4 vertex : POSITION;
            float2 texcoord: TEXCOORD0;
            float4 tilecoord : TEXCOORD1;
        };

        struct vertexOutput {
            float4 pos : SV_POSITION;
            float2 tex: TEXCOORD0;
            float2 tileIndex : VECTOR;
        };

        vertexOutput vert (vertexInput v)
        {
            vertexOutput output;

            output.pos = mul (UNITY_MATRIX_MVP, v.vertex);
            output.tex = v.texcoord;
            output.tileIndex = v.tilecoord.xy; // <-- Using UV2 might be a bit hacky
                                               //     to get the tile index but it
                                               //     seemed better than creating a
                                               //     texture to do it...

            return output;
        }

        float4 frag (vertexOutput i) : SV_Target
        {
            int xTile = (i.tileIndex.x * 16);
            int yTile = (i.tileIndex.y * 16);

            float2 uv = float2(xTile, yTile + 1) / 16;

            float xoffset = frac( i.tex.x * _MapSize.x ) / 16;
            float yoffset = frac( i.tex.y * _MapSize.y ) / 16;

            uv += float2( xoffset, -yoffset );

            uv.y = 1.0 - uv.y;

            return tex2D(_TileSheet, uv);
        }

        ENDCG
    }
}
    }

```

I stumbled across this http://connorhollis.com/code/fast-tilemap-shader/ and modified it to get what I have above.

this is how I create my Mesh: (I don't think this is the issue but who knows)

```
    void BuildMesh()
{
    int numTiles = (int) (mapSize.x * mapSize.y);
    int numTris = numTiles * 2;

    int vsize_x = (int)mapSize.x + 1;
    int vsize_z = (int)mapSize.y + 1;
    int numVerts = vsize_x * vsize_z;

    // Generate the mesh data
    Vector3[] vertices = new Vector3[numVerts];
    Vector3[] normals = new Vector3[numVerts];
    Vector2[] uv = new Vector2[numVerts];

    //Tiles
    _tileMap = new Vector2[numVerts];

    int[] triangles = new int[numTris * 3];

    int x, z;
    for (z = 0; z < vsize_z; z++)
    {
        for (x = 0; x < vsize_x; x++)
        {
            vertices[z * vsize_x + x] = new Vector3(x * TileSize, 0, -z * TileSize);
            normals[z * vsize_x + x] = Vector3.up;
            uv[z * vsize_x + x] = new Vector2((float)x / (int)mapSize.x, 1f - (float)z / (int)mapSize.y);
            //Tiles TEMP
            switch (Random.Range(0, 2))
            {                                             // Tile Selection
                case 0:                                   // X              Y
                    _tileMap[z * vsize_x + x] = new Vector2((1 * 0.0625f), (0 * 0.0625f));
                    break;
                case 1:
                    _tileMap[z * vsize_x + x] = new Vector2((2 * 0.0625f), (0 * 0.0625f));
                    break;
            }

        }
    }

    for (z = 0; z < (int)mapSize.y; z++)
    {
        for (x = 0; x < (int)mapSize.x; x++)
        {
            int squareIndex = z * (int)mapSize.x + x;
            int triOffset = squareIndex * 6;
            triangles[triOffset + 0] = z * vsize_x + x + 0;
            triangles[triOffset + 2] = z * vsize_x + x + vsize_x + 0;
            triangles[triOffset + 1] = z * vsize_x + x + vsize_x + 1;

            triangles[triOffset + 3] = z * vsize_x + x + 0;
            triangles[triOffset + 5] = z * vsize_x + x + vsize_x + 1;
            triangles[triOffset + 4] = z * vsize_x + x + 1;
        }
    }

    //Populate mesh with the data
    _mesh.vertices = vertices;
    _mesh.triangles = triangles;
    _mesh.normals = normals;
    _mesh.uv = uv;
    _mesh.uv2 = _tileMap;

    _material.SetVector("_MapSize", new Vector4(mapSize.x, mapSize.y));
}

```

And this is how it all ends up looking

and this is the tile sheet I'm using to test. There are 16x16 tiles, and each tile is 16x16 pixels

https://i.stack.imgur.com/zzQpJ.png

Thank you for the Help, I've been stuck on this for a few days now, I tried to keep things short and to the point.

# Answer
It turns out it was the Mesh creation and the shader was working fine.

In my above example vertices are shared between different tiles, below vertices are only shared between the 2 triangles that make each tile.

```
        void BuildMesh()
{
    Vector3[] vertices = new Vector3[(int) mapSize.x * (int) mapSize.y * 4];
    Vector3[] normals = new Vector3[vertices.Length];
    Vector2[] uv = new Vector2[vertices.Length];

    _tileMap = new Vector2[vertices.Length];

    int[] triangles = new int[vertices.Length * 6];

    float width =  (int)mapSize.x;
    float height = (int)mapSize.y;

    float x, z;
    for (z = 0; z < mapSize.y; z++)
    {
        for (x = 0; x < mapSize.x; x++)
        {
            int squareVal = (int)((z * width + x) * 4);

            vertices[squareVal + 0] = new Vector3(x, 0, -z);
            vertices[squareVal + 1] = new Vector3(x + 1, 0, -z);
            vertices[squareVal + 2] = new Vector3(x, 0, -z - 1);
            vertices[squareVal + 3] = new Vector3(x + 1, 0, -z - 1);

            normals[squareVal + 0] = Vector3.up;
            normals[squareVal + 1] = Vector3.up;
            normals[squareVal + 2] = Vector3.up;
            normals[squareVal + 3] = Vector3.up;

            uv[squareVal + 0] = new Vector2((x + 0f) / width, 1f - (z + 0f) / height);
            uv[squareVal + 1] = new Vector2((x + 1f) / width, 1f - (z + 0f) / height);
            uv[squareVal + 2] = new Vector2((x + 0f) / width, 1f - (z + 1f) / height);
            uv[squareVal + 3] = new Vector2((x + 1f) / width, 1f - (z + 1f) / height);

            _tileMap[squareVal + 0] = Vector2.zero;
            _tileMap[squareVal + 1] = Vector2.zero;
            _tileMap[squareVal + 2] = Vector2.zero;
            _tileMap[squareVal + 3] = Vector2.zero;

            int triangleVal = squareVal * 6;

            triangles[triangleVal + 0] = squareVal + 0;
            triangles[triangleVal + 1] = squareVal + 1;
            triangles[triangleVal + 2] = squareVal + 2;

            triangles[triangleVal + 3] = squareVal + 1;
            triangles[triangleVal + 4] = squareVal + 3;
            triangles[triangleVal + 5] = squareVal + 2;
        }
    }

    //Populate mesh with the data
    _mesh.vertices = vertices;
    _mesh.triangles = triangles;
    _mesh.normals = normals;
    _mesh.uv = uv;
    _mesh.uv2 = _tileMap;

    _material.SetVector("_MapSize", new Vector4(mapSize.x, mapSize.y));
}

```

and to set a tile I do this for each tile

```
void setTile(Vector2 tile, Vector2 sprite)
{
    int squareVal = (int)((tile.y * mapSize.x + tile.x) * 4);

    _tileMap[squareVal + 0] = sprite * 0.0625f;
    _tileMap[squareVal + 1] = sprite * 0.0625f;
    _tileMap[squareVal + 2] = sprite * 0.0625f;
    _tileMap[squareVal + 3] = sprite * 0.0625f;
}

```

and call this when I want to push the changes.

```
    _mesh.uv2 = _tileMap;

```
> 1 votes

---
Tags: c#, unity, tilemap, fragment-shader, cg
---


title: OpenGL VBO and VAO Confusion

text:
# Question
Title: OpenGL VBO and VAO Confusion
I would like to present here my Question about VBOs and VAOs. Basically from what i understand you can have different VAOs each of which can contain up to several VBOs , and by binding to the VAO's ID you can draw from the VBOs stored inside.

I have Wrote a simple class that reads a obj file then creates vertices, normals and uvs vector lists and upload those in 3 VBOs (vboID 1,2 and 3)

```
void Model::loadToVBO()
{
glGenVertexArrays(1, &vaoID);
glBindVertexArray(this->vaoID);

glBindBuffer(GL_ARRAY_BUFFER, vertexID);
glBufferData(GL_ARRAY_BUFFER, this->vertices.size()*sizeof(vec3), &this->vertices[0], GL_STATIC_DRAW);

glBindBuffer(GL_ARRAY_BUFFER, normalID);
glBufferData(GL_ARRAY_BUFFER, this->normals.size()*sizeof(vec3), &this->normals[0], GL_STATIC_DRAW);

glBindBuffer(GL_ARRAY_BUFFER, uvcoordID);
glBufferData(GL_ARRAY_BUFFER, this->uvs.size()*sizeof(vec2), &this->uvs[0],      GL_STATIC_DRAW);

glBindVertexArray(0);
}

```

if I do that in the render function i try to Bind to vaoID , and draw elements , but it would not work. To make it work i have to RELOAD vbo data every frame in Render Function (that happens because i have 2 models each model's constructor calls loadVBO , and obviously the second model overrides the first vbo's 1,2 and 3 ID positions(i was assuming that the vao generated from the first object will be entirely separate from the vao generated from the second model and each vao will have its own 3 VBOs). So maybe my code doesnt setup VAOs properly. Was reading something about how glEnableVertexAttribArray and glVertexAttribPointer are used to set up current vbo state into vao , but could not understand it really well. Maybe because i use the same functions to bind to shaders variables ....

This code below is in the shader class and it loads the vbo data into shader's variables

```
void StaticShader::loadAttribute(GLuint bufferID, string variable, GLuint size)
{
GLuint variableID;
variableID = glGetAttribLocation(this->shaderProgramID, variable.c_str());
glBindBuffer(GL_ARRAY_BUFFER, bufferID);
glEnableVertexAttribArray(variableID);
glVertexAttribPointer(variableID, size, GL_FLOAT, GL_FALSE, 0, 0);
}

```

The Model Render Functions looks like that. The loadToShader function loads: all model matrices + vertices + normals + uvs This function calls the function loadAttribute for v, n and uvs ( i assume thats not where its supposed to be ... maybe)

```
void Model::Render()
{
glBindVertexArray(vaoID);
//loadToVBO();
loadToShader();
glDrawArrays(GL_TRIANGLES, 0, this->vertices.size());
glBindVertexArray(0);
}

```

My question is - Is it Bad (performance wise) to load VBO data every time render is called (i assume YES). Second part - Should i reload model data(meaning v/n/uvs) in shader every time its called to be rendered ?

# Answer
Yes, sending your mesh data to the GL every time you render it would be very wasteful. You should only be doing that if your data has changed from one frame to another (e.g. you are computing animations in the CPU). Otherwise, you shouldn't have to re-submit data if the model/mesh was not changed.

Apparently, the problem with your program is that you are not setting the vertex layout when the VAO is created. Usually, the workflow of VAOs is:

* On initialization:

1. Create the VAO and bind it;
    2. Create buffers, bind them and submit data with `glBufferData`/`glMapBuffer`;
    3. Set vertex layout with `glEnableVertexAttribArray` and `glVertexAttribPointer`;
    4. Optionally unbind the VAO and buffers to avoid programming errors.
* On rendering:

1. Bind the VAO;
    2. Issue the draw call(s);
    3. Optionally unbind the VAO to avoid programming errors.

So the fix for your problem might be achieved rearranging the calls to `glVertexAttribPointer`. I see that you are querying the attribute locations from the shader. You might wish to specify your own locations with `glBindAttribLocation` before compiling the shader, to make things simpler. Another even better option is directly specifying the locations in shader code using the `layout(location)` qualifier. You'll have to check if the latter is available in your version of GLSL.
> 6 votes

---
Tags: opengl, c++, shaders, vbo, vao
---


# Question
Title: opengl : Running at least 25 windows with different Draw callback
I need to run at least 25 windows concurrently with each window rendering a different game state. I am storing all the 25 game states in the array of type GameState allGameStates\[25\].

For each of the window, i am currently doing this to register a different draw callback for each of the 25 windows.

```
 glutCreateWindow(title);
 glutDisplayFunc(allGameStates[i].Draw);

```

The issue here is that glutDisplayFunc requires a parameter of type function ptr, and i cannot pass in a member function ptr.(i am using GLUT which is in C)

It is not feasible to make the Draw function static as i require the Draw function to render differently accordingly to the other variables in the game state object.

How do i overcome this problem?

# Answer
> 4 votes
According to the documentation for `glutDisplayFunc()`:

> Before the callback, the current window is set to the window needing to be redisplayed

This means that inside the display callback, you can call `glutGetWindow()` to find out which window is being drawn to.

This means that you *can* use a static member function as the display callback; just have that static member function figure out which window is being drawn to, and map from that window to its particular game state object instance, and then call a non-static member function on that instance.

---
Tags: opengl, c, window-management
---


# Question
Title: Is it better to use an image component or to draw on a canvas?
I am developping a small 2D RPG with JavaFX, although my question might apply to any toolkit or even any language for the matter.

I have two choices to display the characters, the scenery, the items and other displays such as a life bar or an inventory:

1. Put them in `imageView` printed on top of a background.
2. Draw them directly on the canvas (`graphicsContext`) of the background.

Which is the best practice? Is there a significant difference in term of speed, for example?

# Answer
Whichever option is easier for you to work with, you are unlikely to push the hardware limits with a 2d game so you should get a good framerate with either approach.

Using a Group and place components in it means you can detect mouse clicks on each element the same as any other JavaFX control.

Drawing into a Canvas is more similar to how a fully fledged OpenGL/DirectX game would work, and it's also much more like how HTML5/Javascript would work if you ever want to make a web version of your game. But you lose all built in JavaFX control support and have to calculate what element the user clicks on or performs drag drop with yourself.

If you wish to make more advanced graphics later on I would go for the latter option, but only if your not sure which option to pick, otherwise go with whatever your leaning towards already.
> 1 votes

---
Tags: sprites, image
---


# Question
Title: Does game engines (like Unreal, Unity, Crafty) add value compared to pure js frameworks (react, ember..) for my isometric tile-based games
I'd like to create a huge tile-based board (say 100K tile). The game does not have any advanced graphics (you don't see the players or landscapes), the main difficulty is that it has 100K tiles to show; something like this (but with many more tiles) or like this

Also, I can't use any technique like in minecraft where I only show smaller "regions" at a time of the map - *all* of the map has to be shown on the screen at once (people will zoom)

Would a game engine (unity, unreal, crafty, etc) add anything *compared* to pure javascript frameworks (react, ember, etc) if the only thing you are using them for is to render a tile based board (no animated graphics or characters moving on the screen)? With each tile only showing the state of a tile (occupied or not).

I might need collision detection as 2 players can't be on the same tile (note: I don't think it would be too hard to do this in javascript) And maybe GPU acceleration out of the box?

# Answer
> 2 votes
The main importance in a case like this is to be able to use hardware acceleration and being able to upload your map to the GPU for smooth zooming.

Usually using a game engine tends to restrict how you access the hardware, whereas using OpenGL/WebGL directly will not get in your way (but also won't assist you with common tasks either).

In this case it sounds like you want to upload your map into a buffer/texture, then render it with a specialized fragment shader, alternatively using instancing to render all those squares. With that in mind you probably won't be getting any assistance from an engine (although they may have some map implementation that you could use).

With 100k elements you can store each element as a byte in a texture/buffer and it would only take up 100kb of memory, textures commonly are 4Mb or larger for detailed meshes.

```
// Create and initialize the WebGLTexture object.
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

var data = UInt8Array(256*256);

for(var x = 0; x < 256; x++) {
  for(var y = 0; y < 256; y++) {
    data[x*256 + 6] = (x + y) % 2;
  }
}

gl.texImage2D(gl.TEXTURE_2D, 0, gl.GL_RGBA, 256, 256, 0, gl.GL_RGBA,
              gl.GL_UNSIGNED_BYTE, data);

```

The code is untested but after the texImage2D call you have the texture loaded with your values from the for loops and can use that in your fragment shader. Updating the picture every frame should be doable.

Another option is to have a point list of the claimed tiles that you add more and more points to, this would reduce the amount of data to upload since you just append to the end of the buffer, but it is a little bit more complex.

---
Tags: 2d, memory-efficiency
---


# Question
Title: How to calculate Pong ball's expected position perfectly (taking wall bounces into account)
I'm writing a Pong clone where the player has to type a word in order to move the paddle. Because of this, I need a way to calculate the position of the ball immediately after it hits the CPU's paddle. For each letter the player types correctly, the paddle will move a little bit so that when the player finishes the word, the paddle is waiting for the ball to come. It needs to be very accurate, and relatively fast.

I was considering just simulating a much faster ball and figuring out where it will end up (the time it arrives is not important, but the position is). I'm worried that I'll run into problems down the line when the game speed starts ratcheting up, and the actual ball is going as fast as the simulated one. This normally wouldn't be an issue, but the way the whole typing thing works kinda relies on it.

The tough part of just using an equation to find the ball's position is the existence of walls. An equation would be preferable to a quick simulation/extrapolation but I fail to see how it would be done.

Thanks so much for any insight.

# Answer
> 2 votes
I would try to use raycasting.

* Cast a ray in the direction the ball will be going.
* If it hits any kind of obstacle, then reflect this vector along the hitpoint's normal.
* Cast a new ray int he reflected direction .
* Repeat until the ball hits the "goal zone".

In the end the last hitpoint's coordinates give where you paddle should be.

This should be quite straightforward if you have a physics engine, also reliable and flexible(until you start to add moving objects, then you'll probably need a faster simulation as you said)

# Answer
> 0 votes
To achieve integrity between user success by typing and pong mechanic you need to 'cheat' a little. Otherwise you will encounter problems when under corner cases(quite literally) ball will be predicted incorrectly.

The concept is:

1)Make the ball own the object defining the Path and its properties like current speed per simulation step.

2)Then use math to simulate several steps ahead considering each paddle is in perfect position to reflect incoming projectile(there are pong games where position of paddle defines angle of ball reflection but I doubt this feature being to be good where player doesn't directly control the paddle)

3)Each simulation step move ball through the path and when it reaches reflection point check if paddle is able to reflect the ball or not. If yes - make it continue path(you can acknowledge reflection with sound to make it more evident) and if not - make it fall beyond the paddle and mark the game to be loosed by party failed to reflect.

This will give a fine control on when AI should fail and where to expect the ball far ahead in time for player.

For specific algorithms of raytracing and reflection consider checking StackOverflow. Like this: https://stackoverflow.com/questions/4030565/line-and-line-segment-intersection

# Answer
> 0 votes
I would run the game simulation in a tight loop with fixed timestep, adding the changes to a linked list as I go, until the ball reaches the "point of no return".

Not only do you now know where the paddle should be to bounce the ball correctly, but you can also tell exactly how long the player has to type the word so you can pick a word of suitable length to make the games difficulty curve correct (instead of accidentally giving "Machiavellian" when the ball will bounce right back to the paddle in a second).

As the game carries on you simply use the linked list to pull out the next spot the ball will be in instead of calculating it, that way you are 100% accurate in your prediction since you run the simulation only once.

You will probably have no difficulty whatsoever running the entire path without giving a visual glitch in the game since most pong levels aren't too big, but if you have any issues then simply calculate the path for the next word while the game is displaying the current words action, either in a background thread or by limiting the amount of time spent in your tight loop so it never drops below 60fps.

```
void update() {
  timeS = time();
  while (time() - timeS < 1000/60 && !simulationComplete()) {
    simulatedTime += timestep;
    ball.pos += ball.velocity;
    brick = ball.performCollision();
    actions.add(simulatedTime, ball.position);
    if (brick != null) {
      actions.add(simulatedTime, brick);
    }
  }
}

```

---
Tags: extrapolation
---


# Question
Title: LibGdx: How to check if VSync is enabled
I am just about finished my options screen, the only thing I need is some way of detecting if Vsync is enabled or not.

I'm using LibGdx 1.5. I have tried to find an access to wglSwapIntervals, but haven't found one. Libgdxs API only allows a setVsync options that accepts a Boolean.

If anyone could shed some light on this, it would be greatly appreciated!

# Answer
Why not just set the VSync to on at the start of your game and create a variable within your code that will store the VSync boolean. Then if a user changes their VSync settings you update your variable as well. This will also allow you to save a user's VSync option because you can store your boolean when the game exits and when it restarts, set VSync to the stored variable.
> 0 votes

---
Tags: libgdx, vsync
---