# Question
Title: how to set in vector float x y coordinates
i am use eclipse java android i am try to projectile trajectory in my game like angry birds example here http://blog.gemserk.com/2012/07/03/drawing-a-projectile-trajectory-like-angry-birds-using-libgdx/

this is my code error - x cannot be resolved or is not a field \- y cannot be resolved or is not a field

how to solve this problem

```
class ProjectileEquation {

    public float gravity;
    public Vector<E> startVelocity = new Vector<E>();
    public Vector<E> startPoint = new Vector<E>();

    public float getX(float t) {
        return startVelocity.x * t + startPoint.x;
    }

    public float getY(float t) {
        return 0.5f * gravity * t * t + startVelocity.y * t + startPoint.y;
    }

}

```

# Answer
It is at it says, java.util.Vector does not a field named x or y. It is probably not the class you want to be using here. java.util.Vector is close to ArrayList and is meant to store a list of items in a thread-safe manner. So I recommend writing you own vector class instead.

Here is an example

```
public class Vector2f {
    public float x;
    public float y;
}

```

You should be able to use this in you code instead.
> 1 votes

---
Tags: java, android, vector, bullet-physics
---


# Question
Title: OpenGL — Better to switch out material or shader for changing object colors?
I'm fairly new to shaders and OpenGL so bare with me please, I just want to make sure I'm doing it correctly! Now I'm using **LibGDX** in order to create a simple 3d diagram for my company. I have a few models that I need to display as grey until they are active, where they will fade to a brighter blue, probably gain some emission value so that they're brighter.

Now, when I export my models from Blender to .fbx, and then run Fbx-Conv to generate .g3dj files, I get some output like the following:

```
"materials": [
    {
        "id": "glowy_blue_material",
        "ambient": [ 0.000000,  0.000000,  0.000000],
        "diffuse": [ 0.000000,  0.753256,  1.000000],
        "emissive": [ 0.000000,  0.753256,  1.000000],
        "opacity":  0.592209,
        "specular": [ 0.000000,  0.759441,  1.000000],
        "shininess":  9.607843,
        "textures": [
            {
                "id": "Texture",
                "filename": "heat_exchange_uv_edge_highlight.png",
                "type": "DIFFUSE"
            }
        ]
    }
]

```

Which is all good and displays what I want, but I've been reading about shaders the past few days and see that in a lot of cases LibGDX suggests extending the default shader and making tweaks that way.

From a computational point of view, what is the best way to go about **switching colors of models**? Extending the default shader with some logic about if x is inactive, change shader to render as greyscale, else render as normal blue material? Or should I create a greyscale version of the material and switch them out? ( *I'm not quite sure how to do this, also, because I apply the material in the g3dj file — could I do this in Java instead of the g3dj file? Does it cause a performance hit? If anyone could point me in the direction of some documentation somewhere..* )

Any help would be appreciated. Thanks!

# Answer
> 1 votes
If you want to make everything black and white, use a post processing shader. Otherwise, it can be a simple line in you shader. In hlsl (directx) this would be something like:

```
if (greyscale)
{
  float tint = (color.r+color+g+color.b)/3;
  color.rgb = tint;
}

```

I assume this would also work in OpenGL.

# Answer
> 1 votes
To preserve performance, you should change the material setting in java rather than a "if" statement of the shader.

You can access the material the objects after the config file has been loaded using the functions described here

Hope it helps

---
Tags: opengl, java, libgdx
---


# Question
Title: How much latency can I expect from Apple Game Center connections?
I would need a few bytes of data roughly every 0.1 seconds between players to have a smooth multiplayer snake game on iOS.

Is the iOS Game Center fast enough for this? What latency values can I expect?

# Answer
I'm currently working on a real time pong type game using game center and it is more than fast enough to handle it, it should be fine for snake as long as you test that the connection between the players is good enough
> 0 votes

---
Tags: game-center, latency
---


# Question
Title: LWJGL3 Input for single press of keyboard
I am making a game with lwjgl and GLFW and am having a hard time figuring out how to check for a single press on the keyboard.

# Answer
I figured this out on my own eventually. So I used the GLFWKeyCallback method and created something like this.

```
private static List<Integer> pressed = new ArrayList<Integer>();
private static boolean[] keys = new boolean[65536];

public static boolean isPressed(int key){
    return keys[key];
}

public static boolean isClicked(int key){
    if (!keys[key]) return false;
    if (pressed.contains(new Integer(key))) return false;
    pressed.add(new Integer(key));
    return true;
}

public static void glfwKeyCallback(long window, int key, int scanCode, int action, int mods){
    keys[key] = action != GLFW_RELEASE;
    if(action == GLFW_RELEASE && pressed.contains(new Integer(key))) pressed.remove(new Integer(key));
}

```
> 1 votes

---
Tags: lwjgl, glfw
---


# Question
Title: Understanding Javascript Variable Initialization
I saw this piece of code while doing research for an idle game I am making:

```
var minions = new Object;
minions = {
    0: {
        name: "Mole",
        description: "...",
        price: 10,
        priceModifier: 1.5,
        attributes: {
            goldPerSec: 1
        }
    },
    1: {
        name: "Bulldog",
        description: "...",
        price: 1e3,
        priceModifier: 1.5,
        attributes: {
            goldPerSec: 70,
            diamondsPerSec: .5
        }
    },
    2: {
        name: "Giant Ant",
        description: "...",
        price: 1e5,
        priceModifier: 1.5,
        attributes: {
            goldPerSec: 700,
            diamondsPerSec: 3
        }
    },
    3: {
        name: "A.W.E.S.O.M.-O 2000",
        description: "...",
        price: 1e6,
        priceModifier: 1.3,
        attributes: {
            goldPerSec: 5e3,
            diamondsPerSec: 20
        }
    },
    4: {
        name: "Caterpillar",
        description: "...",
        price: 8e7,
        priceModifier: 1.3,
        attributes: {
            goldPerSec: 3e4,
            diamondsPerSec: 100
        }
    },
    5: {
        name: "Pterodactyl",
        description: "...",
        price: 19e8,
        priceModifier: 1.3,
        attributes: {
            goldPerSec: 85e3,
            diamondsPerSec: 400
        }
    },
    6: {
        name: "Miner Spaceship",
        description: "...",
        price: 29e9,
        priceModifier: 1.3,
        attributes: {
            goldPerSec: 5e5,
            diamondsPerSec: 2700
        }
    },
    7: {
        name: "The dwarf King",
        description: "...",
        price: 3e11,
        priceModifier: 1.3,
        attributes: {
            goldPerSec: 3e6,
            diamondsPerSec: 16e3
        }
    },
    8: {
        name: "Spirit Golem",
        description: "...",
        price: 5e13,
        priceModifier: 1.3,
        attributes: {
            goldPerSec: 25e6,
            diamondsPerSec: 98e3
        }
    }
};

```

And I have a small idea of what is being done here but my question is how would this code be handled or triggered.

Really all I need is the name for what this is, and I can take it from there :)

# Answer
What you're looking at is an in-line initialization of an associative array (which functions similarly to a dictionary or map in other languages). If you made a variable in javascript like so:

```
var phones = {};

```

Then added *values* (right hand side) to *keys* (after the dot on the left)

```
phones.Steve = '2342311';
phones.Kyle = '3230009';

```

You will have an associative array (technically everything in javascript is an associative array but lets move on) with two keys. If you've never used them, read about javascript arrays. Continuing on to what you're seeing, my same 3 lines of code can be written like this:

```
var phones = { Steve: '2342311', Kyle: '3230009' };

```

Now, the *keys value pairs* are inside of brackets and separated by commas. When you see something like your example:

```
minions = {
0: {
    name: "Mole",
    ...
    attributes: {
        goldPerSec: 1
    }

```

`0` is a key for `minions` with a value of another array (this concept is known in languages as a *nested array* or *two dimentional arrays*). `attributes` is an even more deeply nested array.

To use all of this, say you wanted that `goldPerSec` value, you'd retrieve it like this:

```
var gps = minions[0].attributes.goldPerSec;

```
> 4 votes

---
Tags: javascript, architecture, jquery
---


title: Newton physics "hiding" rigid bodies

text:
# Question
Title: Newton physics "hiding" rigid bodies
It seems like creating a bunch of rigid bodies (say 100K) causes a huge slowdown. However, what if the model the rigid body is attached to isn't visible. Is there a way to remove the rigid body from any sort of iteration from Newton so it doesn't cause a slowdown during run-time?

# Answer
> 1 votes
> Is there a way to remove the rigid body from any sort of iteration from Newton so it doesn't cause a slowdown during run-time?

Yes!

To prevent wasting CPU power on mathematically intensive *Narrow Phase* calculations, all good physics engines will implement some form of *Broad Phase* detection. This could include spatial partitioning like octrees and bounding spheres.

If desired, this concept of reducing calculations via *Broad Phase* can be taken one step further, beyond collisions, to completely remove a rigid body from any kinematic calculations entirely if that's desired.

# Answer
> 0 votes
Depending on which physics system you use it may be that rigid bodies can be disabled, removed from the world or destroyed and recreated. It depends entirely on the system you are using.

Generally inactive or not yet spawned objects are not added to the world until needed. However as one person noted the hidden object won't get any collisions or simulation.

As an aside I wonder are you creating all the bodies on top of each othet? Any engine will be slow if forced to evaluate many bodies overlapping at once.

---
Tags: physics
---


# Question
Title: Mesh-level acceleration structures for collision detection when mesh instances can be rotated, scaled and/or resized
Short version: in the mid-phase or narrow-phase of collision-detection, does any acceleration structure organizing the mesh's vertices (e.g. AABB-trees, Octrees, Quadtrees) work for the mesh's instances that are re-scaled, re-sizes and/or rotated?

Long version: suppose a concave mesh composed of a very high number of triangles (e.g. 200k) and for which I cannot use convex decomposition in order to perform collision detection. The most efficient solution usually employed would be to organize the vertices of the mesh using acceleration structures to quickly prune which parts of the mesh are likely to have been collided with.

However, that mesh is used for generating instantiated copies - and each of these can have different size, rotation and/or scale at any of the X,Y,Z axis. Would any acceleration-structures work since the instances can be re-scaled, rotated and resized? Suggestions, tips, academic references, are all appreciated.

# Answer
The best option is to perform all the mid and narrow phase in the local space of the instanced mesh object.

Most collision detection algorithms air pair-wise using two matrices, one for each objects transform. In this case create an inverse matrix from the instanced object's matrix and concatenate it with the other objects matrix. This effectively moves the collision detection into the local space of the instanced object. After detection is performed multiply the results by the instanced objects transform to get the results in world space. This removes the need to move every triangle into world space. It also allows you to use an acceleration structure shared with each instance.

Some pair-wise detection algorithms require extra treatment when dealing with scale but this is certainly where I would start.
> 1 votes

---
Tags: collision-detection, instancing
---


title: 2D Collision Response

text:
# Question
Title: 2D Collision Response
I am trying to implement collision response in my libgdx game. I'm using Rectangle objects as my bounbing boxes. This makes collision detection very easy, however I can't quite get the response working correctly. At the moment I have this:

```
float overlapX = getOverlap1D(dynamicBounds.x, dynamicBounds.x + dynamicBounds.width, blockBounds.x, blockBounds.x + blockBounds.width);
float overlapY = getOverlap1D(dynamicBounds.y, dynamicBounds.y + dynamicBounds.height, blockBounds.y, blockBounds.y + blockBounds.height);

if (overlapX < overlapY)
{
      if (dynamic.getVelocity().x < 0)
      {
            dynamic.getPos().add(overlapX, 0);
      }
      else
      {
            dynamic.getPos().sub(overlapX, 0);
      }
      dynamic.setVelocityX(0);
}
else
{
      if (dynamic.getVelocity().y < 0)
      {
            dynamic.getPos().add(0, overlapY);
      }
      else
      {
            dynamic.getPos().sub(0, overlapY);
      }
      dynamic.setVelocityY(0);
}

private float getOverlap1D(float min1, float max1, float min2, float max2)
{
    return Math.max(0, Math.min(max1, max2) - Math.max(min1, min2));
}

```

Using this, corners are handled in a very unpleasant way, resulting in less than extraoridnary results like this. Where am I going wrong that allows this to happen?

# Answer
> 1 votes
It's a rather old question, so the OP probably solved it already, but for those who might stumble here, there are my 2 cents.

I didn't made a thorough check of all the code, but the first obvious mistake I have spotted in the OP's code, is that he is using the *overlap* to compute the collision response. It might or might not be the culprit, but it's wrong IMHO. The value to compute should be the *compenetration*, which is similar to the overlap, but not the same in some edge cases (e.g. *when high speed or a low framerate prevents a correct collision response* and the object is now "inside" the one it's colliding with. Not this case, but still...).

Second, from the video I have also noticed that the "player" is sort of "sucked" in the object he's colliding with (maybe a signs problem of sorts? Are you sure the bodies in the the ifs are not inverted?). A word to the wise: **wire some graphic debugging in your game**: a couple of vectors with the values of speed and acceleration, coupled with a way to slow the simulation 10x or 20x will do wonders for your understanding of what's going on.

Even better: write all values to a file and do some post-game analysis with gnuplot/excel/whatever is an invaluable tool.

Hope this helps

# Answer
> 0 votes
Why don't you just use the rectangle class for this?

```
if (tileRectangle.overLaps(playerRec))
{
    //Overlapping, do not move in the direction you currently want.
}

```

Since you are using a tilemap you do not have to check each and every rectangle. Just the ones around the player. You setup a `y` loop with a inner `x` loop and set the start and end coordinates in it. This way you just have to check 9 tiles each loop or maybe 12 since you sprite is a bit bigger.

Once you have a overlap with other rectangles you can check check more precisely what is happening. You only ever have to check 2 direction because if the sprite is moving down and right the collision could never have been taking place above or at the left of the object.

So let's assume the player moves right and due to gravity (simulating or not) was pressed down as well and collided with something. So we have to check the bottom of the character and the right of the rectangle/character.

```
Vector2 bottomLeft = new Vector2(playerRec.x, playerRec.y);
Vector2 bottomRight = new Vector2(playerRec.x + playerRec.width, playerRec.y);
Vector2 topRight = new Vector2(playerRec.x + playerRec.width, playerRec.y + playerRec.height);

```

Now we check the bottom and right points independently so if we just detect a collision at the bottom we keep moving to the right

```
for (Rectangles r : rectanglesYouJustColidedWith)
{
    if(r.contains(bottomLeft) || r.contains(bottomRight)
    {
        //bottom collision you should not increase the y of the player.
        //You could however set is to the height of the rectangle + player height offset
    }
//If we use the same vector as the above for checking the right we would always hit true when we just have a bottomRight collision.
//So we need a offset, this could also function as a step height the player can climb.
//You should offset this step offset by the amount your point went into the colliding rectangle, otherwise the point could still be inside the bottom rectangle.
//Rectangle
     if(r.contains(topRight) || r.contains(new Vector2(bottomRigth.x, bottomRight.y + stepheight)
    {
        //side collision you should not alter x of the player.
    }
}

```

Perhaps you can go with only 4 points if you do not have tiny gaps in your level. For bottom you only have to check the bottom middle and for right only the right center.

It all comes down to fine tuning this to your own liking. But these are the basics. You have to do the same for the top and the left, just wrap them in a statement like `if (player moves left) checkThe corresponding collision`.

---
Tags: libgdx, collision-resolution
---


# Question
Title: Touch taps only on very short flicks on Win7 with Monogame
I have an application on win7 which needs to support touch and mouse input using monogame. But reading touch taps proves to be a very hard thing.

The TouchPanel is initialized like this:

```
TouchPanel.EnableMouseTouchPoint = true;
TouchPanel.EnabledGestures = GestureType.Tap | GestureType.DoubleTap | GestureType.Hold | GestureType.Pinch |
                             GestureType.FreeDrag | GestureType.DragComplete | GestureType.Flick | GestureType.HorizontalDrag |
                             GestureType.VerticalDrag;
TouchPanel.EnableMouseGestures = true;

```

Without EnableMouseTouchPoint and EnableMouseGestures there is no reaction from the touchscreen. Enabling both will at least get me touch locations and gestures on drag moves (this already makes me think that there is something essential missing here).

I have the following code to read input which is called on every Update:

```
private void GetInput(GameTime gameTime)
    {
        var gesture = default(GestureSample);
        MouseState mouseState = Mouse.GetState();

        TouchCollection touchCol = TouchPanel.GetState();
        foreach (var touch in touchCol)
        {
            Console.WriteLine(touch.Position);
        }

        while (TouchPanel.IsGestureAvailable)
        {
            gesture = TouchPanel.ReadGesture();
            Console.WriteLine(gesture.GestureType);
            if (gesture.GestureType == GestureType.Tap)
            {
                DoHitTest(mouseState.X, mouseState.Y);
            }
        }
     }

```

The touch collection will remain empty until the finger is dragged across the screen. Taps are not showing up. To get an actual tap i have to do a very short flick. In this case, there is a touch in the touch collection.

What am i missing? Am i doing something fundamentally wrong here?

# Answer
I just had this same problem with Monogame on Windows 7. The problem is that Win7 doesn't support `WM_POINTERxxx` messages, but instead sends `WM_TOUCH` messages (which are not handled by MonoGame). And for some reason, short flicks get translated into fake mouse events which are then picked up by MonoGame.

There are two solutions:

1. Decide to use Windows 8 and skip support for Windows 7, or
2. Register the window for legacy touch events by p/invoking `RegisterTouchWindow` from user32, and then add handlers for `WM_TOUCH`, as described in this article.

Even after doing this, depending on your touch screen driver, you might get awkward touch events now and then (like the long-press right click, which seems impossible to disable in Windows 7). Which is the reason why XNA initially chose not to support touch on desktops (prior to Windows 8 which introduced proper touch handling).
> 1 votes

# Answer
I have a game using MonoGame that supports touch and mouse. It is sort of a hack. Essentially I use conditionals to see if it is a touchscreen. If it is, I use `gst = TouchPanel.ReadGesture();`. If not, I "fake" the gesture by detecting the mouse state and coding it accordingly:

```
#if (!WINDOWS_APP)
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gst = TouchPanel.ReadGesture();
#else
            int use = 0;
            while (use < 1)
            {
                use++;
                MouseState ms = Mouse.GetState();
                GestureSample gst = new GestureSample();
                if (ms.ScrollWheelValue != PreviousScrollState) { gst = new GestureSample(GestureType.FreeDrag, gameTime.ElapsedGameTime, new Vector2(), new Vector2(), new Vector2(0, (ms.ScrollWheelValue - PreviousScrollState)/3), new Vector2()); }
                else if (ms.LeftButton == ButtonState.Released && PreviousState == ButtonState.Pressed) { PreviousDragPosition = Vector2.Zero; gst = new GestureSample(GestureType.Tap, gameTime.ElapsedGameTime, new Vector2(ms.X, ms.Y), new Vector2(), new Vector2(), new Vector2()); }
                else if (ms.LeftButton == ButtonState.Pressed && PreviousState == ButtonState.Released) { PreviousDragPosition = new Vector2(ms.X, ms.Y); }
                else if (ms.LeftButton == ButtonState.Pressed && PreviousState == ButtonState.Pressed) { gst = new GestureSample(GestureType.FreeDrag, gameTime.ElapsedGameTime, PreviousDragPosition, new Vector2(), (Vector2.Distance(PreviousDragPosition, new Vector2(ms.X, ms.Y)) >= 2) ? -new Vector2(PreviousDragPosition.X - ms.X, PreviousDragPosition.Y - ms.Y) : Vector2.Zero, new Vector2()); PreviousDragPosition = new Vector2(ms.X, ms.Y); }
                PreviousState = ms.LeftButton;
                PreviousScrollState = ms.ScrollWheelValue;
#endif
                // Do stuff with the 'gst' variable
            }

```

I also pre-define these variables somewhere:

```
ButtonState PreviousState = ButtonState.Released;
int PreviousScrollState = Mouse.GetState().ScrollWheelValue;
Vector2 PreviousDragPosition = Vector2.Zero;

```

This code will detect taps and drags (which are the only gestures my games uses). It will consider scrolling a `FreeDrag` in the vertical direction, and will correctly detect dragging the mouse across the screen.
> 0 votes

---
Tags: c#, monogame, windows, touch
---


# Question
Title: How to avoid cost comparison each and every frame?
I'm toying around with a ticker(incremental game) for JavaScript.

The basic idea is that you have buttons that represent buildings, each building provides a certain amount of resource per 'tick'.

Each building can cost an arbitrary amount of resource types and amounts (a farm can cost wood, food and labor for example). The game is intended to have several dozens of buildings, units, technologies etc.

I would like to disable the buttons of buildings that you can't currently afford.

My concern: I prefer not to loop over every item and every cost within it to see if we have enough to build it every single tick (a tick is 50ms~).

Is there a 'smart' way that I missed that solves this issue without brute force?

EDIT : I decided to approve the answer that basically says "Just ignore the problem". The reasoning behind it is as follows :

1. Tests indicated that while the theoretical problem is interesting, it's of little consequence in a reality, the performance hit is extremely minimal.
2. This website is about solving problems, and as "sam hocevar" suggested, The answer needs to be as clear as possible(and the reason behind it).
3. While the answers are clever and very interesting to read as a theoretical background , they all address the "number of checks", while some answers reduce that number by some fraction, non actually mitigate the amount by any performance-altering number.
4. Following on 3, It seems that if you've come to a point where you need to implement any of the suggested, over-engineered, solutions to save performance, It seems that the gain from those solutions will be so minimal that performance will still be an issue even after implementation, making the entire game model not viable anyway.

TL;DR - If it doesn't work by ignoring the problem, it probably won't work with over-tweaking it either.

# Answer
A boolean check is a very inexpensive thing. I wouldn't worry at all about performance costs. But there are two ways to go about this: Push or Pull. Either you 'pull' the data by checking every tick, or you 'push' the data by notifying buttons whenever a resource changes. For example, if your wood has increased, it fires an event to all buildings that need wood to be built and re-evaluates whether they can be built. The pull method is probably much easier and cleaner to implement, but the push will be less performance intensive.
> 11 votes

# Answer
Just recalculate your building-options at a bigger interval than your game-loop? You could just as well recalculate every 500, or even every 1000ms. The user won't care/notice if the building-options refresh with a slight delay.

All in all, this sounds a bit like premature optimization. I highly doubt you're going to have so many options to calculate that you'll be running into performance problems *even* if you update every 50ms.
> 3 votes

# Answer
Store your listeners in an ordered collection based upon their resource value - e.g. activate Factory Upgrade3 at 500 coins. Then every tick simply enable/disable any listener between the last tick's value and the current ticks value. By using an ordered collection you should be able to find this range of values very quickly.

1. Memory/CPU Efficient (only touch relevant items)
2. Real time - no delays to annoy players.

Of course, to echo earlier comments this sounds like a premature optimization at this point.
> 3 votes

# Answer
What is specific to javascript is that it has an overall high overhead when interpreted, and when (JIT) compiled, it will perform ok only with guessable types, simple loops, and using built-in functions, i think especially here about sort.
Sort your 'buildables' by each type of resource -this is done once, stored in separates arrays- (time vs space).
now each tick OR at a slower rate, but anyway every time the user *spend* resources, you just have to do a few for loops to tag the buildables with a boolean (using a boolean mask). for/while loops are so simple even javascript is fast with them.

Since i'm not sure i'm clear, here's some pseudo code :

```
// declared once (init)
var buildables = [ array of buildables with their resource requirements];
var resourceNames = [ 'water', 'gold', ... ...]
var sortedBuildables = [];
resourceNames.forEach(function(rn) {
            sortedBuildables.push(buildables.sort(
                                         function(a,b) { return a[rn]-b[rn]; }  )); });
var resourceCount = resourceNames.length;
var allResourcesOkMask = (1<<resourceCount)-1;

```

Now when you need to check (every now and then OR when user spent resources)

```
var resourceValues = [ ... the amount of resource you have for each resource ...];
var lastResourceValues = new Array(resourceValues.length);

sortedBuildables.forEach(
   function(sorted, resourceIndex) {
      var resourceValue = resourceValues[resourceIndex];
      var lastResourceValue = lastResourceValues[resourceIndex];
      if (resourceValue != lastResourceValue) {
        var resourceName = resourceNames[resourceIndex];
        var resourceMask = 1 << resourceIndex;
        var buildable = null;
        var i=0;
        while((buildable = sorted[i]) && (buildable[resourceName]<resourceValue))
               {
                 buildable.mask |= resourceMask;
                 i++;
               }
        while ((buildable = sorted[i]))
               {
                 buildable.mask &= !resourceMask;
                 i++;
               }
        }
      }
      lastResourceValues = resourceValues.slice(0);
);

```

now for each buildable, knowing if you can build it is the result of this test :

```
if (buildable.mask == allResourcesOkMask) --> button enabled.

```

While still brute force, this algorithm should work much faster in JS than even any smarter (tree/...) algorithm, given the js overhead : nothing is faster in js than doing plain for/while loops cruching integer numbers.
> 1 votes

# Answer
In most games, just run the loop every time. The cost of checking every bloody button you could ever press is way less than the cost of rendering a single button onscreen. GameAlchemist's answer should be more than enough for anything you actually want to do.

However, if you want better than brute force, you will want to take advantage of temporal consistency. On average, the set of enabled/disabled buttons doesn't change very much. All you have to do is prove that it hasn't changed much, and you're set.

Put all of your upgrades into an ordered structure for each resource, along with their prices. I'm going to talk to using an array, but any structure would do. One tiny change: invert all the prices. 500 minerals should become -500 minerals. *Why? It could work either way, but the specific named algorithms tend to have specific meanings, and if I do this silly optimization, they correctly handle the case where I have exactly 500 minerals and want the build option to be enabled.*

On the first iteration, we have to do some slower prep work. We take the number of minerals we have (let's say 249), and invert it to -249. Now if we treated this -249 as a `lower_bound`, and looked at the part of the ordered array that was equal or greater than this negative number, we'd have the list of everything that is enabled at first (its cost is closer to 0 than the amount of resources we have). Likewise, if we take an `upper_bound` operation, we'd look at the part of the ordered arraythat was less than this negative number, we'd have the list of everything that is disabled at first (its cost is further from 0 than the amount of resources we have).

The weirdness with negative numbers should be meaningful with an example where we have exactly 500 resources:

```
 -900   -500   -400   -200  -100    prices of each item (inverted)
        -500                        actual resources (inverted)
       |------------------------|   values for which -500 is a lower bound
|------|                            values for which -500 is an upper bound

```

You could absolutely word the logic differently and avoid all this silly negation. However, by doing it this way, you can use a lot of existing routines for dealing with bounds in sorted arrays. At least as far back as C++, the definitions of `lower_bound` and `upper_bound` have been defined such that `lower_bound` includes the value you're searching for, while `upper_bound` excludes it.

That was a lot of work, however, after frame 1, we can start using some temporal consistency to save time. We need to save off the current enabled/disabled state and resource count before we increment resources. Then we can compare the new resources against the old. If the new resources are higher, we are going to try to enable more states. If the new resources are lower, it means we spent resources last tick, and we need to disable more states.

So what states are going to change? It's easy really. Let's handle the increasing resources case first. If we negate the resources, like we have to to work with this structure, this means our resource number is going more negative. If we do a `lower_bound` based on this resource number, we'd get a part of the ordered array which should be enabled, just like before. However, this time, we also know that everything above the previous frame's `lower_bound` is already enabled, so we don't need to re-notify them. We only have to notify what's in between. Let's look at this on a number line. I'm intentionally making it jump a lot, from 300 resources to 500 so we can show the algorithm at work. Typically this jump would be a lot smaller.

```
 -900   -500   -400   -200  -100    prices of each item (inverted)
                   -300             old resources: 300 (inverted)
                     |---------|    values for which -300 is a lower bound
                       EN    EN     Enabled resources in previous frame
        -500                        new resources: 500 (inverted)
       |-----------------------|    values for which -500 is an lower bound
         EN      EN    EN    EN     Resources which need to be enabled
       Notify  Notify               Buttons that need notification because
                                    they were not enabled before, but are
                                    enabled now.

```

Likewise, if we're decreasing resources this frame, we need to disable buttons. Everything which was under the `upper_bound` of the previous frame were things that we know were properly disabled already. Everything under the `upper_bound` of this frame are things we need to disable. Thus, we should notify everything which is under the new `upper_bound` but stop when we see the old `upper_bound` because that was already handled. As an example, let's do the opposite of the previous example. Let's go from 500 resources to 300.

```
 -900   -500   -400   -200  -100    prices of each item (inverted)
        -500                        old resources: 500 (inverted)
|------|                            values for which -500 is an upper bound
         EN      EN    EN    EN     Enabled resources in previous frame
                   -300             new resources: 300 (inverted)
|------------------|                values for which -300 is a  upper bound
                       EN    EN     Resources which need to be enabled
       Notify  Notify               Buttons that need notification that
                                    they are no longer enabled

```

*Phew*. I told you its easier to just run the loop every time, but this *will* run faster than brute force. First off, because we're operating on an ordered array, `lower_bound` and `upper_bound` are O(log n), rather than the O(n) of the brute force approaches. Second, we're only sending notifications to the minimum number of buttons possible.

If you want to have more than one type of resources, keep an ordered array for each resource separately. Have each object which manages your buttons keep track of how many resources it needs which are unsatisfied by the current resources. On notification that you have enough of a resource, decrement this "unsatisfied" count by 1. on notification that you no longer have enough, increment this "unsatisfied" count by 1. Now you only really have to worry about the transition from 0 (fully satisfied, enabled) to 1+ (not satisfied, disabled).

Lots of work, but that'll keep your runtime costs as low as they can possibly go! If you have a few hundred buttons, and a few dozen resources for each, that may be the trick that takes you from "runs too slow to play" to "fun to play!" Maybe if you're going for hard-realtime 60Hz, this might help. The only way to tell is to profile. There's a lot more upkeep involved than with the brute force method, and depending on how well javascript optimizes, that might hurt more than it helps. However, this is scaleable, so when you want to have 100,000 buildings with 50 resources each, updating every millisecond, on the dot, this might be the ticket you need. It's also quite parallelizable in many steps, not that that matters much for javascript.
> 1 votes

# Answer
I assume these buttons need not be available at the exact same frame as the player gathers enough resources to buy them.

If that assumption is true, you can divide your list of buttons into four or five lists, and iterate over each of them on a different frame. For disabling, you should still check every frame, or do a second check when the user clicks the button, to prevent the user from taking advantage of that extra frame to click again.

### Pseudocode:

```
buttons = [{costs:{lumber:10, gold:30}} ...]
buttonParts = divideArray(buttons, 4)
currentPart = 0

onUpdate():
    currentPart = currentPart+1 % buttonParts.length //every frame process next list, looping back to 0
    for btn in buttonParts[currentPart]:
        canEnable = true
        for {resource: costAmount} in btn.costs:
            if PLAYER_RESOURCES[resource] < costAmount:
                canEnable = false
                break //exit resources loop if any resource is not enough
        if canEnable:
            btn.enable()

```
> 1 votes

# Answer
checking each button before drawing it will be simplest and cheap enough for sane number of buttons.

if resources grow at constant speed (that is, unless new building is built, every tick player gains same amount resources), this algorithm might be worth considering is there is a lot of things to update:

```
have priority queue.
number your ticks.
disable all buttons.
for each button:
  has enough resources?
    mark as enabled.
  else:
    compute when there will be enough resources.
    put it in priority queue, with priority=tick number when to enable.
each frame:
  for each button in priority queue with priority==current tick number:
    mark as enabled.
    remove from queue.
when player clicks any enabled button:
  build building or whatever.
  disable all buttons.
  clear the queue.
  repopulate queue and enable buttons as in initialization.

```

there might be a way to do less work when player builds something (possibly with queue for every resource kind), but algorithm would be even more complicated.
> 0 votes

---
Tags: javascript, performance
---


title: Where to store persistent player data?

text:
# Question
Title: Where to store persistent player data?
I'm working on a 2d game, where the player can take damage and die. And upon death, player object gets destroyed.

However, some attributes of player shouldn't be affected by his death, such as lives, ammo, current weapon and so on. I'm wondering where to store these values.

I'm using c++.

# Answer
Why would you destroy the player class, if you clearly want to preserve data related to that player.

Instead of destroying the player class use a statemachine to tell what state the player is in (alive, dead) and add a state if the player has run out of lives to signal the end of the game.

Keep the data close to the object 'owning' the data. Imagine you make your game multiplayer, it is easier to keep track of this data in the player objects than to design a storage that scales whith the number of players or keeps track what property belonged to what player.
> 4 votes

---
Tags: c++, design-patterns
---


# Question
Title: Is Flash (Flash/Flex/AIR) a still maintained technology (either officially / 3rd party) suitable for Web Player (linux) and mobiles?
Today I use Flash Player 11 since it's the last one released by Adobe, for linux-based OSs. The same applies to Flex/AIR platforms: I use Flex 4.1.4 and AIR 2.6, while Windows and Mac systems have newer versions (at least 4.6 and 3.1 respectively).

Is there a (trusted 3rd party) community making a good port (*good* stands for compatibility) of those newer versions to Linux-based OSs? Or is Flash/Flex/AS3 actually dying\*?

(\* my concern with this point is that I would not like to stick to an unmaintained technology in a mid-term future. Currently I'm learning Citrus Engine + Starling and I'd like to know if it is a bad).

# Answer
I'll interpret your question this way:

> In the context where I want to *produce* stuff, should I keep on making games with Flash given the current situation?

From experience, if the publisher of an API or library stops supporting that said API/library, you'll be fine for some time, then it's going to start to be harder to work with the API as new OS will require new API binaries, access to core OS functions will change, and such.

That is, if the source is not released.

If the source is released, yes, a community can emerge and keep the support for the API, but development will most likely be halted or very slow, just like the bug fixes.

IMHO, if a technology has reached it's end of life, there is no point in putting time in it, and you'll have a better future to chose the technology that replaced it.
> 3 votes

---
Tags: flash, linux, flex
---


# Question
Title: Publishing a Unity game to Android/iPhone
How can I publish a game that I made in Unity onto Android and iPhone? How do I generate the Android/iPhone binaries?

# Answer
In Unity, if you select *File \> Build Settings...* you'll bring up this window:

You can click on any platform and select "*Switch Platform*" which slightly changes your development environment. Some assets might re-import and Unity Platform Directives in your code like `if #UNITY_ANDROID` will become useful.

From this same menu, clicking "*Player Settings...*" will provide more customization options in the *Inspector*.

When you're confident the project is in the state you want, click *Build*. For Android, you can follow this Manual to help with Building for Android. With IOS, Unity will give you an .xcodeproj which you will then need XCode to compile and deploy to IOS devices (you can't do this without a Mac or without doing some illegal work-arounds).

Note that this is for "Building" to these platforms and not "Publishing". If you have a completed project and would like to publish it to Android and IOS's markets, that's not something to ask here.
> 1 votes

# Answer
Google Play Developer Console: https://play.google.com/apps/publish/
App Store Developer Page: https://developer.apple.com/app-store/

They both need registration fees.
> 0 votes

---
Tags: unity, android-studio
---


# Question
Title: HLSL pixel inside a view (cascaded shadowmapping)
I'm figuring out shadowmapping in HLSL (see also this question). I understand that I need projection matrices for each cascading shadowmap.

I use this code to create the projections:

```
    Matrix CreateLightViewProjectionMatrix(LightProjectionDistance distance)
    {
        // Matrix with that will rotate in points the direction of the light
        Matrix lightRotation = Matrix.CreateLookAt(Vector3.Zero,
                                                   -_lightDir,
                                                   Vector3.Up);

        BoundingFrustum cameraFrustum = new BoundingFrustum(_view);
        switch (distance)
        {
            case LightProjectionDistance.Close:
                cameraFrustum = new BoundingFrustum(_view * _projectionClose);
                break;
            case LightProjectionDistance.Medium:
                cameraFrustum = new BoundingFrustum(_view * _projectionMedium);
                break;
            case LightProjectionDistance.Far:
                cameraFrustum = new BoundingFrustum(_view * _projectionFar);
                break;
        }

        // Get the corners of the frustum
        Vector3[] frustumCorners = cameraFrustum.GetCorners();

        // Transform the positions of the corners into the direction of the light
        for (int i = 0; i < frustumCorners.Length; i++)
        {
            frustumCorners[i] = Vector3.Transform(frustumCorners[i], lightRotation);
        }

        // Find the smallest box around the points
        BoundingBox lightBox = BoundingBox.CreateFromPoints(frustumCorners);

        Vector3 boxSize = lightBox.Max - lightBox.Min;
        Vector3 halfBoxSize = boxSize * 0.5f;

        // The position of the light should be in the center of the back
        // pannel of the box.
        Vector3 lightPosition = lightBox.Min + halfBoxSize;
        lightPosition.Z = lightBox.Min.Z;

        // We need the position back in world coordinates so we transform
        // the light position by the inverse of the lights rotation
        lightPosition = Vector3.Transform(lightPosition,
                                          Matrix.Invert(lightRotation));

        // Create the view matrix for the light
        Matrix lightView = Matrix.CreateLookAt(lightPosition,
                                               lightPosition - _lightDir,
                                               Vector3.Up);

        // Create the projection matrix for the light
        // The projection is orthographic since we are using a directional light
        Matrix lightProjection = Matrix.CreateOrthographic(boxSize.X, boxSize.Y,
                                                           -boxSize.Z, boxSize.Z);

        return lightView * lightProjection;
    }

```

Where the view matrices are like this:

```
        float aspectRatio = (float)graphics.PreferredBackBufferWidth / (float)graphics.PreferredBackBufferHeight;
        _projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                         aspectRatio,
                                                         1f, 500.0f);
        _projectionClose = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                         aspectRatio,
                                                         1f, 20.0f);
        _projectionMedium = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                         aspectRatio,
                                                         20.0f, 100.0f);
        _projectionFar = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                         aspectRatio,
                                                         100.0f, 500.0f);

```

In my Pixelshader I try this:

```
diffuse = input.Color;
float4 lightingPosition = mul(input.WorldPos, LightViewProjClose);
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{
   diffuse = float4(1,0,0,1);
}

lightingPosition = mul(input.WorldPos, LightViewProjMedium);
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{
   diffuse = float4(0,1,0,1);
}

lightingPosition = mul(input.WorldPos, LightViewProjFar);
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{
   diffuse = float4(0,0,1,1);
}

return diffuse;

```

Now I expected to see the picture colored in red (close), green (medium) and blue (far) bands. However it seems only the close range is actually colored and the medium and far distances are not triggered. I did set the parameters like this:

```
_myEffect.Parameters["LightViewProjClose"].SetValue(CreateLightViewProjectionMatrix(LightProjectionDistance.Close));
        _myEffect.Parameters["LightViewProjMedium"].SetValue(CreateLightViewProjectionMatrix(LightProjectionDistance.Medium));
        _myEffect.Parameters["LightViewProjFar"].SetValue(CreateLightViewProjectionMatrix(LightProjectionDistance.Far));

```

I'm getting frustrated as I'm trying to figure this out for the past couple of days with almost no progress. What am I missing? How can I get the pixel shader switch between the correct light projections so it can pick the right cascaded shadowmap?

**Edit, after tweaking this is my shader code:**

```
float4x4 World;
float4x4 View;
float4x4 Projection;
float4x4 LightViewProjClose;
float4x4 LightViewProjMedium;
float4x4 LightViewProjFar;

float3 LightDirection1 = float3(-1.5, 0.45, 0);
float4 LightColor1 = float4(1, 1, 1, 1);
float3 LightDirection2 =float3(1,1,0.2);
float4 LightColor2 = float4(0.2, 0.2, 0.25, 1);

float4 AmbientColor = float4(0.15, 0.15, 0.15, 0.15);
float DepthBias = 0.001f;

texture ShadowMap;
sampler ShadowMapSampler = sampler_state
{
    Texture = <ShadowMap>;
};

struct VertexShaderInput
{
    float4 Position : SV_POSITION;
    float4 Normal : NORMAL0;
    float4 Color : COLOR0;
};

struct ShadowVertexShaderInput
{
    float4 Position : SV_POSITION;
    float4 Normal : NORMAL0;
    float4 Color : COLOR0;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Normal   : TEXCOORD0;
    float4 Color    : COLOR0;
    float4 WorldPos : TEXCOORD2;
};

struct CreateShadowMap_VSOut
{
    float4 Position : POSITION;
    float4 Color : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4x4 WorldViewProj = mul(mul(World, View), Projection);

    // Transform the models verticies and normal
    output.Position = mul(input.Position, WorldViewProj);
    output.Normal =  input.Normal;
    output.Color = input.Color;

    // Save the vertices postion in world space
    output.WorldPos = mul(input.Position, World);

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    // Color of the model
    float4 diffuseColor = input.Color;

    // Intensity based on the direction of the light
    float diffuseIntensity1 = clamp(dot(input.Normal.xyz, LightDirection1.xyz), 0, 1);
    float diffuseIntensity2 = clamp(dot(input.Normal.xyz, LightDirection2.xyz), 0, 1);

    // Final diffuse color with ambient color added
    float4 diffuse = saturate((diffuseIntensity1 * LightColor1 + diffuseIntensity2 * LightColor2) * diffuseColor);

    // Find the position of this pixel in light space in the close projection
    float4 lightingPosition = mul(input.WorldPos, LightViewProjClose);
    lightingPosition.xyz = 0.5 * lightingPosition.xyz / lightingPosition.w;
    if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
    {
        lightingPosition = mul(input.WorldPos, LightViewProjClose);
        // Find the position in the shadow map for this pixel
        float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
            lightingPosition.w + float2(0.5, 0.5);
        ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

        // Get the current depth stored in the shadow map (red component for close)
        float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).r;

        // Calculate the current pixel depth
        // The bias is used to prevent floating point errors that occur when
        // the pixel of the occluder is being drawn
        float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

        // Check to see if this pixel is in front or behind the value in the shadow map
        if (shadowdepth < ourdepth)
        {
            // Shadow the pixel by lowering the intensity
            diffuse *= float4(0.5, 0.5, 0.5, 0);

        };
    }

    lightingPosition = mul(input.WorldPos, LightViewProjMedium);
    lightingPosition.xyz = 0.5 * lightingPosition.xyz / lightingPosition.w;
    if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
    {

        lightingPosition = mul(input.WorldPos, LightViewProjMedium);
        // Find the position in the shadow map for this pixel
        float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
            lightingPosition.w + float2(0.5, 0.5);
        ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

        // Get the current depth stored in the shadow map (green component for medium)
        float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).g;

        // Calculate the current pixel depth
        // The bias is used to prevent floating point errors that occur when
        // the pixel of the occluder is being drawn
        float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

        // Check to see if this pixel is in front or behind the value in the shadow map
        if (shadowdepth < ourdepth)
        {
            // Shadow the pixel by lowering the intensity
            diffuse *= float4(0.5, 0.5, 0.5, 0);
        };
    }

    //do the same trick using the 'far' matrix.
    lightingPosition = mul(input.WorldPos, LightViewProjFar);
    lightingPosition.xyz = 0.5 * lightingPosition.xyz / lightingPosition.w;
    if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
    {
        lightingPosition = mul(input.WorldPos, LightViewProjFar);

        // Find the position in the shadow map for this pixel
        float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
            lightingPosition.w + float2(0.5, 0.5);
        ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

        // Get the current depth stored in the shadow map (blue component for far)
        float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).b;

        // Calculate the current pixel depth
        // The bias is used to prevent floating point errors that occur when
        // the pixel of the occluder is being drawn
        float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

        // Check to see if this pixel is in front or behind the value in the shadow map
        if (shadowdepth < ourdepth)
        {
            // Shadow the pixel by lowering the intensity
            diffuse *= float4(0.5, 0.5, 0.5, 0);
        };
        //diffuse = float4(0, 0, 1, 1);
    }
    return diffuse;
}

CreateShadowMap_VSOut ShadowCloseVertexShaderFunction(VertexShaderInput input)
{
    CreateShadowMap_VSOut output;

    output.Position = mul(input.Position, mul(World, LightViewProjClose));
    output.Color = float4(output.Position.z / output.Position.w,0,0,1);

    return output;
}
CreateShadowMap_VSOut ShadowMediumVertexShaderFunction(VertexShaderInput input)
{
    CreateShadowMap_VSOut output;

    output.Position = mul(input.Position, mul(World, LightViewProjMedium));
    output.Color = float4(0,output.Position.z / output.Position.w, 0, 1);

    return output;
}
CreateShadowMap_VSOut ShadowFarVertexShaderFunction(VertexShaderInput input)
{
    CreateShadowMap_VSOut output;

    output.Position = mul(input.Position, mul(World, LightViewProjFar));
    output.Color = float4(0,0,output.Position.z / output.Position.w, 1);

    return output;
}

float4 ShadowPixelShaderFunction(CreateShadowMap_VSOut input) : COLOR0
{
    return input.Color;
}

technique MyTechnique
{
    pass Pass1
    {
        VertexShader = compile vs_4_0_level_9_3 VertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_3 PixelShaderFunction();
    }
}

technique ShadowTechniqueClose
{

    pass Pass1
    {
        VertexShader = compile vs_4_0_level_9_3 ShadowCloseVertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_3 ShadowPixelShaderFunction();
    }
}
technique ShadowTechniqueMedium
{

    pass Pass1
    {
        VertexShader = compile vs_4_0_level_9_3 ShadowMediumVertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_3 ShadowPixelShaderFunction();
    }
}
technique ShadowTechniqueFar
{

    pass Pass1
    {
        VertexShader = compile vs_4_0_level_9_3 ShadowFarVertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_3 ShadowPixelShaderFunction();
    }
}

```

The "close" shadows seem to work. However the 'medium' and 'far' shadows are still not working. The result looks like this:

What am I doing wrong here?

# Answer
Maybe this is not the whole problem, but you need to divide by the w component after multiplying with a projection matrix.
So after `float4 lightingPosition = mul(input.WorldPos, LightViewProjClose);` but before the `if` you should do this:

```
lightingPosition.xyz /= lightingPosition.w

```
> 1 votes

---
Tags: xna, hlsl, monogame, shadow-mapping, projection-matrix
---


# Question
Title: Can't parent the standard FPSController during gameplay
I'm parenting the standard assets FPS controller during play with a simple script. The controller get's parented but also instantly inherits the rotation of the parent. This doesn't happen in Editor mode. This incorrect behavior happens regardless if I move the player with a script or by parenting him with my mouse cursor.

I suspect the error comes from the way the character controller script is set up.

In the FPS controller script the player rotates via mouse movement in the Update function in the following way:

```
private void Update()
{
    RotateView();
}

private void RotateView()
{
    m_MouseLook.LookRotation (transform, m_Camera.transform);
}

```

*m\_MouseLook* get's its rotation from *m\_Camera.transform*. It in turn uses *transform.localPosition*.

I think it's the use of *localposition* that causes the strange behavior.

How do I fix it?

I added the script that I used to re-parent the fps controller below:

```
    public Transform ParentTarget;
    public GameObject player;

     void OnTriggerEnter(Collider other)
    {
        player.transform.SetParent(ParentTarget, true);
    }

     void OnTriggerExit(Collider other)
    {
        player.transform.parent = null;
    }

```

As I said the script is fairly simple and the same error happens when I re-parent the controller by dragging it with my mouse during play.

If I set *worldPositionStays* to false then the player is offset and doesn't inherit the parent rotations at all. This isn't what I want.

Here is my scene before the player steps unto the trigger. The red box is the trigger. The blue box is the new parent (the parent is rotated 45 degrees)

Here is the original incorrect behavior. The player is instantly rotated 45 degrees as he steps unto the trigger. This is wrong

Here is the behavior when worldPositionStays is set to false. Rotating the parent has no effect. This is wrong.

The desired behavior is to keep the player rotation, and then change it as the parent is rotating after the re-parenting event. This is what would happen if I re-parented any ordinary GameObject.

It is the character controller mouse look part that is most likely causing all the trouble.

I suspect I have to abandon the re-parenting solution and simply add the transforms to the camera mouse look part of the character controller script.

I would be very grateful is someone more knowledgeable would help me out with achieving this. Hopefully by getting re-parenting to work, since it is simpler, and simplicity is always king. I would settle for help with writing a script to add rotations and positions correctly to the controller.

# Answer
> 4 votes
I appreciate that you'd prefer to solve your problem using parenting but the truth is you're going to be fighting Unity more than utilizing its simplicity if you attempt this.

The problem is that `MouseLook` (which is used by `FirstPersonController`) stores its own value for rotation and uses that exclusively on the `Transform` that it owns. This is a problem in combination with how the `GameObject` hierarchy handles the rotation, scaling, and transforming of parent child relationships. This hierarchical "guidance" along with `FirstPersonController`'s use of `MouseLook` and its persistent rotation storage causes mathematical complications when re-parenting occurs; it's not impossible to solve but will require hacking together some stupid math.

You're better off with an alternative solution of re-implementing that parental "guidance" and then making minor modifications to the `FirstPersonController` and `MouseLook`.

For these files that already exists, I've marked which likes are old, modified, or new.

---

## MouseLook.cs

First, in `MouseLook`, we need a way to modify the rotation because it stores its own and forces it upon the `Transform` that it's working with. We'll need an extra `float` for rotating on the y axis:

```
private Quaternion m_CharacterTargetRot; // Old
private Quaternion m_CameraTargetRot; // Old
private float m_extraY; // New

```

We need to allow it to modify `MouseLook`'s internal rotation in `MouseLook.LookRotation()`:

```
float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity; // Old
float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity; // Old

m_CharacterTargetRot *= Quaternion.Euler (0f, yRot + m_extraY, 0f); // Modified
m_extraY = 0.0f; // New
m_CameraTargetRot *= Quaternion.Euler (-xRot, 0f, 0f); // Old

```

and some public access to set it. Add this function:

```
public void AddYRotation(float y) { m_extraY = y; } // New

```

## FirstPersonController.cs

This simply needs a method to call the new function you just made in `MouseLook`:

```
public void AddYRotation(float y) { m_MouseLook.AddYRotation(y); } // New

```

---

Now you need a new class to handle the hierarchical "guidance" you would have gotten with parenting:

## Vehicle.cs

```
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class Vehicle : MonoBehaviour
{
    public FirstPersonController fps;

    private Vector3 m_lastPosition;
    private Vector3 m_positionDiff;

    private float m_lastYRot;
    private float m_yRotDiff;

    void Start() {
        m_lastPosition = transform.position;
        m_lastYRot = transform.rotation.eulerAngles.y;
    }

    void Update() {

        m_positionDiff = transform.position - m_lastPosition;
        m_lastPosition = transform.position;

        m_yRotDiff = transform.rotation.eulerAngles.y - m_lastYRot;
        m_lastYRot = transform.rotation.eulerAngles.y;
    }

    void LateUpdate() {
        if (fps != null) {
            fps.transform.position = fps.transform.position + m_positionDiff;
            fps.AddYRotation (m_yRotDiff);
        }
    }
}

```

---

Wrapping this all up, after your modifications and adding the `Vehicle` to whatever you need (a Train, elevator, sliding platform, that blue bar in your pictures), instead of calling `SetParent` it will look more like this:

```
void OnTriggerEnter(Collider other) {
    // If these GetComponent calls return null, you're doing something wrong
    var veh = ParentTarget.GetComponent<Vehicle>();
    veh.fps = player.GetComponent<FirstPersonController>();
}

```

# Answer
> 1 votes
I think the easiest way to do this would be to update your code so that when the FpsController is added as a parent it is first updated so that its rotation matches the current position of the child object.

I think this should give the effect required but I may be misunderstanding what you are trying to do!

This should be posible with:

```
transform.Rotate()

```

http://docs.unity3d.com/400/Documentation/ScriptReference/CharacterController.SimpleMove.html

# Answer
> 0 votes
Here is the quick and dirty way:

```
 void OnTriggerEnter(Collider other)
{
    Quaternion toSubs = ParentTarget.transform.rotation / player.transform.rotation;
    player.transform.SetParent(ParentTarget, true);
    player.transform.rotation /= toSubs;
}

```

Since i don't understand majority of the question, i can't provide you an appropiate way.

---
Tags: c#, software-engineering, unity, character
---


# Question
Title: Lazy way to figure out the two sides of a border?
We have a 3d model. There is a simple path on that model's surface graph `G` of the form:

```
<v_0, v_1 ... v_n-1, v_n> where if v_i == v_j then i == j

```

Great! now the simple question appears:

How do you programmatically tell in the human sense if `v_orange` and `v_green` are on the same side of the trail and if `v_green` and `v_blue` are on the same side or not?

My intuition is that you Dijkstra the shortest path between them and if it goes through the trail an even number of times their on the same side. However that is not defined if you don't know what goes through the trail computes to. If thinking if it was 2d and we could project these trail edges on some flat surface this would be made trivial.

My current solution is a lie. Each edge is normally shared by two faces unless it's an orbifold which is currently not interesting to this question's input population set. Also, in our world, each face has percisely three vertices.

1. Use Dijkstra to find the shortest path between them. If the path does not touch the trail, their relation to the trail isn't well defined or their on the same side (for now it outputs they are on the same side).
2. Assuming the path does go through the path, we pick one of the edges it went through. Each edge belongs to two faces, each of these faces has precisely one vertex that is not on the edge trail. we now have two vertices that are supposed to be on different sides of the trail.
3. Dijkstra from each of the trail side vertices to the vertices in question.
4. If the shorter path to both vertices in question is from the same side then maybe they are on the same side. If it each vertex prefers a different side then maybe they are not.

Here is one fault in this solution:  Sometimes the two are on the same side and the other route is shorter.

---

# Clarification

This is a clarification inspired by wondra that felt nothing can be on the right side or the left side of a trail, something that in my opinion people would disagree with as we have a good sense of left & right.

Lets "split" the model where the trail is and add more faces between the two new trails (lips) and get something like this:

Trail 1 is `Blue`, trail 2 `Red` and some epsilon wide faces between them. Now we use Dijkstra to find the shortest distance from both trails (Blue and Red). Some vertices are closer to the `Red`, some to `Blue`. Very few are (the same), closest simply to the last or first vertex in the original trail that are conjoined between the trails.

# Answer
> 3 votes
I believe the solution is simple - mark vertices of the path as impassible and run regular Dijkstra for this input. If it fails to find a path you are sure they are on different sides.
**Edit:** If your path does not split the graph into two components you can still use method described above with only difference - after finding the shortest route check whether it contains endpoints of the path. If it contains exactly one endpoint, you know the points lies on different sides (if it contains both of them, you know it went "the other way around", in example given in question it would take the bottom path, points still can be assumed on same side).

---

You might point out now: *"But unsuccessful Dijkstra will visit every vertex of the component!"*. Yes that is correct, and there can be no other way - imagine the example given in answer what if there was not just the spike but whole labyrinth? Running full Dijkstra is necessary if you need 100% correct answer (OP found in solution it will give you only "maybe" answers otherwise).
If the speed proves to be problem, and you are confident that the path is "simple enough" you can speed the process up by giving up early, after *n* steps this should give better results with A\* instead of plain Dijkstra. Alternatively, you can do (offline) pre-computation by giving each vertex its component ID using flood fill, this is way fastest solution(for answer just compare component IDs), but also the least flexible one.

---
Tags: models, graph, path
---


title: OpenGL Face Order

text:
# Question
Title: OpenGL Face Order
i have written a simple OBJ-file loader to render meshes using OpenGL. But there is a problem displaying the loaded mesh. It seems that faces that from the background (far) are displayed above the front faces.

To illustrate the problem i have rendered a little example picture (Blender monkey).

I am using really simple shaders:

**Vertex shader**

```
#version 330

layout (location = 0) in vec3 vert;
layout (location = 1) in vec2 uv;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

out vec2 frag_uv;
out vec3 frag_vert;

void main()
{
    gl_Position  = vec4(vert, 1);
    gl_Position *= model;
    gl_Position *= view;
    gl_Position *= projection;

    frag_vert = vec3(vec4(vert, 1) * model);
    frag_uv = uv;
}

```

**Fragment shader**

```
#version 330

in vec2 frag_uv;
in vec3 frag_vert;

out vec4 color;

void main()
{
    color = vec4(frag_vert.x, frag_vert.y, frag_vert.z, 1.0);
}

```

The mesh is rendered using a VBO and a VAO. I have no clue ehat i am doing wrong. Thank you, and a nice christmas :)

# Answer
> 1 votes
**Solved**

Depth testing was not enabled:

```
glEnable(GL_DEPTH_TEST);

```

... fixed the Problem.

---
Tags: opengl, shaders, 3d-meshes
---


# Question
Title: Is using two languages in a game engine a good idea?
I'm thinking about making a game engine, as a learning project.

I know Java the best, and I figure most of the code is not going to be running that much of the time, given the 20/80 rule. Why not write most of it in a language I know? For the part that has to be really fast, like the renderer, I was thinking of writing that in native code.

Is this approach of using two languages a good idea, or a terrible one?

# Answer
Yes, some parts need to be *really fast*. Now are these part written in Java slow? Did you measure and considered that it would really be an improvement to figure out how to plug everything that needs to go fast in native language?

This seems to me like it's premature optimization. Unless you realize that these parts are really a bottleneck and that the only way to fix it is to use native code, you should not bother.

As @Steven mentioned, the transition may be very expensive.

Typically, the way to use more that one language is to use one 'compiled' language (Java, c#, c++), and one script language (lua, python, xml-based) to do some more changing stuff.
> 9 votes

# Answer
Writing engines in multiple languages that work together can offer many benefits, but almost always results in higher complexity and higher cost for maintenance.

For your first engine, you want to deliver a finished and working product, so the most important thing is to keep complexity down. Java is fast enough.

Another way to look at it is this: No matter how many languages you use, you are pretty much guaranteed to miss out on some clever optimizations that would make the engine one or more orders of magnitude faster. In comparison making the engine 10-50% faster by using C/C++ and SIMD instructions isn't that big of a deal. And forget about getting even close to these 50% if you don't know C/C++ yet, you'll be lucky if you can break even.
> 2 votes

# Answer
There are a lot of engines that work this way. The important thing is to make sure you don't transition from one language to the other too often as there is usually a cost there.
> 1 votes

---
Tags: java
---


# Question
Title: Trying to open an .fx file, text editor full of random symbols
Sorry, I'm a complete newbie to this place, and I don't know how appropriate my question is, but I didn't know where else to ask.

I'm trying to make a mod for The Sims 2, and this game uses a lot of internal formats which it bundles up in .package files. Its main modding program is called SimPE. SimPE can read some of these internal formats (for which plugins exist), others not. Specifically, it lacks a plugin for .fx files, which are all stored in a game file named Effects.package. This file had one resource which I've exported as an .fx.

I've opened the .fx with Notepad, with Visual Studio and with FXEditor, but for the most part it's not intelligible. It looks like this:

I understand I'm supposed to see code here.

Is there a way to fix my .fx (heh), or to get it into a readable format?

# Answer
It’s a binary file, not a `.fx` file. Don’t waste your time.

See those `ÍÌÌ=` in the screenshot? Since Notepad uses the CP1252 codepage by default, it means the sequence of bytes in the file was `cd cc cc 3d`. This rarely means anything special, except in binary file formats, where it stands for `0.1` encoded as an IEEE 32-bit float. Similarly, all those `ÍÌL>` mean `0.2`, and `š™™>` is for `0.3`… unless you know the actual file format, there’s not much you can do with the file except reverse-engineer it yourself.
> 1 votes

# Answer
This file is in binary. You can use a hexediter to view the file in a different way. However when the game loads the file it only reads the information it needs, and doesn't need to store all of the data in characters (which are human readable).
Instead of storing "10000.00" in a file, which takes up 8 characters, it would store that information using 32 bits instead. Which saves on disk space, and load time. If you want to read the file, or convert it to readable format. You will have to write a conerter, or find one online to do it for you. Basically you will have to read it in binary format, then output it in ascii format.
> 0 votes

---
Tags: modding
---


# Question
Title: ARBShaderObjects.glDeleteObjectARB vs GL20.glDeleteShader to remove shader?
I've created a shader object using `ARBShaderObjects.glCreateShaderObjectARB`and I'm wondering exactly how I'm suppose to remove said shader.

It seems both `ARBShaderObjects.glDeleteObjectARB` and `GL20.glDeleteShader` can do this.

I'm leaning towards `ARBShaderObjects.glDeleteObjectARB` since I created the shader using the `ARBShaderObjects` set of classes.

Do both of these work?

In this case is one prefered or different from the other?

Sorry for general LWJGL / OpenGL noobiness.

# Answer
If you used the extension function to create an object, then you *must only* use those extension functions to manipulate that object. So if you use `ARBShaderObjects.CreateShaderObjectARB` to create it, then you must use `ARBShaderObjects.glShaderSourceARB` to give it source strings, `ARBShaderObjects.glCompileShaderARB` to compile it, `ARBShaderObjects.glAttachObjectARB` to attach it to a program, and `ARBShaderObjects.glDeleteObjectARB` to delete it.

Remember: the return type of `glCreateShaderObjectARB` is `GLhandleARB`, which is a *pointer*, not a `GLuint` like the return value of `glCreateShader`. So they don't even use the same object type interface. The only functions that work with the ARB\_shader\_objects objects are those that explicitly say so. Which basically means those from that extension.

Also, there is no guarantee that you can compile any GLSL versions other than 1.10. The extension only guarantees support for that version, no others.

Basically, there is no reason to write code for this terrible 10+ year old extension. If you want to support hardware that has some shader functionality that isn't GL 2.0-capable, then use ARB\_vertex/fragment\_program.
> 1 votes

---
Tags: lwjgl
---


# Question
Title: Player controller script rigidbody velocity?
I don't understand how this works. How does this code go about manipulating the player's rigidbody velocity? Can you explain it piece by piece?

```
//Movement
public float speed;
public float jump;
float moveVelocity;

//Grounded Vars
bool grounded = true;

void Update ()
{
  //Jumping
  if ( Input.GetKeyDown (KeyCode.Space)
    || Input.GetKeyDown (KeyCode.UpArrow)
    || Input.GetKeyDown (KeyCode.Z)
    || Input.GetKeyDown (KeyCode.W))
  {
    if(grounded)
    {
      GetComponent<Rigidbody2D>().velocity = new Vector2(
        GetComponent<Rigidbody2D>().velocity.x,
        jump);
    }
  }

  moveVelocity = 0;

  //Left Right Movement
  if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A))
  {
    moveVelocity = -speed;
  }
  if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D))
  {
    moveVelocity = speed;
  }

  GetComponent<Rigidbody2D>().velocity = new Vector2(
    moveVelocity,
    GetComponent<Rigidbody2D>().velocity.y);
}

```

# Answer
> 4 votes
4 member variables that persist between calls to `Update`:

```
//Movement
public float speed;
public float jump;
float moveVelocity;

//Grounded Vars
bool grounded = true;

```

In Unity, `Update()` is called on a `MonoBehaviour` once per frame:

```
void Update ()
{

```

This detects the four different jump buttons:

```
    //Jumping
    if ( Input.GetKeyDown (KeyCode.Space)
        || Input.GetKeyDown (KeyCode.UpArrow)
        || Input.GetKeyDown (KeyCode.Z)
        || Input.GetKeyDown (KeyCode.W))
    {

```

If a jump button is pressed, this checks if the player is on the ground:

```
        if(grounded) {

```

Gets the rigid body attached to this script's `GameObject` and sets its `velocity` property using its current speed in direction `x` and whatever the speed `jump` was set to in direction `y`:

```
            GetComponent<Rigidbody2D>().velocity = new Vector2(
                GetComponent<Rigidbody2D>().velocity.x,
                jump);
        }
    }

```

Resets the a member variable and detects left and right inputs to change the speed in direction `x`:

```
    moveVelocity = 0;

    //Left Right Movement
    if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A)) {
        moveVelocity = -speed;
    }
    if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D)) {
        moveVelocity = speed;
    }

    GetComponent<Rigidbody2D>().velocity = new Vector2(
        moveVelocity,
        GetComponent<Rigidbody2D>().velocity.y);
}

```

---

The most notable problem with this script is that `grounded` doesn't ever seem to be set so I'm guessing you've omitted that part. Also, calling `GetComponent<>` is pretty expensive when done like this. It would make more sense to save the `Rigidbody2D` as a member variable from `Start()`:

```
private Rigidbody2d body;

void Start() {
    body = GetComponent<Rigidbody2D>();
}

```

Then you can just use `body.velocity`.

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


# Question
Title: Objects fall off screen, because stay one behind another[unity]
I m learning unity, I placed objects on a scene, camera is looking at them and displays them fine.

but in 3d, I can see they are one behind another, so when i hit play button, they just fall!

Pic:

is there any specific button like "align on one level" in unity?

# Answer
Probably you have attached `Rigidbody` or `Rigidbody2D` to them. Just mark as `Kinematic` in Rigidbody's configuration in `Inspector`. By attaching `Rigidbody` or `Rigidbody2D` your body will behave like real world object following all the physics rules. In this case it is falling down probably due to gravity. By marking as `Kinematic` it you defined your behaviour as not to receive any force or gravity but still a physical body.
> 2 votes

---
Tags: 2d, unity
---


# Question
Title: How would I implement a realistic stock market?
I'm making a corporation simulator, and it contains stocks. In the game you can buy and sell stocks, but I can't implement a realistic change in the price for them. How do I make them change up/down in a realistic way?

# Answer
> 1 votes
Rather unspecific to the programming language or the platform mentioned, but I would probably go for a greater change as a primary depiction of important stock change, and then generate a small fast change upon that to depict the hooky part of the stock graphs.

So basically:

1. You start at time T1. You're going towards time T2. Price at time T1 is P1. P2 is end price.
2. You generate a random number (probably based on some events, maybe?) for P2. This is your larger number target price.
3. You iterate towards it with a timestep. If you update a couple of times (denoted as Tt) between those timesteps, you do

> (T2 - T1)/Tt = Your time step
4. To get the price at this time, you do

> P1 + (P2 - P1)/Tt * AmountOfTimeStepsPassed
5. This will get you a pretty straight line, so you could look into something like Bezier or something to make a curve. But to get those hooks, you need to add a very small totally random deviation upon it. This needs to go from a small negative number to a small positive number!

> P1 + (P2 - P1)/Tt * AmountsOfTimeStepsPassed + SmallRandomNumber

---
Tags: java, android, simulations
---


title: Raycasting. Corner trap

text:
# Question
Title: Raycasting. Corner trap
In my top-down game character moves to target (pathfinding) also avoiding obstacles with *Raycasting*(Central ray with whiskers), but situation like on picture causes shiver and unneeded turning (problem similar to corner trap). Even if the whiskers angle is small (0.2 rad). How to deal with it?

**EDIT:**

Added more exact picture. I'm using Priority steering and if Raycast steering is not zero, it wins.

# Answer
> 1 votes
In the example of yours, seames that right whisker hits obstacle. In that case you must do a little strade left. In general you must elaborate evasion depending on central and lateral rays hits.

---
Tags: java, libgdx, raycasting, steering-behaviors, cornering
---


# Question
Title: In a 2D multiplayer game should I send the position of user to the server all the time?
In a 2D game where the user moves with the keyboard arrows, should the user send all the time he moves his position (x, y)?. If the user has some speed, the user would send (x, y) like 50 times pixel by pixel in just a second.

# Answer
> 0 votes
Probably you are using sockets. If so, then there is no issue in it. One thing, if your game has physics Angry Bird is type then you should pass relevant info. Like before shooting send positions per frame, after player shoots, then send force, angle, altitude and simulate through this information on other side. If this is not the case then no harm to send info per frame. If data is not very big.

---
Tags: networking, multiplayer
---


# Question
Title: Can't find the solution to the "shadow acne" problem
This is how it looks now:

This is the code that generate the shadow matrix an shaders source:

```
void shadow::calculateShadowMatrixFromLightPointOfView(vector3f lightPosition, vector3f lightDirection)
{
//this method, only bind the frame buffer:
//glBindFramebuffer(GL_FRAMEBUFFER, uiFramebuffer);
fboShadowMap.bindFramebuffer();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//this method only bind the shader
m_shader.bindShader();

//I'M not sure if this is ok..
float rangeX = globalData::windowWidth;
float rangeY = globalData::windowHeight;

m_ProjectionMatrix =  glm::ortho<float>(-rangeX,rangeX,-rangeY,rangeY, 0.05f,400.0);

m_currentLigthPosition = glm::lookAt(
glm::vec3(lightPosition.x,lightPosition.y,lightPosition.z),
glm::vec3(
lightDirection.x,
lightDirection.y,
lightDirection.z
),
glm::vec3(0,1,0)
);

glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);

mDepthBiasMVP = biasMatrix * m_ProjectionMatrix * m_currentLigthPosition;

}

```

This creates the frame buffer:

```
bool frameBuffer::createFrameBufferForDepthShadow(int width, int height)
{
if(uiFramebuffer != 0)return false;

iWidth = width;
iHeight = height;
glBindRenderbuffer(GL_RENDERBUFFER, uiFramebuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);

glGenFramebuffers(1, &uiFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, uiFramebuffer);

tFramebufferTex.createTexture(width, height, true);

tFramebufferTex.setFiltering(TEXTURE_FILTER_MAG_NEAREST, TEXTURE_FILTER_MIN_NEAREST);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glBindFramebuffer(GL_FRAMEBUFFER, uiFramebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, tFramebufferTex.getTextureID(), 0);
glDrawBuffer(GL_NONE);

// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    return false;
return true;
}

```

The width and height integers are 1024.

This creates the texture:

```
unsigned int CTexture::createTexture(int w,int h,bool isDepth)
{
glGenTextures(1,&uiTexture);
glBindTexture(GL_TEXTURE_2D,uiTexture);
glTexImage2D(GL_TEXTURE_2D,0,(!isDepth ? GL_RGBA8 : GL_DEPTH_COMPONENT),w,h,0,(isDepth ? GL_DEPTH_COMPONENT : GL_RGBA),GL_FLOAT,NULL);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

int i;
i=glGetError();
if(i!=0)
{
cout << "Error happened while loading the texture: " << i << "\n";
}
glGenSamplers(1, &uiSampler);
return uiTexture;
}

```

isDepth variable, is true when i use this function to construct de framebuffer.

Then in the shaders i use for shadows:

VERTEX SHADER:

```
#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 inPosition;

// Values that stay constant for the whole mesh.
uniform mat4 depthMVP;

void main(){
gl_Position = depthMVP*vec4(inPosition.xyz,1.0f);
}

```

FRAGMENT SHADER:

```
#version 330 core

// Output data
layout(location = 0) out float fragmentdepth;

void main(){
fragmentdepth = gl_FragCoord.z;
}
Finally to render shadow in the "world", i use this shaders:

```

VERTEX SHADER:

```
#version 330

uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 normalMatrix;
uniform mat4 modelMatrix;

uniform mat4 DepthBiasMVP;
smooth out vec4 ShadowCoord;

layout (location = 0) in vec3 inPosition;
layout (location = 1) in vec2 inCoord;
layout (location = 2) in vec3 inNormal;

smooth out vec2 texCoord;
smooth out vec3 vNormal;
smooth out vec3 vEyeSpacePos;
smooth out vec3 vWorldPos;

uniform float objOpacity;
smooth out float fObjOpacity;
uniform vec3 objColor;
smooth out vec3 vObjColor;

void main()
{
vec4 vEyeSpacePosVertex = modelViewMatrix*vec4(inPosition, 1.0);
gl_Position = projectionMatrix*vEyeSpacePosVertex;
texCoord = inCoord;
vec4 vRes = normalMatrix*vec4(inNormal, 0.0);
vNormal = vRes.xyz;
vEyeSpacePos = vEyeSpacePosVertex.xyz;
vec4 vWorldPosVertex = modelMatrix*vec4(inPosition, 1.0);
vWorldPos = vWorldPosVertex.xyz;

ShadowCoord = DepthBiasMVP * vWorldPosVertex;

fObjOpacity = objOpacity;
vObjColor = objColor;

}

```

FRAGMENT SHADER

```
#version 330

smooth in vec2 texCoord;
smooth in vec3 vNormal;
smooth in vec3 vEyeSpacePos;
smooth in vec3 vWorldPos;

smooth in vec3 vObjColor;
smooth in float fObjOpacity;
struct material
{
float specularIntensity;
float specularPower;
};
uniform material m_material;

out vec4 outputColor;

uniform sampler2D gSampler;
vec4 totalLight = vec4(0.0,0.0,0.0,0.0);
float visibility = 1.0f;

struct DirectionalLight
{
vec3 vColor;
vec3 vPosition;
vec3 vDirection;
float fAmbientIntensity;
float fStrength;
};

vec4 getDirectionalLightColor(DirectionalLight dirLight, vec3 vNormal)
{
float fDiffuseIntensity = max(0.0, dot(normalize(vNormal), -dirLight.vDirection));
return vec4(dirLight.vColor*(dirLight.fAmbientIntensity+fDiffuseIntensity)*dirLight.fStrength, 1.0);
}

uniform DirectionalLight sunLight;

uniform sampler2D shadowMap;
smooth in vec4 ShadowCoord;
vec2 poissonDisk[16] = vec2[](
vec2( -0.94201624, -0.39906216 ),
vec2( 0.94558609, -0.76890725 ),
vec2( -0.094184101, -0.92938870 ),
vec2( 0.34495938, 0.29387760 ),
vec2( -0.91588581, 0.45771432 ),
vec2( -0.81544232, -0.87912464 ),
vec2( -0.38277543, 0.27676845 ),
vec2( 0.97484398, 0.75648379 ),
vec2( 0.44323325, -0.97511554 ),
vec2( 0.53742981, -0.47373420 ),
vec2( -0.26496911, -0.41893023 ),
vec2( 0.79197514, 0.19090188 ),
vec2( -0.24188840, 0.99706507 ),
vec2( -0.81409955, 0.91437590 ),
vec2( 0.19984126, 0.78641367 ),
vec2( 0.14383161, -0.14100790 )
);

float getVisibility(sampler2D shadowMap, vec4 vShadowCoord, float windowWidth, float windowHeight)
{

float visibility = 1.0;
float bias = 0.0012;

for (int i=0;i<4;i++)
{
    int index = i;
    vec4 vShadowSmooth = vec4(vShadowCoord.x + poissonDisk[index].x/windowWidth, vShadowCoord.y + poissonDisk[index].y/windowHeight, (vShadowCoord.z)/vShadowCoord.w, 1.0);
    float fSub = texture(shadowMap, vShadowSmooth.st).r;

    if(fSub<vShadowCoord.z-bias){
        visibility -= 0.1*(1.0-fSub);

    }
}

return visibility;
}

void main()
{
vec3 vNormalized = normalize(vNormal);

totalLight += getDirectionalLightColor(sunLight, vNormal);

visibility =  getVisibility(shadowMap, ShadowCoord);

vec4 vTexColor = texture2D(gSampler, texCoord);
vTexColor.a = fObjOpacity;
vec4 vMixedColor = vTexColor*vec4(vObjColor,1.0);
outputColor = vec4(vMixedColor*totalLight*visibility);

}

```

As you can see in the pictures, the shadow have these horrible "acne" and i don know how to avoid it.

This is the order in wich the scene is rendered:

```
glViewport(0, 0, 1024, 1024);

//this function are described above
m_shadows->calculateShadowMatrixFromLightPointOfView(
dirLight->getPosition(),
dirLight->getDirection()
);

//render objects

glViewport(0, 0, globalData::windowWidth, globalData::windowHeight);

glBindFramebuffer(GL_FRAMEBUFFER, 0);

//render objects

```

# Answer
Shadow acne is a finicky thing to deal with sometimes. I would suggest double checking your projection matrix when filling the shadow map to make sure it is as "tight" as possible, that is its far plane as as close as possible.

This Microsoft page has a lengthy discussion on shadow acne and shadows in general, and how to fix it:

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

And another page I used when developing my shadows: http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/
> 1 votes

# Answer
Those darker triangles seem to say that its possible you havent set your normals right. Please check your normals for the vertices
> 0 votes

# Answer
This helped me with my shadow acne, maybe it will work for you?

In the shadow fragment shader:

```
gl_FragDepth = gl_FragCoord.z;
gl_FragDepth += smoothstep(0.0f, 1.0f, (1.0f - gl_FragDepth));

```

I don't know why `smoothstep` made a difference, but it did.
> 0 votes

---
Tags: opengl, shadows, shadow-mapping
---


# Question
Title: How did the SNES handle palettes of multiple sprites?
(This is assuming all graphics are stored in 4 bpp)

I understand that the SNES has a 256 color palette split into 16 palettes (each with 16 colors), and 8 of these represent palettes usable by sprites. Each sprite has a number representing which of these 8 palettes it uses. My question is *how* and *when* are the colors of these 8 palettes set typically.

Does the SNES copy the palette of a sprite into one of these 8 palettes when it is rendered? If so that would mean that only 8 sprites could be rendered simultaneously, and two sprites using the same colors would not share the palette which would be a waste of memory.

# Answer
> 14 votes
You're thinking of paletting from a modern perspective. That is, you're thinking of palettes as a part of the image, with each image owning its own palette.

In SNES-style hardware, palettes are *global*. You don't design your palette for your images, you design your images *for your palettes*. Well, it's a complex interplay between the two, but the needs of the palette primarily inform the art design of an image.

You don't get to change palettes in the middle of rendering a frame on the SNES. You set the palette at the beginning of the frame and then render everything in the frame with it. If you have a bunch of different sprites, then they need to be *designed* to share a lot of colors.

No SNES game developer would be so wasteful as to assign each sprite its own individual 8-color palette index (except *maybe* for the main character). Multiple sprites will use the same palette index. You have different palette indices for variety of sprites, but a lot of sprites are going to have to share. Which means that a palette has to serve the needs of multiple sprites.

---

The palette gets set by... the game setting the palette. This ain't rocket science.

At some point in time, the artists got together and came up with the available color palette. They probably went through several iterations of palettes, so that they could get the most out of the limited color palette space. They probably got together with the game designers so that they could have sprites that conflict in their palette, simply by forcing the developers not to put conflicting sprites in the same level.

Once all that was nailed down, they just did their work, making each sprite work with the palette colors they worked out Again, this probably involved many iterations.

The tools they used to create those images were not programs like Photoshop. Look around the Super Mario World rom-hacking scene for examples of the kinds of art tools they would use to generate sprites. Those tools are *given* a palette to work with, and you build your image only from those colors.

The source of the palette was not imaging software; it was designed explicitly by the developers.

For the SNES, image data and palette data live in different places. Images tend to live in large blocks of data in the ROM. Palettes tend to be hard-coded or otherwise live in tables in entirely different places in the ROM. The link between the two is merely a well-educated coincidence.

Take Super Mario World, for example. A sprite is a game construct that is attached to a level. But the images those sprites use depend on certain colors being in certain palette indices. How does that happen? Exactly and only because that level *just so happens* to put those colors there. That is, each level has a setting for which palettes to use (a palette of palettes). And if the level loads the right palette for the sprites that level uses, then everything appears fine.

This is one way such linkage happens. But individual games can do things a different way. Indeed, even in SMW, there are some palette entries that simply don't change from level to level, and many sprites use colors from them. So many sprites will be unaffected by level-specific palettes.

That's (part of) why you'll notice that many enemies show up in lots of levels, while others only show up in a few.

In any case, the point is that images and their palettes live in different places, and they get to the system in different ways. Games are carefully coded, in terms of level design or whatever, to use sprites when the right palette is available.

---
Tags: palette
---