# Question
Title: lag compensation for slow bullets (opposing players perspective)
I have figured out how the server is suppose to "rewind" for bullet collisions so that when you hit a player on your screen, the server will also say you hit them. However, when you press a key to shoot on your computer, it will take x ms until the opponent sees that you shot. by then, the moving opponent will be past the position that you fired while the sever says that they were still hit anyway.

What you will see: You aim and shoot at them, the bullet hits them and they take damage (this works out perfectly so far)

What they will see: They are moving and you shoot at them. the bullet trails behind them and misses, flying off into the distance. Yet they still take damage. How can this be fixed?

# Answer
# How Lag Compensation Works

This works because the *server* decides what bullets do, not your client and not their client.

The server does this by knowing how good (or bad) your ping is at any given moment and can use that to calculate player's positions at different points in time. Different games "rewind" these positions in different ways, but the general principle is maintaining a certain window of position data and when you shoot a hitscan gun (these are ones like TF2's heavy's minigun, scout's shotgun, etc: basically anything that uses fast moving bullets) the server looks at where players were Xms ago (based on YOUR ping) and then performs the hitscan (raycast) and applies damage as required.

*Slow* bullets are different. Slow bullets are tracked as entities. Types of slow bullets in TF2 would be grenades, rockets, and flamethrower particles. Each of these is tracked on the server by the server and lag compensation is only applied once (to see how far away from the shooting player they need to have moved before entering the standard update loop).

The reason you see the bullet "miss" but damage the player anyway has to do with what YOUR client knows about the positions of objects in the game and the interpolation your client does to make things move slowly. As players only care that damage is *dealt* and how common ping, lag, and lag compensation as known mechanics are these days player accept these sorts of inconsistencies when dealing with high-latency situations that there's not a real *problem* here. Rather, the problem is the fact that the lag compensation systems are *not good enough* in edge case scenarios or can offer an advantage to players who install a lightswitch in their eithernet cable...artificially introducing lag on demand that lets them have 3 seconds where their client is (effectively) in charge because TF2 gives a bias towards the shooter with some weapons (like the sniper rifle).

And as every programmer should know:

The client is a lying, cheating bastard.
> 1 votes

---
Tags: multiplayer, lag
---


# Question
Title: Unity c#: How to slow down rotation over time?
I am making a space combat game, in which the player can press q and e to roll their ship. I did this by adding torque to the rigid body when the player press q or e. However, after they do so, they keep on rotating. How do i make the angular velocity slowly go back to zero?

I tried using angular drag, but that does not work.

```
public float TurnSpeed;

public Rigidbody rb;

float currentturn;

Vector3 turn;

float turnEnabler;

bool iszero;

public float dampener;

// Update is called once per frame
void Update()
{

    rb.AddTorque(new Vector3(0, 0, turnEnabler));

    if (Input.GetKey("e"))
    {
        turnEnabler -= TurnSpeed;
    }

    if (Input.GetKey("q"))
    {
        turnEnabler += TurnSpeed;
    }

    rb.angularDrag = dampener;

}

```

}

# Answer
As Tom mentioned, after your second if call, you might have a third if statement such as:

`else if(!Input.GetKey("e") && !Input.GetKey("q")){turnEnabler /= 2;}`

Note that checking for 'q' again is redundant but might be helpful for completeness or readability if desired.

Also, since dividing by 2 will take a long time to really get to zero, you can (if you're bored) throw in something along the lines of:

`if(turnEnabler <= 0.01 && turnEnabler >= -0.01){turnEnabler = 0.00}`
> 3 votes

# Answer
From your example, at the end of `Update`, you can do something like

```
turnEnabler /= 2;

```

This would halve the rotating speed every frame, until it eventually reaches 0.

Depending on what kind of behavior you want, you can also try similar changes to the `turnEnabler` variable, like adding a fixed number every frame.
> 1 votes

---
Tags: unity, c#, rotation, rigidbody
---


# Question
Title: Directx 12 Root signature compatibility with pso
Can you bind a different root signature than the one that pipeline was created with? If so does it have to have exactly the same parameters or could it have like one more but the pipeline will ignore it?

Btw why is there no dx12 tag?

# Answer
If you use a different root signature than the PSO was created with you get (with the Debug device enabled):

```
D3D12 ERROR: ID3D12CommandList::DrawInstanced: The currently set Root Signature doesn't
match the currently set Pipeline State Object. This is invalid and can
lead to unexpected behavior. [ EXECUTION ERROR #201: COMMAND_LIST_DRAW_ROOT_SIGNATURE_MISMATCH]

```

Root signatures have to strictly match. As such, you typically try to design a few root signatures that you can use across a number of shaders.

> Another thing to note is that on some hardware, it's an error to not bind all the slots in a root signature before drawing. For this reason, I create different root signatures for textured vs. non-textured `BasicEffect` shaders in DirectX Tool Kit for DX 12.
> 1 votes

---
Tags: c++, directx, graphics-programming, directx12
---


# Question
Title: MonoGame / XNA Texture2D.SetData results in black texture
I use the following method to draw a box onto the screen:

```
private void DrawBox(Rectangle rect, Color color, Vector2 offset)
{
    Texture2D tex = new Texture2D(GraphicsDevice, rect.Width, rect.Height);
    Color[] data = new Color[rect.Width * rect.Height];

    for (int i = 0; i < data.Length; i++)
        data[i] = color;

    tex.SetData(data);

    var pos = new Vector2(rect.Location.X, rect.Location.Y) + offset;

    spriteBatch.Draw(tex, pos, Color.White);

    tex.Dispose();
}

```

However, this results in a completely black image being drawn onto the screen, regardless of the colour I pass to this method. Why is this happening and how can I fix this?

# Answer
You can draw a box using a precreated white pixel (1x1) texture and then draw this pixel using default spriteBatch.Draw method. Here's an example:

```
public static class Primitives
{
    private static Texture2D Pixel;

    private static void InitializePixel(SpriteBatch spriteBatch)
    {
        Pixel = new Texture2D(spriteBatch.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
        Pixel.SetData(new [] { Color.White });
    }

    public static void DrawBox(this SpriteBatch spriteBatch, Rectangle rect, Color color)
    {
        if (Pixel == null)
            InitializePixel(spriteBatch);

        spriteBatch.Draw(Pixel, rect, color);
    }
}

```
> -1 votes

---
Tags: c#, xna, monogame
---


# Question
Title: Different lighting models in deferred rendering
I would like to support a few different lighting models in my deferred renderer, such as: Phong OrenNayar and Cook-Torrance, so a small limited set to support a bit more than just a single lighting model.

What i came up with:
The most obvious way seems to simply branch in the shader based on some information stored in a texture during the geometry pass. I have come to learn however that branching in shaders is generally a bad idea (at least that's what i read everywhere). So I came up with a branch-less version by using the stencil buffer to mask each of the few shaders, and rendering each light multiple times, once for each lighting model. (The stencil buffer could be filled during the geometry pass and then stored in R8, and with some trickery you can use it as well for light masking.)

Now the question is, what is the best way to do this? Did I miss any better techniques? I could not find many usefull sources online.

# Answer
> 1 votes
One way to do it is to have 3 different shaders and simply using the one that you need at the time. There are a number of ways you can do this.

You could have 3 separate files (or just strings in your code) that contain your shaders, compile them and use them as necessary. That's easy to code up the first time, but maintenance becomes a pain because if you change some non-lighting related stuff in one shader you have to remember to change it in all.

So what I've done in the past is have a file or string that contains just the Phong lighting calculations in a function called something like `calculateLighting()`. Put that into its own file or string. For the Oran-Nayer, also make a function called `calculateLighting()` with the exact same parameters, and put it into a file or string. Same with the Cook-Torrance shader.

You'll also have your base shader that does everything except the lighting. Where you would normally have the lighting, simply call the function. At runtime you can take the Phong version, concatenate the base shader, and compile it. Then take the Oran-Nayer version, concatenate the base shader and compile it. Do the same thing with the Cook-Torrance version. Now, when you need to change something in the base shader, it take affect in all 3.

# Answer
> 0 votes
Unfortunately, branching based on result read from texture is going to be less efficient regarding shader complexity/occupancy than using the stencil trick that is mentioned.

The stencil trick will be a burden more on the CPU however, as there will be need to render each light multiple times and switch shaders in between. There is also need for a stencil buffer which uses GPU memory space and bandwidth. The stencilling path will be possibly harder to maintain and more error prone, so there is also that.

---
Tags: opengl, shaders, glsl, lighting, deferred-rendering
---


# Question
Title: How can I make the cursor avoid something completely?
I wrote some code for a UI button that causes the mouse to avoid it. I realize this is kind of a weird thing to do in a game design-wise, but this is a really weird game. I need a button that is not only unclickable, but also unhoverable. I got it mostly working, but I cannot seem to change the position before the mouse is drawn, probably because mouse movement is handled by the OS, unless there is a problem with my code that I missed. As a result, pushing the mouse against the button boundaries results in a stutter. The mouse briefly appears over the button before I can move it, so it is still possible to click the button.

A demonstration of the button avoidance and stutter: https://youtu.be/7tgIrJ\_vMDg

```
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out Point pos);

...

void Update () {
    var mousePos = Input.mousePosition;
    if (Application.isFocused && isOver) {

        //Get the current mouse position from OS so we can change it;
        Point cursorPos;
        GetCursorPos(out cursorPos);

        if (oldMousePos.x > xMin && oldMousePos.x < xMax)
        {
            //Coming from above or below. Figure out which one
            //and move mouse accordingly
            if (oldMousePos.y > uiPos.y)
                cursorPos.y -= (int)(rt.rect.height / 2 - (mousePos.y - uiPos.y));
            else
                cursorPos.y += (int)(rt.rect.height / 2 - (uiPos.y - mousePos.y));
        }
        else
        {
            //Coming from either left or right.
            if (oldMousePos.x < uiPos.x)
                cursorPos.x -= (int)(rt.rect.width / 2 - (uiPos.x - mousePos.x));
            else
                cursorPos.x += (int)(rt.rect.width / 2 - (mousePos.x - uiPos.x));
        }
        //Give new coordinates to OS to update mouse position
        SetCursorPos(cursorPos.x, cursorPos.y);
    }
    else
    {
        //track the old position to know what direction
        //they moved their mouse from so we can put it back
        oldMousePos = mousePos;
    }
}

```

I tried using the Cursor API to force it to software mode thinking that might fix it, but it still stutters, and I would prefer to use the default cursor anyway, and hardware mode if possible. Is there any way to work around this or remove the stutter?

# Answer
I’m guessing the problem is that you are changing the position of the mouse once per Unity frame (if you’re running at 60 FPS, that’s once every 16.67 ms), which is not the same timing that the OS uses to respond to the mouse moving.

My first thought would be to move the code in Update to run on a separate thread in a loop with no waiting. Note that you would be unable to interact with Unity APIs on this thread.
> 0 votes

# Answer
Hide the system mouse cursor with `Cursor.visible = false;` in some method which runs at the start of your game. Then create your own mouse cursor by reading the mouse coordinates and moving a sprite to the given screen location.

By taking control of mouse drawing like this you also open up many more opportunities to screw with the player's perception of their mouse cursor. Just keep in mind that you are now responsible for making sure that the cursor's draw position matches the logical position. That means unless you want to also forego the Unity mouse event handling for the UI system and roll your own.

I'm looking forward to getting trolled by your game.
> 0 votes

---
Tags: unity, gui, windows, mouse, operating-system
---


# Question
Title: What is the difference between a hotkey and a shortcut-key in a game?
I was wondering: What is the exact difference (if there is any) between a hotkey and a shortcut-key in a game? Some games for example allow the player to bind certain actions to a specific key and call this hotkey other games allow the same thing and call it shortcut or shortcut-key.

When would you use which term? Or are they enterily swappable?

# Answer
With "Shortcut", there is the implication that there is a more intuitive but also more elaborate way to perform the action (like navigating through a menu).

"Hotkey" is a more general term which can also cover actions which can *only* be performed with that keypress.

But in general, these two terms are pretty interchangeable.

Another term you can use to describe keys getting assigned to do things is "key binding".
> 3 votes

---
Tags: mouse, terminology, keyboard
---


title: Help with dual quaternion skinning

text:
# Question
Title: Help with dual quaternion skinning
I'm trying to convert my code to use dual quaternion skinning instead of matrix skinning because i just can't get the skinning matrix created correctly from bones+weights using matrices.

Edit: just to clarify, if each vert has only one bone the matrix version did skin correctly.

But it's just not working and i really don't understand why, i'm using code i found here:

http://www.chinedufn.com/dual-quaternion-shader-explained/

http://donw.io/post/dual-quaternion-skinning/

I've looked at the assorted papers often brought up in the answers to these questions, but for the most part i just don't understand them. I'm not even entirely sure how the \[x, y, z, w\] of a glm::quat correspond to the \[1, i, j, k\] of a quaternion--I think that w might be the scalar because it goes first in the actual byte order of the glm::quat struct, but i'm not sure.

Anyway, in my shader bindings i have:

```
void gltfShader::bindBones(const std::vector<glm::mat4> & bones)
{
    std::vector<glm::fdualquat> dual_quats(std::min<int>(bones.size(), 64));

    glm::quat r;
    glm::vec3 t, s, sk;
    glm::vec4 pr;
    glm::fdualquat dq;

    for(size_t i = 0; i < dual_quats.size(); ++i)
    {
        glm::decompose(bones[i], s, r, t, sk, pr);

        dq[0] = r;
        dq[1] = glm::quat(t.x, t.y, t.z, 0) * r * .5f;

        dual_quats[i] = dq;
    }

    glUniformMatrix2x4fv(u_bones, dual_quats.size(), GL_FALSE, (float*) &dual_quats[0]);
}

```

In the vertex shader:

```
mat2x4 GetBoneTransform(ivec4 joints, vec4 weights)
{
    float sum_weight = weights.x + weights.y + weights.z + weights.w;

    // Fetch bones
    mat2x4 dq0 = u_bones[joints.x];
    mat2x4 dq1 = u_bones[joints.y];
    mat2x4 dq2 = u_bones[joints.z];
    mat2x4 dq3 = u_bones[joints.w];

    // Ensure all bone transforms are in the same neighbourhood
    weights.y *= sign(dot(dq0[0], dq1[0]));
    weights.z *= sign(dot(dq0[0], dq2[0]));
    weights.w *= sign(dot(dq0[0], dq3[0]));

    // Blend
    mat2x4 result =
        weights.x * dq0 +
        weights.y * dq1 +
        weights.z * dq2 +
        weights.w * dq3;

    result[0][3] += int(sum_weight < 1) * (1 - sum_weight);

    // Normalise
    float norm = length(result[0]);
    return result / norm;
}

mat4 GetSkinMatrix()
{
    mat2x4 bone = GetBoneTransform(a_joints0, a_weights0);

    vec4 r = bone[0];
    vec4 t = bone[1];

    return mat4(
        1.0 - (2.0 * r.y * r.y) - (2.0 * r.z * r.z),
              (2.0 * r.x * r.y) + (2.0 * r.w * r.z),
              (2.0 * r.x * r.z) - (2.0 * r.w * r.y),
        0.0,

              (2.0 * r.x * r.y) - (2.0 * r.w * r.z),
        1.0 - (2.0 * r.x * r.x) - (2.0 * r.z * r.z),
              (2.0 * r.y * r.z) + (2.0 * r.w * r.x),
        0.0,

              (2.0 * r.x * r.z) + (2.0 * r.w * r.y),
              (2.0 * r.y * r.z) - (2.0 * r.w * r.x),
        1.0 - (2.0 * r.x * r.x) - (2.0 * r.y * r.y),
        0.0,

        2.0 * (-t.w * r.x + t.x * r.w - t.y * r.z + t.z * r.y),
        2.0 * (-t.w * r.y + t.x * r.z + t.y * r.w - t.z * r.x),
        2.0 * (-t.w * r.z - t.x * r.y + t.y * r.x + t.z * r.w),
        1);
}

```

EDIT: video of the results:

https://youtu.be/8jIt\_Xhhffk

The one on the left is supposed to be a walk cycle, the one on the right is supposed to be this:

https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/Monster

# Answer
changing this:

```
for(size_t i = 0; i < dual_quats.size(); ++i)
{
    glm::decompose(bones[i], s, r, t, sk, pr);

    dq[0] = r;
    dq[1] = glm::quat(t.x, t.y, t.z, 0) * r * .5f;
//this produces worse results:
//   dq[1] = glm::quat(0, t.x, t.y, t.z) * r * .5f;

    dual_quats[i] = dq;
}

```

to this:

```
for(size_t i = 0; i < dual_quats.size(); ++i)
{
    r = glm::quat_cast(bones[i]);
    t = glm::vec3(bones[i][3]);

    dq[0] = r;
    dq[1] = glm::quat(0, t.x, t.y, t.z) * r * .5f;

    dual_quats[i] = dq;
}

```

fixed it. I really have no idea why.
> 1 votes

---
Tags: opengl, glsl, skeletal-animation
---


# Question
Title: What happens when a game is burned to a CD?
What is happening behind the scenes when you take a code base and "burn" it to a CD be read by a game console?

# Answer
Generally, nothing special is happening "behind the scenes" when burning a disc containing a game than when burning any *other* collection of bits to a disc. If you're interested in that basic process, this isn't the place to ask (as it's not game development specific), but you could start by searching for the terms "optical disc manufacturing" or "how CD burners work."

There are, however, two points that are somewhat related to game development:

* As implied above, the mass-market production of optical discs for eventual sale in stores (et cetera) is typically done via a different technique ("duplication") than the one you'd see at home using your own CD "burner." Game publishers would typically create some kind of master image for the final game and send that to a duplication manufacturer.
* Some consoles that used optical discs used nonstandard or unique formats, or variations on those formats (for example, PlayStation discs had intentional bad blocks to identify them to the correct hardware). This was generally done for copy-protection or region-locking purposes, and may have resulted in needing specialized software or workflows to produce a working disc (for example, software that would not balk at the intentional bad sectors).
> 1 votes

---
Tags: architecture, source-code
---


# Question
Title: What type of 3D engine is the original Quake engine?
What type of 3D engine is the original ID Software Quake engine (1996)? What is the correct terminology? Is there a particular simple term that describes this type of engine? E.g. the original Wolfenstein 3D engine is I believe a raycaster, what is the Quake engine?

Articles such as http://en.wikipedia.org/wiki/Quake\_engine describe how it works, but do not seem to put it into a particular category.

I'm interested in the correct name for both the software and the hardware accelerated version of Quake.

# Answer
There isn't a single term for it (other than "Quake-like" or similar), because rendering engines can differ or not in a variety of ways.

That said, the Quake rendering engine does has several identifying features:

* it's a *true 3D* engine, in that it could render actual 3D geometry and not the sort of extruded and offset 2D maps of some of its predecessors.
* it is a *brush* engine, in that it uses oriented convex 3D geometry to define interior spaces of the game world.
* it is a *BSP* engine, because after pre-processing the brushes that define a map, a BSP tree is built for dealing with polygon visibility.
* it used *scanline rasterization*, as noted in the comments, to produce the final scene image.

...and so on. There are several other ways in which you could classify the engine (such as how it rendered the environment front-to-back but still wrote to a depth buffer for handling the rendering of mobile objects, like characters). But you can already see how calling it a "true-3D-brush-and-BSP-using-scanline-rasterization-engine" starts to get a little cumbersome. So we just call it a "Quake" engine.

You can see examples of how the same *basic* engine can still handle some things quite differently in exploring how the old Thief games rendered the world.

And of course, if you really want the nitty gritty details of Quake's engine, you can peruse Michael Abrash's extremely in-depth tome on the matter.
> 2 votes

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


title: HashMap or LinkedList

text:
# Question
Title: HashMap or LinkedList
I'm working on a 2D game for Android using LibGDX in Java. In my game I got lots of enemies, bullets and other stuff. I hold a hash map, which every cell holds a reference to an array list of that kind of objects. For example:

HASH MAP-\>

Enemies = \[enemy1,enemy2,enemy3\]

Bullets = \[bullet1,bullet2\] etc...

In my render() loop I run with an iterator on the hash map and run through all the objects in every array list, calling each one's update() method.

I wonder, would it be faster holding a linked list to every kind of objects instead of array list and running through that linked list?

Thanks!

# Answer
> 0 votes
> I wonder, would it be faster holding a linked list to every kind of objects instead of array list and running through that linked list?

If all you are doing is iteration, stick with the `ArrayList`. The difference in iteration performance for an `ArrayList` versus a linked list is small-to-nonexistent, and favors the `ArrayList` (because of contiguity and cache misses).

The reason to favor a linked list would be if you're need to insert and remove from the interior of the list often, and need items to maintain order (so you can't do the swap-and-pop tricks of sorting "dead" items to the back of a list). It doesn't sound like that's the case here, based on your presented problem description.

---

That said, the above is theoretical in nature; you should really profile your actual code to be sure. I suspect your bottleneck is not where you think it is, and even if it is, profiling the before-and-after scenario will let you know exactly how better or worse you've made things with changes.

---
Tags: java, android, libgdx
---


# Question
Title: Appropriate use for prefabs in Unity in a coordinate based game?
I am wondering how exactly to use prefabs in Unity for my discretely coordinate-based game. Should they only be for gameObjects that are exactly the same? Or can they have small variations?

Example: a treasure chest is interactable and it holds items, so I would make it an empty gameObject, add an interactable component and then an itemContainer component and then drag and drop it into my prefabs folder and delete the instance in the scene.

But the question remains, if I make this treasure chest a prefab, how do I edit the itemContainer component of this treasure chest? Moreover, how would I serialize it for later use, and organize my data? Would I have to use external data files and reconstruct the ItemContainerComponent, just for a treasure chest? That sounds like a lot of work.

If I edit the itemContainer component as a prefab, then all treasure chests will have the same items. Obviously this is not feasible.

Do I drag my treasureChest prefab from the prefabs folder and then simply drop it in the game? That's how most people use it, right?

I would prefer not to just drag and drop the prefabs, because I want a more industrialized approach, and I do want some way of saving what is in each treasure chest. I can't for the life of me figure out a good way. Help appreciated!

EDIT: I see the link provided that marks this as a possible duplicate. However, none of the answers in that link are clear enough to be useful to me, e.g., the "factory." It would be nice if someone could explain the factory idea in more concrete terms.

# Answer
Prefabs are for anything you want to create at run time. After it has been instantiated, you can modify any and all properties without affecting other "copies."

For instance, I have a scrolling list of upgrades in my game, each one had a name, cost, and picture. But I don't want to hand-create 100 menu items (god forbid the costs or names change!). Instead I create a prefab and a`List<Upgrade>` object. Then at run time, I iterate over the list, clone a prefab, imagery it into the scrolling area, set the text and sprite vales to the details in the `Upgrade` object, and bam, the game creates the scrolling menu for me.
> 1 votes

# Answer
A prefab is identical when instantiated. That doesn't mean it can't immediately show variety.

For example, in one of my games I have a prefab of a house that is used multiple times. The house is made from modular parts (wall segments, doors, roof parts, etc.). My prefab includes a script that in its Start() method picks one of its children at random and keeps it, while calling Destroy() on the others. This one, every time I instantiate a house, it will have a random wall segment in this place, a random set of props around it, sometimes a small and sometimes a big window here, etc.

There are other ways to make prefabs vary. For simple values, like the number of gold coins in a treasure chest, you can simply define a range (lowest and highest amount) in the prefab and in Start() call Random.Range() to set the actual demand for this chest. Voila, every chest now has a random amount of coins between your values.
> 0 votes

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


# Question
Title: How to gain accurate results with Painter's algorithm?
A while ago I asked how to determine when a face is overlapping another. The advice was to use a Z-buffer.

However, I cannot use a Z-buffer in my current project and hence I would like to use the Painter's algorithm. I have no good clue as to when a surface is behind or in front of another, though. I've tried numerous methods but they all fail in edge cases, or they fail even in general cases.

This is a list of sorting methods I've tried so far:

* Distance to midpoint of each face
* Average distance to each vertex of each face
* Average z value of each vertex
* Higest z value of vertices of each face and draw those first
* Lowest z value of vertices of each face and draw those last

The problem is that a face might have a closer distance but is still further away. All these methods seem unreliable.

**Edit:** For example, in the following image the surface with the blue point as midpoint is painted over the surface with the red point as midpoint, because the blue point is closer. However, this is because the surface of the red point is larger and the midpoint is further away. The surface with the red point should be painted over the blue one, because it is **closer**, whilst the midpoint distance says the opposite.

What exactly is used in the Painter's algorithm to determine the order in which objects should be drawn?

# Answer
> 15 votes
Usually the distance of the midpoint of a polygon to the camera is being used for z-sorting. The painter's algorithm cannot be 100% accurate by it's nature. There will always be cases where sorting will fail, no matter what reference point you use.

If you want correct z-sorting with the painter's algorithm, you'll have to slice overlapping polygons into smaller parts (eg. by using a quad-tree) and sort these parts individually. This can become quite heavy on the CPU though..

Found this Powerpoint file that illustrates the issue nicely (PDF Version).

# Answer
> 1 votes
In such cases for me it always worked using bsp-trees. Split the scene until you have convex set of polygons in bsp-tree's node and then you can easily sort polygons within the nodes. Note that by sorting polygons from the bsp-tree node it seems like the same problem as you described above, but there is a condition not so obvious - after constructing the bsp-tree all the problematic cases are already solved - in node you should end up with set of polygons from which the convexity test must pass - if you pick a plane from one polygon from this set, the rest of the polygons are all either in front of the plane or behind the plane. Using that info makes sorting easy - the sorting functor takes 2 polygons - check in which half-space is the 1st polygon against the 2nd polygon and also check the placement of camera against the second polygon. The 1st polygon is visually behind the 2nd polygon if: * side(p1, p2) == infront && side(camera, p2) == behind * side(p1, p2) == behind && side(camera, p2) == infront There are however certain cases where above condition if called with (p1, p2) tells that p1 is visually behind p2, and if called with (p2, p1), tells that p2 is visually behind p1 - in such cases the order doesn't matter as the polygons don't overlap on screen from the camera.

Note also that the tests for determining the side of camera placement against polygons and traversing of bsp-tree are slightly different when dealing with orthographic and perspective projection.

If you cannot afford splitting of the input polygons, I think you are out of luck.

---
Tags: 3d, algorithm, objects, face
---


# Question
Title: How best to structure/manage hundreds of 'in-game' characters
I've been making a simple RTS game, which contains hundreds of characters like Crusader Kings 2, in Unity. For storing them the easiest option would be to use scriptable objects, but that isn't a good solution as you cannot create new ones at runtime.

So I created a C# class called "Character" which contains all data. Everything is working fine, but as the game simulates it constantly creates new characters and kill some characters (as in-game events happen). As the game continuously simulates it creates 1000s of characters. I added a simple check to make sure a character is "Alive" while processing its function. So it helps performance, but I can't remove "Character" if he/she is dead, because I need his/her information while creating the family tree.

Is a list is the best way to save data for my game? Or it will give problems once there are 10000s of a character created? One possible solution is to make another list once the list reaches a certain amount and move all dead characters in them.

# Answer
There are three things you should consider:

1. Does it *actually* cause a performance problem? 1000s is, well, not many actually. Modern computers are awfully fast and can handle a lot of stuff. Monitor how much time character processing is taking and see whether it's actually going to cause a problem before worrying too much about it.
2. Fidelity of currently minimally active characters. A frequent mistake of beginner Game Programmers is to obsess over precisely updating off-screen characters in the same way as on-screen ones. This is a mistake, no-one cares. Instead you need to seek to create the *impression* that off-screen characters are still acting. By reducing the amount of update characters that are off-screen receive you can dramatically decrease processing times.
3. Consider Data-Oriented-Design. Instead of having 1000 character objects and calling the same function for each, have an array of the data for the 1000 characters and have one function loop over the 1000 characters updating each in turn. This kind of optimisation can dramatically improve performance.
> 25 votes

# Answer
In this situation, I'd suggest using Composition:

> The principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality)

---

In this case, it sounds like your `Character` class has become god-like, and contains all the details for how a character operates at *all* stages of it's lifecycle.

For example, you note that the dead characters are still required - as they're used in the family trees. However, it's unlikely that all the information and functionality of your alive characters, is still needed just to display them in a family tree. They may for example, simply need names, date of birth and a portrait icon.

---

The solution, is to split the separate parts of your `Character` into sub-classes, that the `Character` owns an instance of. For example:

* `CharacterInfo` may be a simple data-structure with the name, date of birth, date of death and faction,
* `Equipment` may have all the items your character has, or their current assets. It may also have the logic that manages these in functions.
* `CharacterAI` or `CharacterController` may have all the information needed about the character's current goal, their utility functions etc. And it may also have the actual update-logic that co-ordinates the decision making/interaction between it's individual parts.

Once you've split the character up, you no longer need to check an Alive/Dead flag in the update loop.

Instead, you'd simply make an `AliveCharacterObject` that has the `CharacterController`, `CharacterEquipment` and `CharacterInfo` scripts attached. To "kill" the character, you simply remove the parts that are no longer relevant (such as the `CharacterController`) - it will now not waste memory, or processing time.

Note, how the `CharacterInfo` is likely the only data actually needed for the family tree. By decomposing your classes into smaller pieces of functionality - you can more easily keep that small object of data after death, without needing to keep the entire AI-driven character.

---

It's worth mentioning that this paradigm is the one Unity was built to use - and is why it handles things with lots of separate scripts. Building large god-objects is rarely the best way to handle your data in Unity.
> 12 votes

# Answer
When you have a large amount of data to handle and not every data-point is represented by an actual game object, then it is usually not a bad idea to forego Unity-specific classes and just go with plain old C# objects. That way you minimize overhead. So you seem to be on the right track here.

Storing all characters, living or dead, in one List (or array) can be useful because the index in that list can serve as a canonical character ID. Accessing a list position by index is a very fast operation. But it might be useful to keep a separate list of the IDs of all living characters, because you will likely need to iterate those far more often than you will need the dead characters.

As your implementation of your game mechanics makes progress, you might also want to look at what other kind of searches you perform the most. Like "all living characters in a specific location" or "all living or dead ancestors of a specific character". It might be beneficial to create some more secondary data-structures optimized for these kinds of queries. Just remember that each of them must be kept up-to-date. This requires additional programming and will be a source of additional bugs. So only do it if you expect a notable performance increase.

CKII "prunes" characters from its database when it deems them as unimportant to save resources. If your pile of dead characters consumes too many resources in a long-running game, then you might want to do something similar (I don't want to call this "garbage collection". Maybe "respectful incremator"?).

*If* you actually have a game object for every character in the game, then the new Unity ECS and Jobs system might be useful to you. It is optimized for handling a large number of very similar game objects in a performant way. But it forces your software architecture into some very rigid patterns.

By the way, I really like CKII and the way it simulates a world with thousands of unique AI-controlled characters, so I am looking forward to playing your take on the genre.
> 7 votes

# Answer
You don't need to be simulating/updating thousands of characters when only a few are near the player. You only need to update what the player can actually see at the current point in time, so characters that are further away from the player should be suspended until the player is closer to them.

If this doesn't work because your game mechanics require distant characters to show passage of time, you can update them in one "big" update when the player gets closer. If your game mechanics require each character to actually respond to in-game events as they happen, no matter where the character is in relation to the player or the event, then it might work to reduce the frequency at which characters further from the player are updated (i.e. they are still updated in sync with the rest of the game, but not as often, so there will be a slight delay before distant characters respond to an event but this is unlikely to cause a problem or even be noticed by the player). Alternatively you might want to use a hybrid approach, such as only updating nearby characters in response to an event that would affect them but letting characters far from both the player and the event remain suspended.
> 1 votes

# Answer
# Clarification of the question

> I've been making a simple RTS game, which contains hundreds of characters like Crusader Kings 2 in a Unity.

In this answer, I am assuming that the whole game is supposed to be like CK2, instead of only the part about having a lot of characters. Everything you see on the screen in CK2 is easy to do and will neither endanger your performance nor be complicated to implement in Unity. The data behind it, that's where it gets complex.

# No-functionality `Character` classes

> So I created a C# class called "Character" which contains all data.

Good, because a character in your game *is* just data. What you see on the screen is just a representation of that data. These `Character` classes are the very heart of the game and as such are in danger of becoming "god objects". So I would advise extreme measures against that: Remove all functionality from those classes. A method `GetFullName()` that combines the first and last name, OK, but no code that actually "does something". Put *that* code into dedicated classes that do one action; e.g. a class `Birther` with a method `Character CreateCharacter(Character father, Character mother)` will turn out much cleaner than having that functionality in the `Character` class.

# Don't store data in code

> For storing them the easiest option would be to use scriptable objects

No. Store them in JSON format, using Unity's JsonUtility. With those no-functionality `Character` classes, it should be trivial to do. That will work for the initial setup of the game as well as for storing it in savegames. However, it's still a boring thing to do, so I just gave the easiest option in your situation. You could also use XML or YAML or any format really, as long as it can still be read by humans when it's stored in a text file. CK2 does the same, actually most games do. It's also excellent setup for allowing people to mod your game, but that's a thought for much later.

# Think abstract

> I added a simple check to make sure character is "Alive" while processing \[...\] but I can't remove "Character" if he is dead because I need his info while creating the family tree.

This one is easier said than done, because it often collides with the natural way of thinking. You're thinking in a "natural" way, of a "character". However, in terms of your game, it seems like there are at least 2 different types of data that "is a character": I'll call it `ActingCharacter` and `FamilyTreeEntry`. A dead character's `FamilyTreeEntry` doesn't need to be updated and probably needs a whole lot less data than an active `ActingCharacter`.
> 1 votes

# Answer
I'm going to speak from a little bit of experience, going from a rigid OO-design to an Entity-Component-System (ECS) design.

A while back I was just like you, I had a bunch of different types of things that had similar properties and I built out various objects and tried to use inheritance to solve it. A very smart person told me *don't* do that, and instead, use Entity-Component-System.

Now, ECS is a big concept, and it's tough to get right. There's a lot of work that goes into it, properly building entities, components, and systems. Before we can do that, though, we need to define the terms.

1. **Entity**: this is the *thing*, the player, animal, NPC, *whatever*. It's a thing that needs components attached to it.
2. **Component**: this is the *attribute* or *property*, such as a "Name" or "Age", or "Parents", in your case.
3. **System**: this is the logic behind a component, or a *behaviour*. Typically, you build one system per component, but that's not always possible. Additionally, sometimes systems need to influence *other* systems.

So, here's where I would go with this:

First and foremost, create an `ID` for your characters. An `int`, `Guid`, whatever you like. This is the "Entity".

Second, start thinking about the different behaviours you have going on. Things like the "Family Tree" — that's a behaviour. Instead of modeling that as attributes on the entity, build a system that holds *all that information*. The system can then decide what to do with it.

Likewise, we want to build a system for "Is the character alive or dead?" This is one of the most important systems in your design, because it influences all the others. Some systems can delete the "dead" characters (such as the "sprite" system), other systems can internally re-arrange things to better support the new status.

You'll build out a "Sprite" or "Drawing" or "Rendering" system, for example. This system will have the responsibility of determining what sprite the character needs to be displayed with, and how to display it. Then, when a character dies, remove them.

Additionally, an "AI" system that can tell a character what to do, where to go, etc. This should interact with many of the other systems, and make decisions based on them. Again, dead characters can probably be removed from this system, since they're not really doing anything anymore.

Your "Name" system and "Family Tree" system should probably keep the character (alive or dead) in memory. This system needs to recall that info, regardless of what the state of the character is. (Jim is still Jim, even after we bury him.)

This also gives you the benefit of *changing when a system reacts* more efficiently: the system has it's own timer. Some systems need to fire rapidly, some don't. This is where we start getting into what makes a game run efficiently. We don't need to recalculate the weather every millisecond, we can probably do that every 5 or so.

It also gives you more creative leverage: you can build a "Pathfinder" system that can handle the calculation of a path from A-to-B, and can update as-necessary, allowing the Movement system to say "where do I need to go next?" We can now fully separate these concerns, and reason about them more effectively. Movement doesn't need to find the path, it just needs to get you there.

You'll want to expose some parts of a system to the outside. In your `Pathfinder` system you'll probably want a `Vector2 NextPosition(int entity)`. This way, you can keep those elements in tightly-controlled arrays or lists. You can use smaller, `struct` types, which can help you keep components in smaller, contiguous memory blocks, which can make system updates *much* faster. (Especially if external influences to a system are minimal, now it only needs to care about it's internal state, such as `Name`.)

But, and I cannot stress this enough, now an `Entity` is just an `ID`, including tiles, objects, etc. If an entity doesn't belong to a system, then the system won't track it. This means we can create our "Tree" objects, store them in the `Sprite` and `Movement` systems (the trees won't move, but they have a "Position" component), and keep them out of the other systems. We no longer need a special list for trees, since rendering a tree is no different than a character, aside from paperdolling. (Which the `Sprite` system can control, or the `Paperdoll` system can control.) Now our `NextPosition` can be slightly rewritten: `Vector2? NextPosition(int entity)`, and it can return a `null` position for entities it doesn't care about. We also apply this to our `NameSystem.GetName(int entity)`, it returns `null` for trees and rocks.

---

I'll draw this to a close, but the idea here is to give you some background on ECS, and how you can *really* leverage it to give you a better design on your game. You can increase performance, decouple unrelated elements, and keep things in a more organized fashion. (This also pairs well with functional languages / setups, like F# and LINQ, which I highly recommend checking out F# if you haven't already, it pairs *very* well with C# when you use them in conjunction.)
> 0 votes

# Answer
As you are doing this in Unity, the easiest approach is this:

* create one game object per character or unit type
* save these as prefabs
* you can then instantiate a prefab whenever needed
* when a character is killed, destroy the gameobject and it won't take up any CPU or memory anymore

In your code, you can keep references to the objects in something like a List to save you from using Find() and its variations all the time. You are trading CPU cycles for memory, but a list of pointers is pretty small so even with a few thousand objects in it that should not be much of a problem.

As you progress through your game, you will find that having individual game objects gives you tons of advantages, including navigation and AI.
> -1 votes

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


# Question
Title: Why can't we put GameObject's into a NativeArray and pass them to a Job?
I just started using the Unity Job System.

It has a lot of limitations. You have to use NativeArray with it and NativeArray doesn't allow many types, notably GameObject's. It says there is a bug that you have to use non-nullable types. Why can't the job system operate directly on game objects?

# Answer
> 2 votes
The Unity team explains this restriction in the documentation on The Safety System in the C# Job System as a way to avoid race conditions in multithreaded code:

> The C# Job System solves this by sending each job a copy of the data it needs to operate on, rather than a reference to the data in the main thread. This copy isolates the data, which eliminates the race condition.
>
> The way the C# Job System copies data means that a job can only access blittable data types. These types do not need conversion when passed between managed and native code.
>
> The C# Job System can copy blittable types with `memcpy` and transfer the data between the managed and native parts of Unity. It uses `memcpy` to put data into native memory when scheduling jobs and gives the managed side access to that copy when executing jobs. For more information, see Scheduling jobs.

GameObjects are more complicated constructs, with different representations between the native & managed side (where the GameObject we use in C# is more like a handle, leading to its interesting behaviour around null / destruction)

We can't trivially copy a block of GameObjects out of the main game thread and then copy them back. For one thing, what if the object was destroyed or modified on the main thread in the meantime? References to the original GameObjects and their components wouldn't match up to the copies, so the whole thing gets pretty unwieldy to marshal back and forth to native code.

Instead, think about the logical transformations you need to perform on a group of GameObjects, and prepare a blittable data structure that contains the information needed for that transformation. Then you can use a job to perform the transformation, and upon completion, apply the results/conclusions back to your GameObjects.

---
Tags: unity, unityscript
---


# Question
Title: How should I be loading a player's content and its bullets content later in the game
I'm trying out Monogame because my course has a simple game programming class in it which is just going over basics. The final project will be using Monogame so I've been getting ahead and making my game.

Anyway, each player (Tank) has a list of Shells (bullets) and a list of Tracks (tank tracks). I load their content in the player's `LoadContent` method. `LoadContent` is called when the game is ran.

Let's say I wanted to add a new player sometime later in the game for whatever odd reason. I would do something along the lines of:

```
 entityManager.Add(new Player("Player Name", resourceManager.GetTexture("BlueTank"))
 {
      set initial position and keybinds here,
 };

```

This successfully creates a new player and loads its texture but what about its bullets textures, sound effects, track textures etc... Since `LoadContent` only gets called once at the start the code below will not run.

Example of the player's `LoadContent` method:

```
 // Match the players bullets with the players colour
 switch (Texture.Tag)
 {
      case "BlueTank":
           shellTexture = resourceManager.GetTexture("BlueShell");
           break;
      case "DarkTank":
           shellTexture = resourceManager.GetTexture("DarkShell");
           break;
 }

 // After this I use the resourceManager to set private Texture2D's and sound effects for the bullets, tracks and player.

 // e.g.
 trackTexture = resourceManager.GetTexture("Track");

```

When I finally shoot a bullet I set the bullets texture and sound effect properties to the private ones in the player.

When a player dies I currently just set their `IsActive` bool to false and the entity manager will remove them completely so I'm stuck on how to load content again.

I feel like I'm overthinking this but I can't seem to find a clean and simple way to get this done. Also I'm bad at explaining things hopefully this isn't too much of a mess.

**Edit**: Would it be a bad idea to pass the resource manager in the players constructor and just create a method for loading that is called in the players constructor? That way when a player is created the content is loaded for that player. It's only a small game for a basic school project. I could potentially do all the content setting outside of the player itself and in the GameplayState by looping through unloaded entities or something.

# Answer
> 1 votes
The way how I see and use Loadcontent is likely different than yours. But I prefer to use loadcontent to load all the content at once, on different variables each. If it's a small game, then performance doesn't matter much.

When you're loading content, then that content is ready to be used. but the draw method decides when the content should be visible on the screen.

So instead of using LoadContent to change textures, I use a different method to set these variables to their right object.

For example:

```
public Texture blueShellTexture = new Texture();
public Texture darkShellTexture = new Texture();
public Texture shellTexture = new Texture();   //the texture that chooses the right texture

Loadcontent () {
    blueShellTexture = resourceManager.GetTexture("BlueShell");
    darkShellTexture = resourceManager.GetTexture("DarkShell");
}

```

Then I can use a different method (or property) to set the texture:

```
public void setShelltexture () {
    switch (Texture.Tag)
    {
        case "BlueTank":
           shellTexture = blueShellTexture;
           break;
        case "DarkTank":
           shellTexture = darkShellTexture;
           break;
    }
}

```

As for your `isActive` bool, you can use a method that changes all values to their base values, and call that method when you restart the game, so the tank will 'reset' itself. For example:

```
public reset(){
    isActive = true;
    lives = 3;
    //add move default values here...
}

```

I hope this helps you out.

# Answer
> 0 votes
When the size of the assets in your game is manageable, then you should consider to just load every single asset at game start and keep all of it in memory while the game is running. That really saves you a lot of headache which would otherwise be caused if you try to load assets while the game is running.

But there are also some good reasons why you would not want to do this:

* You want to keep your initial loading time as short as possible.
* You have more assets than you can fit into RAM.
* You don't know about all assets at game start, for example because your game loads user-generated assets from the Internet.

When I read between the lines of the question, then I do not get the impression that any of these reasons apply here. But if they do, then you might want to use a resourceManager which keeps track of which assets are already loaded. When the asset is already loaded, it just returns the copy from memory. When the asset is not yet loaded, then there are multiple possible solution, ranging from simple but crude to complex but elegant:

* Block until the asset is loaded. This is easy to do, but might result in some notable stuttering whenever a new object with unloaded assets appears in the game.
* Return a placeholder asset (like an empty image) which then gets replaced with the actual asset as soon as it is loaded.
* Never return an asset. Have the caller pass a callback-function. As soon as the asset is ready, the callback-function is called with the asset as an argument.

---
Tags: c#, xna, monogame
---


# Question
Title: Is Pushdown Automata better for user input than Hierarchical State Machine?
I saw an example of code using HSM for user input, but to me it seems that Pushdown Automata would be a better fit. I'm confused.

If I'm right, then after Hierarchical State Machine exits a superstate via substate, and comes back, it must start at a default state and cannot return to the substate it left earlier(unless of course, that default state is the substate). And then, if I'm right, Pushdown Automata could replace that need, as it can return to an older state via its stack and discarding of states.

Say I have an actor I control, and it has several states that use user input as transitions. It supports jumping, ducking, standing and walking. When you are standing or walking, you can jump or duck, after which you return to the state you were in, thus standing or walking. If I were to use an HSM to prevent the duplication of code, I could not return to the last state. But if I used a Pushdown Automata, I could put jumping or ducking on top of the stack and discard them after they are done, and that way I could return to the state I was in.

Correct me if I'm wrong, and suggest me better options for user input than these two, if there is. Also, please don't post options like duplicating the FSM as the amount of states could vary and my question is related exactly to how to prevent that duplication.

Thanks,

me.

# Answer
> 3 votes
Pushdown automata and hierarchical state machines, at least in the context of game design, are both extensions of finite state machines. Neither contradicts the other, and so you can freely use both.

In hierarchical state machines, the substate/superstate relationship is one such that the substate is just a modified or extended version of the superstate. Lets say you have a superstate that is called `RunningState` that indicates your player is running. You can jump while running left if the A button is pressed, so one of your transitions is something like `if (A_BUTTON_PRESSED) next_state = jump_state;` However, you also want there to be an injured running state, for when the player has \<50% health, that behaves like `RunningState` in every way except that a) you run slightly slower, and b) you cannot jump. So you create `InjuredRunningState : public RunningState` that has `if (A_BUTTON_PRESSED) {next_state = NULL;} else { RunningState::transition(); }` in its transition method.

You see that `InjuredRunningState` will behave in every way like `RunningState` except when the A button is pressed it will do nothing. This example I think encapsulates why you would use a hierarchical state machine. The downside to using a hierarchical state machine is that inheritance can make your code complex and difficult to read / manage relatively quickly. Change `RunningState` and your implicitly change every state that inherits from it, which may have entirely intended consequences or may not, if those substates were designed with some assumptions about how `RunningState` behaves.

Pushdown automata, on the other hand, are good because they maintain state history. In other words, a state, instead of being told to transition specifically into state X or state Y given conditions A or B, can be told to do something like "transition into the previous state" given some condition, where the previous state can be any state that transitions into this one. Say you want to be able to jump from standing and from crouching, and the jump animation and physics etc. are identical, but when you land you want to return to whatever state you were in before, be it standing or crouchihg. You could use a pushdown automata for this. Instead of transitioning to a `JumpState`, you `push()` a `JumpState`. When the `JumpState` is done, instead of transitioning into some explicitly named state, it simply `pop()`s, and the state underneath it, the state that pushed the `JumpState`, is returned to, be this `StandingState` or `CrouchingState`.

The downside of this is that you have to maintain a stack of states, and make sure that you `pop()` what you `push()`.

Hopefully it is clear that you can have both at this point. You could have a `StandingState` and `CrouchingState` that transition into `JumpingState`, and then create `InjuredStandingState` or `InjuredCrouchingState` that inherit from their respective states (Hierarchical State Machine), while making sure any state that transitions into `JumpingState` does so by pushing it onto a state, and popping it when the jump is done (Pushdown Automata).

A final note: all the functionality described here could be achieved with regular finite state machines. For example, `InjuredStandingState` could just be its own completely independent state that repeats all the code of `StandingState` that it needs without inheriting from it. Similarly, instead of `JumpingState` you could have `JumpingFromStandingState` and `JumpingFromCrouchState` that, when done, transition back into the appropriate previous state. The problem here is repeat code and a rapidly expanding number of states, depending on the kind of behavior you want. It is up to you to decide if these extensions are even necessary. A regular finite state machine may be entirely sufficient for a very simple set of states and transitions.

# Answer
> 0 votes
You're right, finite state machines do not maintain history, and many extensions are often added to them in order to overcome their limitations (including pushdown automata).

More info on state machines (with a section on pushdown automata).

---
Tags: input, state
---


# Question
Title: "SetSelectedGameobject" only highlights button on second try (Unity 2017.3)
To support the use of a gamepad in the options menu I set `SetSelectedGameObject` and `firstSelectedGameObject` (which doesn't seem to do anything) to the button in the upper left, so it's highlighted. This works fine in my pause and option menus (panels that are enabled/disabled) but there's also a third panel that displays the controls as an image. On this screen the first button is set as selected but it doesn't get highlighted until I go back to the pause menu and then open the "controls" screen again.

The Hierarchy:

The ControlsPanel looks like this: click

All 4 buttons are set to "automatic" and they're all accessible to the gamepad but, like I said, the first one ("Keyboard") doesn't light up the very first time I access the panel. It should be like this:

* Click on "Controls" in the pause menu
* ControlsPanel is enabled
* "Keyboard" button is highlighted
* Pressing right on the gamepad highlights the next button ("Controller")

What actually happens:

* Click on "Controls" in the pause menu
* ControlsPanel is enabled
* "Keyboard" button is still grey
* Pressing right on the gamepad highlights the next button ("Controller")
* Press the "Back" button ("ControlsPanel" is disabled and "PausePanel" enabled)
* Click on "Controls" again
* This time the "Keyboard" button is highlighted

The "ControlsPanel" script:

```
public Image pic;
public GameObject controllerChoicePanel;
public GameObject firstControls;
private String controls;
private bool windows;

void Start() {
    controls = GetControls();
    windows = GetOS();
    pic.sprite = Resources.Load<Sprite>(controls);

    if(windows) {
        controllerChoicePanel.SetActive(true);
        EventSystem es = EventSystem.current;
        es.firstSelectedGameObject = firstControls;
        es.SetSelectedGameObject(firstControls);
    }
}

```

Any idea why it would work fine in my pause/options menu but not in the "Controls" one, even though I'm doing the same thing?

# Answer
`es.currentSelectedGameObject.name` output "Keyboard", so the button was indeed set properly, it just didn't highlight it (no idea why). Resetting the selected GameObject before setting it again helped:

```
if(windows) {
    controllerChoicePanel.SetActive(true);
    EventSystem es = EventSystem.current;
    es.SetSelectedGameObject(null); //Resetting the currently selected GO
    es.firstSelectedGameObject = firstControls;
    es.SetSelectedGameObject(firstControls);
}

```

Important: Only do this at the very beginning if you're using a gamepad, if you reset it every time, you won't be able to navigate to the next button! If you want to support both gamepad and mouse navigation, you have to do this every time though, otherwise clicking on the button will keep it highlighted until you click on another one (if the buttons' navigation is set to "Automatic"). So in the end you'll have to check where the input is coming from (gamepad or mouse).
> 1 votes

---
Tags: unity, c#, gui, gameobject
---


# Question
Title: Are there any disadvantages of using Distance Squared checks rather than Distance?
I use distance squared checks for basically all my distance (vector3 length) checking, due to the performance increase from not incurring a square root (like in plain length checks).

From the looks of it, squared distance checks work fine in every situation:

`if x^2 < y^2, then x < y, even when 0 < (x or y) < 1`

I am not considering situations where x or y is less than 0, as distance and distance-squared is always going to be positive.

Since this works, it looks like distance checks are never ever needed, but I have a nagging feeling that i'm missing something. Will this still hold up in accuracy-critical situations?

# Answer
> 44 votes
There's no disadvantage I'm aware of when using squared length to compare distances. Think about it like that: You're just skipping the `sqrt` which doesn't give you any additional accuracy. If you don't need the actual Euclidean distance, then you can safely leave the `sqrt` out.

Of course the squared length scales quite differently than the Euclidean distance and is therefore a bad candidate for things like pathfinding heuristics.

# Answer
> 14 votes
As bummzack hinted with the Path-finding analogy, you NEED to use the "normal" length every time you add distances together and want to compare their sum. (Just because summs of squares of lengths are different from squared summs of lengths).

x^2 + y^2 != (x+y)^2

# Answer
> 4 votes
The only disadvantage I can think of is when dealing with large numbers which will overflow when squared.

For example, in Java:

```
int x = Integer.MAX_VALUE / 1000000; //2147
int y = Integer.MAX_VALUE / 5000; //429496
System.out.println("x < y: " + (x < y)); //true
System.out.println("x*x: " + (x * x)); //4609609
System.out.println("y*y: " + (y * y)); //-216779712 - overflows!
System.out.println("x*x < y*y: " + (x * x < y * y)); //false - incorrect result due to overflow!

```

Also worth noting that is what happens when you use Math.pow() with the exact same numbers and cast back to int from the double returned from `Math.pow()`:

```
System.out.println("x^2: " + (int) (Math.pow(x, 2))); //4609609
System.out.println("y^2: " + (int) (Math.pow(y, 2))); //2147483647 - double to int conversion clamps to Integer.MAX_VALUE
System.out.println("x^2 < y^2: " + ((int) (Math.pow(x, 2)) < (int) (Math.pow(y, 2)))); //true - but for the wrong reason!

```

Is it working? *No*, it only gave the correct answer because `y*y` is clamped to `Integer.MAX_VALUE`, and `x*x` is less than `Integer.MAX_VALUE`. If `x*x` was also clamped to `Integer.MAX_VALUE` then you would get an incorrect answer.

Similar principles also apply with floats & doubles (except they obviously have a greater range before they overflow) and any other language which silently allows overflows.

# Answer
> 3 votes
One time I was working in square distances, and made the mistake of *accumulating* squared distances, for an odometer count.

Of course, you can't do this, because mathematically,

```
(a^2+b^2+c^2+d^2)!=(a+b+c+d)^2

```

So, I ended up with an incorrect result there. Oops!

# Answer
> 3 votes
You may run into trouble if you're writing an algorithm which requires that you compute an optimized position. For example, let's say you had a set of objects, and you were trying to compute the position with the smallest total distance from all of the objects. Just for a concrete example, say we're trying to power three buildings, and we want to figure out where the power plant should go so that we can connect it to all the buildings using the smallest total length of wire. Using the distance squared metric, you would end up with the x-coordinate of the power plant being the average of the x-coordinates of all the buildings (and analogously for the y-coordinate). Using the ordinary distance metric, the solution would be different, and often very far off from the distance squared solution.

# Answer
> 1 votes
Using distance squared is almost always just fine and good for performance. The following considerations are important:

If you want to think about the sum of a number of distances, distance squared will be inaccurate. For instance, I have two distances and I want to make sure their sum is less than 10. The following code is incorrect:

```
a = get_distance_squared(c,d);
b = get_distance_squared(e,f);
assert(a+b < 10^2);

```

It fails to assert in the following invalid case: `a=36` and `b=49`. In this case, the first length is 6 and the second 7; their sum is greater than 10, but the sum of the squares is not 100 or greater.

Another consideration: for real-valued distances, distance squared will always be positive. If you're measuring displacement for instance, you may need to deal with negative values, and squaring them will not do.

---
Tags: mathematics, spaces
---


# Question
Title: unity job system for 2d or more dimmension arrays?
I need to send a 2d array to a job system but execute function of `IJobParallelFor` just accepts one dimension. This is the example:

```
public  struct CalculateJob : IJobParallelFor
    {
        public NativeArray<Vector3> vertices;

       public int rows;
       public int x, y;

        public void Execute(int i)
        {

        }
    }

```

# Answer
Just flatten the 2d array into a 1d array by concatenating the rows. So a 2d array like this:

```
11111
22222
33333

```

becomes a 1d array like this:

```
111112222233333

```

Like this for example:

```
int i = 0;
for (int y = 0; y < height; y++) {
     for (int x = 0; x < width; x++) {
         nativeArray[i] = 2dArray[x,y];
         i++;
     }
}

```

To find the index in the 1d array which corresponds to a specific x:y coordinate pair, use the formula `i = x + y * width`. So to convert it back:

```
for (int y = 0; y < height; y++) {
     for (int x = 0; x < width; x++) {
         2dArray[x,y] = nativeArray[x + y * width];
     }
}

```
> 4 votes

---
Tags: unity, unityscript
---


# Question
Title: Do we really need quaternions? In UE4 I rotate without them
I want to experience gimbal lock to be able to understand how it happens. In lots of videos it shows that when you rotate along one axis, other axis is also being rotated and you obtain gimbal lock. For example, as you can see in this video, https://www.youtube.com/watch?v=zc8b2Jo7mno the axis are hierarchical. But I don't see the same in UE4. When you rotate in Editor it always rotates around world coordinate system and you cannot obtain a lock. If I can rotate around world (fixed) coordinate system, why shouldn't we always use that and instead use quaternions? Or I miss something? See all the videos that explain gimbal lock. They always rotate around one axis, while rotating other axis with it too. Why? And at this point, as I cannot obtain the lock, I think quaternions are useless if you rotate around world coordinate system and have 0 problem.

# Answer
> 5 votes
Rotating around euler-angles in world-space makes sense as long as you have a concept of a fixed horizon and a fixed "up" and "down" direction (like in a first person shooter).

But in some other contexts, like a first person flight simulator (atmospheric or space), this way of handling rotations falls apart.

Imagine a plane in level flight. What do you do when the player moves their stick to the left? You would rotate the plane around the z-axis. Pitch and roll stay the same and the yaw changes. So far, so good.

But now imagine what happens if the plane isn't level but actually in a steep ascending flight. When the player moves the stick to the left, you would not just expect the heading to change, you would expect the ascending angle to get lower and the plane to bank to the side. But that's not what will happen if you rotate around the world z-axis. Only the direction will change, pitch and roll will stay the same.

This behavior might be OK in a very arcade-like and simplified aeroplane simulation. But when you do the same in a space simulation where the horizon is usually merely implied by your level arrangement (if at all) and the player stops being aware of it when they get into a dogfight, it becomes quite annoying.

But if you use quaternions for handling rotation, you won't have that problem, because quaternions allow you to handle rotations in a way which is completely agnostic to the directions in which your axis' point.

# Answer
> 2 votes
I think you have one key misunderstanding in your question which is causing all this confusion.

You've asked "why shouldn't I just rotate objects using Unreal Engine 4's world rotations instead of using quaternions?"

But those aren't actually different choices; UE4 performs its world rotations by using quaternions; you can't pick just one or the other -- they're both the same thing! And that's why you have been unable to see gimbal lock in UE4's editor.

Gimbal lock is only a problem when an object's orientation is represented internally using euler angles, which no modern game engine does. (And no major game engine has done for probably approaching two decades, now)

So.. this isn't really something you typically need to worry about, these days, unless you're writing your own engine from scratch!

# Answer
> 2 votes
I'm quite late here but maybe this helps someone...

You can't get the gimbal lock this way. How it works is that the editor keeps current object orientation (as a quaternion) and when you drag-rotate your object it creates a new, relative rotation around selected axis (also as quaternion). Then it concatenates both rotations to compute the result. This way the math works just fine so you won't see any problems.

To get the issue you're after you need an app, that allows you to set the rotation using 3 Euler angles, then computes 3 separate rotations - around each axis, and concatenates them, to get the result. That's probably every app with some kind of "Object Inspector" where you set 3 floats as an X, Y and Z rotation, like 3D MAX, Unity or UE4.

I've tested it with Unity but you can do the same in UE4:

* Create a 3D object and select it
* Click and slightly drag every rotation value in object inspector - you should notice that dragging X value rotates object around X axis and so on...
* Now type 90deg into X, Y and Z.
* Click and slightly drag every rotation value again - this time you should notice that despite having 3 controls for rotation you can rotate the object only around 2 axes. In other words - two of your X,Y,Z controls rotate around the same axis - you've got the gimbal lock!

It doesn't seem so bad, right? But imagine you're the operator of some robotic arm, that can freely rotate around each axis and you have 3 levers to steer rotation - one lever for each axis. There're some orientations in which you just can't rotate around some axis.

This applies also in virtual 3D - if you 'steer' you orientation using Euler angles then there are situations where you just can't do what you want and it results in erroneous movements.

We can also look at this from another way:

You have some initial orientation, given with 3 Euler angles and you want to rotate to your final orientation. The final one is very similar to initial, but slightly rotated around the axis that you don't control because of the gimbal lock. Despite the fact that both orientations are visually similar, their Euler values may differ a lot, so if you're interpolating them, from initial to final then you object can rotate semi randomly at some point.

# Answer
> 0 votes
You can avoid gimbal lock by using matrices to store the rotation and iteratively ad rotations to it. Once in a while you'll need to re-orthonormalize the matrix to avoid developing odd skews.

However you can't easily interpolate between 2 matrix orientations. If you do, you need to re-orthonormalize it each time, while you can very easily interpolate between quaternions.

Quaternions are handy because they easily support a near-perfect super-set of the operations you typically want to perform on orientations (concatenating, interpolating, inversion). The only one of the top of my head that they don't is the lookat.

---
Tags: unreal, gimbal-lock, unreal-4
---


# Question
Title: To use Apple's game servers, do I need to enroll in the Apple Developer program?
I am developing a multiplayer iPhone game. To use the Apple game servers, do I need to register for the Apple Developer program?

# Answer
Yes. "Game Center" services are on the list of services included with an Apple Developer Program membership, as is App Store Connect, which is needed to manage various back-end aspects of some Game Center features, such as leaderboards and matchmaking.

Note that the "servers" Apple provides are only for these services. No part of Game Center involves Apple hosting your actual game server process. They just supply "meta" services like leaderboards, achievements, matchmaking, and so on.
> 1 votes

---
Tags: game-center
---


title: DirectX function calls' duration

text:
# Question
Title: DirectX function calls' duration
Today I downloaded Nvidia Nsight in order to profe my game GPU side and I came across some doubts:

* I can't find only any resource of what are the average times for the different DirectX functions (such as map/unmap, clear the target view, draw (even if is strongly dependant on shader and similar my are really basic), ...) and so I can't know if my values are normal or not. For example for the map function (with write\_discard) I've got an average of 0.8-1 microseconds.
* There are always peaks in each function: map() for example goes up to 200 microseconds (randomly and rarely).

Here's a screenshot:

Is it normal?

# Answer
> 1 votes
You're unlikely to find comprehensive resources on what the "average time" for D3D calls is. Any given D3D call is generally going to involve three things that seriously impact performance:

* the front-end part of the function, implemented in the D3D library
* the back-end part of the function, implemented by the driver
* the algorithm used by the function, impacted by the data you give it

Only that first aspect is likely to be fixed broadly enough to collect "average" timings, but the impact of the other two aspects would likely overwhelm the first anyway. So "average" timings aren't very useful.

If your game is running acceptably, you shouldn't worry about those profiling numbers. They're "fine." If your game isn't, it may be worth investigating more deeply why you get those spikes or whatever. But there isn't enough information present in your question to provide much further guidance.

# Answer
> 0 votes
It is also the matter how you call Map(), for example a MAP\_WRITE\_DISCARD can take more time than using MAP\_NO\_OVERWRITE because of their contracts. DISCARD will give you a new allocation, NO\_OVERWRITE is saying that your allocation is safe to be written to, just get the pointer to it. Not only these can affect your performance, but how big and much data you actually copy into these mapped buffers. Your best bet is to profile them with a real CPU profiler or inserting some timers of your own.

---
Tags: c++, directx, directx11, nvidia, profiling
---


# Question
Title: How can I fix texture clipping in Unreal 4?
I made a small project testing out mini-maps, it worked fine, I left it alone for a few months and reopened the project, and now I'm getting this:

I'm not even sure what to call this kind of issue other than clipping.

Also note, a sprite representing the player model is supposed to be at the center of the mini-map, but now it doesn't show. I hadn't made any changes to the project since I last worked on it, and when I check the camera I'm using for the mini-map, the pointer is definitely visible in the Blueprint. The project was made in 4.13.

Though as I took that screenshot, everything else that should be visible disappeared, so the mini-map no longer is showing the floors and walls. This feels like a graphics problem. Anyone know where I can start fixing this?

**SOLVED: It was a rendering/shader problem. Project settings \> platform \> mac \> rendering \> Max Metal Shader Standard to Target = "Metal v1.1"**

# Answer
**SOLUTION:** It was a rendering/shader problem. Project settings \> platform \> mac \> rendering \> Max Metal Shader Standard to Target = "Metal v1.1"
> 1 votes

---
Tags: unreal-4, unreal
---


title: Initializate float4x4 in vertex shader

text:
# Question
Title: Initializate float4x4 in vertex shader
Forgive me for my English. I am trying to create a 4x4 matrix in vertex shader, but it is not initialized correctly. Why is this happening? Vertex shader:

```
struct LogicBufferPosition
{
    matrix Pos;
};

struct LogicBufferBool
{
    bool flag;
};

StructuredBuffer<LogicBufferPosition> arrayPositions: register(t0);
StructuredBuffer<LogicBufferBool> arrayBools: register(t1);

cbuffer ConstantBufferVS: register(b0)
{
    matrix World;
    matrix View;
    matrix Perspective;
};

struct VS_INPUT
{
    float3 Pos: POSITION;
    float3 TexCoord: TEXCOORD;
    float3 Normal: NORMAL;
};

struct GS_INPUT
{
    float4 Pos: SV_POSITION;
    float3 TexCoord: TEXCOORD0;
    float3 Normal: TEXCOORD1;
    bool visible: VISIBLE_FLAG; // отрисовывать ли примитив?
};

GS_INPUT main(VS_INPUT input, uint id: SV_InstanceID)
{
    GS_INPUT _out = (GS_INPUT)0;
    if(arrayBools[id].flag == false)
    {
        _out.visible = arrayBools[id].flag;
        return _out;
    }

    float4x4 translateCenter =
    {
    1.f,0.f,0.f,-input.Pos.x,
    0.f,1.f,0.f,-input.Pos.y,
    0.f,0.f,1.f,-input.Pos.z,
    0.f,0.f,0.f,1.f,
    };

    float4x4 translateCenterInverse =
    {
    1,0,0,input.Pos.x,
    0,1,0,input.Pos.x,
    0,0,1,input.Pos.x,
    0,0,0,1
    };

    _out.Pos = mul(float4(input.Pos, 1), World);
    _out.Pos = mul(_out.Pos, translateCenter);
    _out.Pos = mul(_out.Pos, arrayPositions[id].Pos);
    _out.Pos = mul(_out.Pos, translateCenterInverse);

    _out.Pos = mul(_out.Pos, View);
    _out.Pos = mul(_out.Pos, Perspective);
    _out.TexCoord = input.TexCoord;
    _out.Normal = input.Normal;
    _out.visible = arrayBools[id].flag;
    return _out;
}

```

# Answer
> 0 votes
The issue is resolved. I thought that the matrix by columns is filled as I showed above. And it should be in the usual way:

```
float4x4 translateCenter =
{
1.f,0.f,0.f,0.f,
0.f,1.f,0.f,0.f,
0.f,0.f,1.f,0.f,
-center.x,-center.y,-center.z,1.f
};

float4x4 translateCenterInverse =
{
1.f,0.f,0.f,0.f,
0.f,1.f,0.f,0.f,
0.f,0.f,1.f,0.f,
center.x,center.y,center.z,1.f
};

```

---
Tags: c++, directx, directx11
---


title: 2D Blizzard/Snowstorm Effect

text:
# Question
Title: 2D Blizzard/Snowstorm Effect
How can I implement a blizzard/snowstorm effect in a 2D platformer? I have a particle system for snow particles, but I need some kind of windblown texture similar to this as well: How do I create this windblown snow effect?

Could I generate a windblown texture using perlin noise in Photoshop or something and sample it similar to the answer in this question about fog? How to create a 2D fog shader?

In that case it would have to be more dense than the fog texture, so holes don't appear that you can peak through when sampling the texture.

BTW I have a wind speed variable for my snow particles, could that be used for the windblown texture as well somehow?

# Answer
> 1 votes
I figured it out. You can create a blizzard/snowstorm effect using different windblown particles like here: https://www.unrealengine.com/marketplace/supergenius-weather-fx, this is used for pretty much all 3D games, but it requires a fancy particle system. The following is a simpler, cheaper method for 2D: https://assetstore.unity.com/packages/vfx/shaders/fullscreen-camera-effects/simple-2d-fog-storm-smoke-115617

example video

You can use this system both for a blizzard, fog, sandstorm, etc. effect by tuning the different shader parameters. The only asset you're interested in from this package is the shader "D2FogsNoiseTex.shader" it's in GLSL, but can be translated to any other shader language and used in any engine or framework. It takes a noise texture and applies the Perlin Noise algorithm to it using the shader parameters and scrolls it at a certain velocity.

To make it look like a blizzard the most important things are tinting it white and setting horizontal and vertical speed quite high. Make it be affected by wind direction and speed: Set horizontal and vertical speed to your normalized wind direction multiplied by wind speed. Size should be small and the density should be high.

Finally, add your own snow particles and make them be affected by the wind direction and speed as well. This will give a pretty convincing blizzard effect IMO.

Optional: Generate a texture with Perlin Noise

If you're unsatisfied with the look of the final texture being rendered on screen, you could use an external script with Python for example and generate a more specialized blizzard noise texture and edit the shader, so it doesn't apply the Perlin Algorithm, or simply edit the shader to give a different output from the noise texture.

Result (without snow particles):

Video

# Answer
> 4 votes
# Making Snow by particle system

as you mentioned in your question you need some noisy windblown. particle system have part that called noise that you can moving your particles based on noise.

# 2D Snow

you can easily make 2D snow effect by offsetting snowTexture by time.

```
Shader "Hidden/SimpleSnow"
{
    Properties
    {
        _SnowTexture ("SnowTexture", 2D) = "white" {}
        _OffsetDirection("OffsetDirection",Vector) = (1,2,0,0)
        _NoiseMask("NoiseMask",2D) = "white"{}
        _Speed("Speed",Float) = 2
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            sampler2D _SnowTexture,_NoiseMask;
            float4 _OffsetDirection;
            float _Speed;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float2 uvnoise : TEXCOORD1;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float2 uvnoise : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                v.uv += _OffsetDirection.xy * _Time.x * _Speed + sin(_Time.x);
                o.uv = v.uv;
                o.uvnoise = v.uvnoise;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_SnowTexture, i.uv);
                col *= tex2D(_NoiseMask,i.uvnoise);
                return col;
            }
            ENDCG
        }
    }
}

```

also to making hot bath effect you can make cloud noise and use it:

```
Shader "Hidden/HotBath"
{
    Properties
    {
        _CloudNoiseMask("CloudNoiseMask",2D) = "white"{}
        _OffsetDirection("OffsetDirection",Vector) = (1,0,0,0)
        _Alpha("Alpha",Range(0,1)) = 0.5
        _Speed("Speed",Float) = 2
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always
        Blend One One

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            sampler2D _CloudNoiseMask;
            float4 _OffsetDirection;
            float _Speed;
            float _Alpha;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                v.uv += _OffsetDirection.xy * _Time.x * _Speed;
                o.uv = v.uv;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_CloudNoiseMask, i.uv);
                col = smoothstep(0.05,0.9,col);
                return float4(col.rgb,col.r)*_Alpha;
            }
            ENDCG
        }
    }
}

```

another way is making snow effect by shader:

```
 //source: https://www.shadertoy.com/view/ldsGDn
    Shader "Snow"
    {
        Properties
        {
            LAYERS("Layers",Int) = 100
            DEPTH("Depth",Range(0.0,1.0)) = 0.2
            WIDTH("Width",Range(0.0,2.0)) = 0.9
            SPEED("Speed",Range(0.0,2.0)) = 0.9
        }
        Subshader
        {
            Pass
            {
                CGPROGRAM
                #pragma vertex vertex_shader
                #pragma fragment pixel_shader
                #pragma target 3.0

                int LAYERS ;
                float DEPTH,WIDTH,SPEED ;
                static const float3x3 p = float3x3(13.323122,23.5112,21.71123,21.1212,28.7312,11.9312,21.8112,14.7212,61.3934);

                struct custom_type
                {
                    float4 vertex : SV_POSITION;
                    float2 uv : TEXCOORD0;
                };

                custom_type vertex_shader (float4 vertex : POSITION, float2 uv : TEXCOORD0)
                {
                    custom_type vs;
                    vs.vertex = UnityObjectToClipPos (vertex);
                    vs.uv = uv;
                    return vs;
                }

                float4 pixel_shader (custom_type ps) : COLOR
                {
                    float2 uv = ps.uv.xy;
                    float3 acc = float3(0.0,0.0,0.0);
                    float dof = 5.*sin(_Time.g*.1);
                    for (int i=0;i<LAYERS;i++)
                    {
                        float f = float(i);
                        float2 q = uv*(1.+f*DEPTH);
                        q += float2(q.y*(WIDTH*fmod(f*7.238917,1.)-WIDTH*.5),SPEED*_Time.g/(1.+f*DEPTH*.03));
                        float3 n = float3(floor(q),31.189+f);
                        float3 m = floor(n)*.00001 + frac(n);
                        float3 mp = (31415.9+m)/frac(mul(m,p));
                        float3 r = frac(mp);
                        float2 s = abs(fmod(q,1.)-0.5+0.9*r.xy-0.45);
                        s += 0.01*abs(2.*frac(10.*q.yx)-1.0);
                        float d = .6*max(s.x-s.y,s.x+s.y)+max(s.x,s.y)-.01;
                        float edge = .005+.05*min(.5*abs(f-5.-dof),1.);
                        float t = smoothstep(edge,-edge,d)*(r.x/(1.+.02*f*DEPTH));
                        acc += float3(t,t,t);
                    }
                    return float4(float3(acc),1.0);
                }
                ENDCG
            }
        }
    }

```

# Generating Perlin noise by shader :

You can use noise to make a procedural shape:

Here's a Fractal Brownian Motion (FBM) tutorial.

```
Shader "Smkgames/FbmNoise"
{
Properties
{
_TileAndOffset("Tile and Offset",Vector) = (1,1,0,0)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100

Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};

struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};

float4 _TileAndOffset;
float _Step,_Min,_Ma;

v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv*_TileAndOffset.xy+_TileAndOffset.zw;
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}

// Author @patriciogv - 2015
// http://patriciogonzalezvivo.com

float random (in float2 st) {
return frac(sin(dot(st.xy,
                    float2(12.9898,78.233)))*
    43758.5453123);
}

// Based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in float2 st) {
float2 i = floor(st);
float2 f = frac(st);

// Four corners in 2D of a tile
float a = random(i);
float b = random(i + float2(1.0, 0.0));
float c = random(i + float2(0.0, 1.0));
float d = random(i + float2(1.0, 1.0));

float2 u = f * f * (3.0 - 2.0 * f);

return lerp(a, b, u.x) +
        (c - a)* u.y * (1.0 - u.x) +
        (d - b) * u.x * u.y;
}

#define OCTAVES 6
float fbm (in float2 st) {
// Initial values
float value = 0.0;
float amplitude = .5;
float frequency = 0.;
//
// Loop of octaves
for (int i = 0; i < OCTAVES; i++) {
    value += amplitude * noise(st);
    st *= 2.;
    amplitude *= .5;
}
return value;
}

        fixed4 frag (v2f i) : SV_Target
        {

float2 st =i.uv;

float3 color = float3(0,0,0);
color += fbm(st*3.0);
return float4(color,1.0);

        }
ENDCG
}
}
}

```

The FBM above shouldn't be used directly in to your shader because it has many GPU calculations and decreases performance. Instead of using directly, you can render the result to a texture with RenderTexture.

Shadertoy uses multiple passes, one per "buffer". As the name indicates, this pass stores the results in a buffer, which is just a texture. Unity will let you render to textures too.

also this tutorial will learn you how to generate perlin noise.

---
Tags: 2d, shaders, hlsl, graphic-effects
---