title: Render an mesh topmost

text:
# Question
Title: Render an mesh topmost
I can render anything 3d with SharpDX. However, my mind is mixed what should I do to render a mesh topmost. (Example: menu and all things behind). How can I render something front of the all other meshes even I do many transforms rotations etc.

# Answer
> 0 votes
First up I would make a render state helper class to make it easy to work with blend, depth, raster and sampler states.

```
Friend Class StateHelper
Friend Shared Function [New](ByVal device As Device, ByVal sourceBlend As BlendOption, ByVal destinationBlend As BlendOption) As BlendState
    Dim description As BlendStateDescription = BlendStateDescription.Default
    description.RenderTarget(0).IsBlendEnabled = True
    description.RenderTarget(0).SourceBlend = sourceBlend
    description.RenderTarget(0).DestinationBlend = destinationBlend
    description.RenderTarget(0).SourceAlphaBlend = sourceBlend
    description.RenderTarget(0).DestinationAlphaBlend = destinationBlend
    Return New BlendState(device, description)
End Function

Friend Shared Function [New](ByVal device As Device) As BlendState
    Dim description As BlendStateDescription = BlendStateDescription.Default
    description.RenderTarget(0).IsBlendEnabled = False
    description.RenderTarget(0).RenderTargetWriteMask = ColorWriteMaskFlags.Alpha
    Return New BlendState(device, description)
End Function

Friend Shared Function [New](ByVal device As Device, ByVal sourceBlend As BlendOption, ByVal destinationBlend As BlendOption, ByVal sourceBlend2 As BlendOption, ByVal destinationBlend2 As BlendOption) As BlendState
    Dim description As BlendStateDescription = BlendStateDescription.Default
    description.IndependentBlendEnable = True
    description.RenderTarget(0).IsBlendEnabled = True
    description.RenderTarget(0).SourceBlend = sourceBlend
    description.RenderTarget(0).DestinationBlend = destinationBlend
    description.RenderTarget(0).SourceAlphaBlend = sourceBlend
    description.RenderTarget(0).DestinationAlphaBlend = destinationBlend
    description.RenderTarget(1).IsBlendEnabled = True
    description.RenderTarget(1).SourceBlend = sourceBlend2
    description.RenderTarget(1).DestinationBlend = destinationBlend2
    description.RenderTarget(1).SourceAlphaBlend = sourceBlend2
    description.RenderTarget(1).DestinationAlphaBlend = destinationBlend2
    Return New BlendState(device, description)
End Function
Friend Shared Function [New](ByVal device As Device, ByVal mode As CullMode) As RasterizerState
    Dim description As RasterizerStateDescription = RasterizerStateDescription.Default
    description.CullMode = mode
    Dim state As RasterizerState = New RasterizerState(device, description)
    Return state
End Function
Public Shared Function [New](ByVal device As Device, ByVal description As RasterizerStateDescription) As RasterizerState
    Return New RasterizerState(device, description)
End Function
Public Shared Function [New](ByVal device As Device, ByVal description As DepthStencilStateDescription) As DepthStencilState
    Return New DepthStencilState(device, description)
End Function
Friend Shared Function [New](ByVal device As Device, ByVal depthEnable As Boolean, ByVal depthWriteEnable As Boolean) As DepthStencilState
    Dim description As DepthStencilStateDescription = DepthStencilStateDescription.Default
    description.IsDepthEnabled = depthEnable
    description.DepthWriteMask = If(depthWriteEnable, DepthWriteMask.All, DepthWriteMask.Zero)
    Dim state As New DepthStencilState(device, description)
    Return state
End Function
Friend Shared Function [New](ByVal device As Device, ByVal filterMode As Filter, ByVal uvwMode As TextureAddressMode) As SamplerState
    Dim description As SamplerStateDescription = SamplerStateDescription.Default
    description.Filter = filterMode
    description.AddressU = uvwMode
    description.AddressV = uvwMode
    description.AddressW = uvwMode
    description.BorderColor = Color.Black
    Return New SamplerState(device, description)
End Function
End Class
Public NotInheritable Class RenderStates
Public Sub New(ByVal device As Device)
    Me.Additive = StateHelper.[New](device, BlendOption.SourceAlpha, BlendOption.One)
    Me.AlphaBlend = StateHelper.[New](device, BlendOption.One, BlendOption.InverseSourceAlpha)
    Me.NonPremultiplied = StateHelper.[New](device, BlendOption.SourceAlpha, BlendOption.InverseSourceAlpha)
    Me.Opaque = StateHelper.[New](device, BlendOption.One, BlendOption.Zero)
    Me.NoColorWrits = StateHelper.[New](device)

    Me.AdditiveParticle = StateHelper.[New](device, BlendOption.SourceAlpha, BlendOption.One, BlendOption.One, BlendOption.InverseSourceAlpha)
    Me.AlphaBlendParticle = StateHelper.[New](device, BlendOption.One, BlendOption.InverseSourceAlpha, BlendOption.SourceAlpha, BlendOption.One)
    Me.NonPremultipliedParticle = StateHelper.[New](device, BlendOption.SourceAlpha, BlendOption.InverseSourceAlpha, BlendOption.SourceAlpha, BlendOption.One)

    Me.CullFront = StateHelper.[New](device, CullMode.Front)
    Me.CullBack = StateHelper.[New](device, CullMode.Back)
    Me.CullNone = StateHelper.[New](device, CullMode.None)
    Dim description As RasterizerStateDescription = Me.CullBack.Description
    description.FillMode = FillMode.Wireframe
    Me.WireFrame = StateHelper.[New](device, description)
    description.CullMode = CullMode.None
    Me.WireFrameCullNone = StateHelper.[New](device, description)

    Me.Default = StateHelper.[New](device, True, True)
    Me.DepthRead = StateHelper.[New](device, True, False)
    Me.None = StateHelper.[New](device, False, False)

    Me.PointWrap = StateHelper.[New](device, Filter.MinMagMipPoint, TextureAddressMode.Wrap)
    Me.PointClamp = StateHelper.[New](device, Filter.MinMagMipPoint, TextureAddressMode.Clamp)
    Me.PointBorder = StateHelper.[New](device, Filter.MinMagMipPoint, TextureAddressMode.Border)
    Me.PointMirror = StateHelper.[New](device, Filter.MinMagMipPoint, TextureAddressMode.Mirror)
    Me.LinearWrap = StateHelper.[New](device, Filter.MinMagMipLinear, TextureAddressMode.Wrap)
    Me.LinearClamp = StateHelper.[New](device, Filter.MinMagMipLinear, TextureAddressMode.Clamp)
    Me.LinearBorder = StateHelper.[New](device, Filter.MinMagMipLinear, TextureAddressMode.Border)
    Me.LinearMirror = StateHelper.[New](device, Filter.MinMagMipLinear, TextureAddressMode.Mirror)
    Me.AnisotropicWrap = StateHelper.[New](device, Filter.Anisotropic, TextureAddressMode.Wrap)
    Me.AnisotropicClamp = StateHelper.[New](device, Filter.Anisotropic, TextureAddressMode.Clamp)
    Me.AnisotropicMirror = StateHelper.[New](device, Filter.Anisotropic, TextureAddressMode.Mirror)
    Me.BorderLin = StateHelper.[New](device, Filter.MinMagMipLinear, TextureAddressMode.Border)

End Sub
' Fields
Public ReadOnly Additive As BlendState
Public ReadOnly AlphaBlend As BlendState
Public ReadOnly NonPremultiplied As BlendState
Public ReadOnly Opaque As BlendState
Public ReadOnly NoColorWrits As BlendState

Public ReadOnly AdditiveParticle As BlendState
Public ReadOnly AlphaBlendParticle As BlendState
Public ReadOnly NonPremultipliedParticle As BlendState

' Fields
Public ReadOnly CullBack As RasterizerState
Public ReadOnly CullFront As RasterizerState
Public ReadOnly CullNone As RasterizerState
Public ReadOnly WireFrame As RasterizerState
Public ReadOnly WireFrameCullNone As RasterizerState
' Fields
Public ReadOnly [Default] As DepthStencilState
Public ReadOnly DepthRead As DepthStencilState
Public ReadOnly None As DepthStencilState
' Fields
Public ReadOnly AnisotropicClamp As SamplerState
Public ReadOnly AnisotropicMirror As SamplerState
Public ReadOnly AnisotropicWrap As SamplerState
Public ReadOnly LinearClamp As SamplerState
Public ReadOnly LinearBorder As SamplerState
Public ReadOnly LinearMirror As SamplerState
Public ReadOnly LinearWrap As SamplerState
Public ReadOnly PointClamp As SamplerState
Public ReadOnly PointBorder As SamplerState
Public ReadOnly PointMirror As SamplerState
Public ReadOnly PointWrap As SamplerState

Public ReadOnly BorderLin As SamplerState

End Class

```

Next when its time to draw you do it like this

```
 ImmediateContext.OutputMerger.SetTargets(_device.DepthStencilView, ColorBufferRT)
 ImmediateContext.ClearRenderTargetView(ColorBufferRT, New Color4(0, 0, 0, 0))
 ImmediateContext.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth, 1, 0)
 ImmediateContext.Rasterizer.SetViewport(Viewport)

   //Set render states
 ImmediateContext.OutputMerger.BlendState = device.RenderStates.Opaque // Change as needed
 ImmediateContext.Rasterizer.State = device.RenderStates.CullNone // Change as needed
 ImmediateContext.OutputMerger.SetDepthStencilState(device.RenderStates.Default) // Change as needed

//Draw 3D stuff here in back to front or front to back depending on your alpha requirements

// Set 2d Depthstate to none or clear the depthbuffer
ImmediateContext.OutputMerger.SetDepthStencilState(device.RenderStates.None)

ImmediateContext.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth, 1, 0)

 ImmediateContext.OutputMerger.BlendState = device.RenderStates.AlphaBlend// Change as needed
 ImmediateContext.Rasterizer.State = device.RenderStates.CullNone // Change as needed

 // Draw Top most stuff here Like Menu\Hud
 UI.Draw(ImmediateContext)

```

I use the SharpDX.Toolkit.Spritebatch to do all my 2d drawing as it handles batching and depthlayers for me and allows to get the draw calls for my UI down to 5(Alpha, Additive, Opaque, Font0, Font1) draw calls not matter the amount of UI I have because I also use a spritesheet.

Here is a call to spritebatch.draw where last value on each line is the layer I want it to be in.

```
 SpriteBatch.Begin(Toolkit.Graphics.SpriteSortMode.Deferred, GraphicsDevice.BlendStates.AlphaBlend, Nothing, Nothing, Nothing, Nothing, ViewMatrix)
SpriteBatch.Draw(UISpritesheet, destrect, sourcerect, UINode.Settings.Color, 0, Nothing, Nothing, 0.5)
SpriteBatch.Draw(UISpritesheet, destrect, sourcerect, UINode.Settings.Color, 0, Nothing, Nothing, 0.0)
SpriteBatch.Draw(UISpritesheet, destrect, sourcerect, UINode.Settings.Color, 0, Nothing, Nothing, 1)
SpriteBatch.End

```

You can find an up to date ToolKit on my GitHub page, you will also need the custom build of sharpDX to use it, you will find that on my GitHub too.

# Answer
> -1 votes
That can be something like:

```
RenderLoop.Run(form, () =>
            {

//...
                context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                context.ClearRenderTargetView(renderView, Color.Black);
//render any mesh

//...

//render on secondary layer:
                            context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                menu1.VerticesBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.VertexBuffer, menu1.Vertices);
                menu1.Render(); context.Draw(menu1.VerticesCount, 0);
                // Present!
                swapChain.Present(0, PresentFlags.None);
});

```

# Answer
> -1 votes
Imho one should **always** render in front to back order, unless there are transparent objects in front. And **not** clear the depth buffer too lightfootedly.

Render the close things (those that occupy a relevant part of the screen space) first and do a depth write accordingly (either by default or by tweaking with a shader). If rendering a closeby object last, there will be **redundant rendering** that will in any case be covered by the big thing in front.

If for example rendering a menu texture (a screen quad of two triangles) that covers a lot of the screen, do it **first** of all, using a shader where you have in the pixel shader part something like:

```
struct PS_OUTPUT {
    float4 Color      : COLOR0;
    float Depth       : DEPTH0;
    };

```

and

```
PS_OUTPUT PS_Main(VS_OUTPUT input) {
    PS_OUTPUT output;
    [calculate res]
    output.Color = res;
    output.Depth = 0;
    return output;
    }

```

and

```
technique FullscreenTech
    {
    pass FullscreenPass0
        {
        blabla
        ZWriteEnable = True;
        }
    }

```

---
Tags: c#, rendering, sharpdx
---


# Question
Title: How would I create colouring such as in Splatoon?
For those who don't know, Splatoon is a game where you color ground with your teams, and other team tries to color more area in their color.

It looks like the whole ground is color-able, which makes every ground part (maybe not every pixel, but very big part of it) rendered every time a color is being sprayed. I would think is a big load on the GPU, but the Nintendo Wii U handles it pretty well.

My question is, how is it possible? Is there a trick behind that kind of process?

# Answer
I would imagine the easiest way to do this for large areas regardless of texture size / quality would be to send a colour / player index over the network, and treat it as a vertex colour at the destination. Let's say there are only 8 players / colours max, that's 2^3 thus 3 bits + the vertex position (vec3) in question would be used to send colour information - very low cost each network update. One could even optimise the position to be a rounded offset from the player position, reducing packet size even further. Obviously a key factor in this is what the vertex density is around each player (cost would increase as density increases).

Remember that if the world is based on a uniform grid, the vertex position could also be quite small - you wouldn't need floats @ 32 bits each - e.g. consisting of a 1024x1024 map would be 10+10=20 bits total for each vector position (`ivec2`).

It would be trivial to perform Run-Length Encoding on such a dataset in order to compress it even further. This would lead to a variable sized packet, but would definitely result in savings (as might any other compression; I mention RLE because it's conceptually simple).
> 3 votes

---
Tags: game-mechanics, graphic-effects
---


# Question
Title: Unity Array Index Is Out Of Range When Comparing Normal Variable With Array Variable
I created a script that used to check all number at `mesh.triangles` and save the value if we did not save it yet to array variable that i created manually in script , but before the script even go check , ***it's stuck at comparing normal variable with array variable*** , but why ? because we can't compare normal variable with array variable or what ? here is my script :

```
Mesh secondmesh = GetComponent<MeshFilter> ().mesh;
Vector3[] secondvertices = secondmesh.vertices;
int[] secondtriangle = secondmesh.triangles;
int saverone = one;
int savertwo = two;
int saverthree = three;
int[] saveint = new int[secondtriangle.Length];
Vector3[] savevector = secondvertices;

// check for number that available in triangle
for (int anythingtwo = 1; anythingtwo < ( secondvertices.Length + 1 ) ; anythingtwo++)
{
    saveint [0] = 0;
    int idontknowthistriangle = secondmesh.triangles [anythingtwo];
    bool isalreadyavailableinsaveint = false;

    // check if the same number already exist in the array
    for(int anythingthree = 0; anythingthree < ( saveint.Length + 1)
        && anythingthree < ( secondtriangle.Length + 1) ;anythingthree++)
    {
        // the error is at line below this comment and another line
        // that is in the bottom of the script
        if (idontknowthistriangle == saveint [anythingthree])
        {
            Debug.Log (" | anything three , already found ! |");
            isalreadyavailableinsaveint = true;
            break;
        }
    }

    // if the same number is found in the array
    if (isalreadyavailableinsaveint == true)
    {
        Debug.Log (" | already available in save int ! | ");
    }

    // if the array does not contain same number
    if (isalreadyavailableinsaveint == false)
    {
        // count how many times the search found that the array
        // don't contain the value we found
        totalcount++;
        Debug.Log (" | total count : " + totalcount + " | ");

        // error also here !
        saveint [anythingtwo] = idontknowthistriangle;
    }
}

```

This is the error immediately :

```
// the variable used at the error
int[] secondtriangle = secondmesh.triangles;
int[] saveint = new int[secondtriangle.Length];
int idontknowthistriangle = secondmesh.triangles [anythingtwo];
// the error is located at
if (isalreadyavailableinsaveint == true) {
// and
saveint [anythingtwo] = idontknowthistriangle;

```

The error is located using the comment at the script , but i don't get it why , can anyone tell me why is this happening ? because what i though `int` never be `null` and i can even debug log the variable ( output 0 ) no matter i set it or not .

# Answer
Reading through your code, it is fairly obvious that you have logic errors that would lead to null reference exceptions. Here are some excerpts, with appropriate formatting:

```
// We create an array of integers, with the same length as the secondTriangle array.
int[] saveInt = new int[secondTriangle.Length];

// We than create a for loop, which iterates using anythingThree.
// Explicitly note that this for loop exits when anythingThree is no longer less than both
// the lengths of saveInt and secondTriangle, + 1.
for(int anythingThree = 0; anythingThree < (saveInt.Length + 1)
    && anythingThree < (secondTriangle.Length + 1); anythingThree ++)
{
    // Lastly, we perform an if statement, checking the values in saveInt
    if (iDontKnowThisTriangle == saveInt [anythingThree])
    {
    }
}

```

In short, you are creating an array called `saveInt` with the same length as `secondTriangle`. You are then entering a for loop where you iterate between `0` and `saveInt.Length` or `secondTriangle.Length` 1. You use the current value to check the `saveInt[]` array, so naturally, as soon as you hit `saveInt.Length`, you are accessing an index that *does not exist* in the array.

***Why is that?***

Simply put, `saveInt.Length` or `secondTriangle.Length` will return the actual length of the arrays. However, in this format, we count the first index as 1 and count up. This is a kin to how we count, in the real world. However, the first index of an array is *not* 1. It is 0. So the value you derive as the `Length` value of an array will *always* point to the first index that is *not available*.

Perhaps you should be ensuring that your for loop uses the condition of `< saveInt.Length`. This ensures that you work within the bounds of your array, as well as removing the redundancy caused by including a check to the `secondTriangle` array, despite already ensuring that these arrays have the same length.

---

***Further consideration***

Only yesterday, you asked another question that was actually quite obvious given an understanding of how arrays work in C#. It is important to get the basics down before we move on to more advanced topics, such as those more commonly found in game development.

It is definitely worth doing some research on how arrays work in C#, as they can be quite tricky, if you are unfamiliar with their operation. You might want to consider reviewing the following documents:

---

1 Note that you explicitly ensure that these two arrays have the same length. Checking that the value is both `< (saveInt.Length + 1)` **and** `< (secondTriangle.Length + 1)` is also rather redundant. We know that if `x < saveInt.Length` then `x < secondTriangle.Length`, because they have the same lengths.
> 1 votes

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


title: Mipmapping on CPU

text:
# Question
Title: Mipmapping on CPU
I'm trying to load a big terrain texture and only want to load a certain mipmap level to the GPU with Vulkan. When the whole terrain is in sight, the camera is far enough away from it so that only a mipmap of the whole terrain texture would be enough for renderering. So for that I don't want to load the whole texture on the GPU just for mipmap generation. So is it possible to generate the mipmap on CPU first? If so, what techniques are being used for mipmapping or (maybe better) is there already a implementation (library) for generating a mipmap on CPU?

# Answer
> 0 votes
Its most likely better to pregenerate and store the lower precision mipmaps along side the original texture in your assets. Then only when you need the higher resolution image do you actually load it from disk.

---
Tags: opengl, textures, gpu, mipmaps, vulkan
---


title: 2D Procedural resource generation

text:
# Question
Title: 2D Procedural resource generation
I'm currently building a Mars colonization game and I'm wondering if anyone can point me to resources on how to procedurally create resources and biomes within a 2d game. Much like in a game like Factorio were different resources and such are spread around the map.

Thanks in advance!

# Answer
Many games use noise generation such as Perlin, Value or Gradient noise for their resource spawning. Perlin is the most common type, and is used in Factorio. There is plenty more info on Perlin Noise to be found on the web.
> 1 votes

---
Tags: procedural-generation
---


# Question
Title: How do I create a Shadow of the Colossus - like climbing system?
I'm developing a game in Unreal Engine 4, and I want to implement a climbing system just like in Shadow of the Colossus, where you can grab and climb onto specific parts of the monster (fur, in this case).

It probably doesn't use the same logic as a building a climbing system/edge grabbing, where it uses a sphere trace by channel to detect edges and then disable the player movement, as the player must be attached to the colossus since it moves.

How would I go about creating something like this?

# Answer
The search-term you are looking for is Inverse Kinematics. This is a technique you can use to modify character animations to take the positions of other objects in the game world into account. The basic application of this technique is to have characters walk properly on uneven ground or accurately reach for objects in the game world. Having a character climb another character which is animated independently from it is a very advanced use of IK, so you might want to familiarize yourself with the basic applications first.

Now how to do climbing with IK?

Define some vertices of your giant model as "grip vertices". These are points on the giant-model you want your player-model to be able to grip to.

Now when you have the player climb the giant, there will be moments in the climb animation where one of the limbs of the player needs to move from its old grip-vertex towards a new grip-vertex. Do that by picking the vertex closest to the preferred end position of that animation phase and use it as the new end effector for the limb.

---

By the way, if you are interested in the animations of Shadow of the Colossus specifically, then you might find the Extra Frames video about its IK system very interesting. It also starts with a general introduction of IK and then shows how they are used in SotC.
> 3 votes

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


# Question
Title: How do I publish a game for the web, using Cocos Creator?
I am new to Cocos Creator and web game programming. I have build a simple game for the web, but I don't know how can I publish it. In the documentation files, it says:

> You only need to .zip scripts and resources in the game project and resource library, and then drop them into the designated release path

But I don't understand it. How do I publish a game for the web, using Cocos Creator?

# Answer
If you want to put something on a website, you need to obviously either create your own site or find a publisher. Both have drawbacks, with a publisher you lose the rights over your IP and with a website you need to pay a certain amount of money every month.

You haven't read the whole site, the important parts are

> The construction of Web platform is very easy. You only need to .zip scripts and resources in the game project and resource library, and then drop them into the designated release path. If you need test, the test mode is there for you. The sourcemap is preserved with versions thus constructed.
>
> Click the construct button, then a progress bar will appear on the top of the panel. When the progress bar reaches 100%, the construction is finished.
>
> If you want to release or share your games on the Internet, click the open button next to release path. After opening the release path, copy everything in the constructed web-mobile or web-desktop folders, and drop them into your Web server. Then you can see the game later there.

So, you take your game code and resources, put it into a .zip file (use WinRar or 7zip), then put these in the release path (by default this is `build`. You can construct the game now. This'll result in some new folders, specifically `web-mobile` if you target a mobile platform and `web-desktop` if you target computers. These folders have everything you need.

If you have a publisher, then this is basically where you need to stop. You need to give the folder to the publisher and they will release it for you.

But if you have your own website, then you need to put the files up yourself. You either have an FTP address or an online file manager. If you want to make your website to only have a single page, then you need to put the contents of one of the folders up depending on whether you want a mobile game or a desktop game. If you want multiple pages with a main page and a way to get to other games, then you can simply upload the folders. These have an index.html file in them. In your main html file you need to create a link to this file.
> 1 votes

---
Tags: cocos2d
---


# Question
Title: Most efficient way to create/modify terrain in real time?
In my game players can modify terrain in real time, but I am not sure what is best practice for this scenario. I have redesigned and refactored the way the player does this a few times, and am feeling at a loss.

Initially I created small blocks of terrain as GameObjects, but this I quickly realised was grossly inefficient. Later I devised a system which procedurally generated the 3d mesh by creating vectors and tris for a much larger terrain chunk GameObject, but this is also unfit for purpose. As I would like the player to be able to place new terrain pieces (replacing old) from premade 3d art assets.

The question is how should one string these pieces together into one map, so that the player can enjoy a large map with a fine level of control? And for this not to break the game with inefficiency? Consider that the terrain system is composed of blocks of premade terrain segments, like river or cliff sections. I feel like I'm missing some basic knowledge of how and when to merge 3d meshes into GameObjects for this purpose?

# Answer
**Heightmap**

This is a 2D structure where every value represents either a vertex or a tile between vertices, in a grid structure. Heightmaps have been rendered in every from software scanline renderers (NovaLogic's voxel engine) to modern 3D environments. These were commonly used for rendering 3D in the '80s and '90s due to the low processing cost / simple structure - essentially a 2D array of integer or floating point values. Games like Magic Carpet used this to great effect.

**pros**: extremely cheap to process and send across network.

**cons**: Does not allow overhangs, e.g. caves, overhanging cliffs, etc.

**Voxels**

This is a 3D structure where every value represents one *vo*lumetric *el*ement in the world (Vo-x-El). As we go from 2 to 3 dimensions, cost increases geometrically (excuse pun).

**pros**: Much more flexible than the heightmaps from which they evolved, you can really create any space you like (subject to voxel grid resolution / density).

**cons**: Much more costly to process - optimisation will be a necessity. Also, your terrain will need to be built with different tools, being a voxelised mesh.

**Voxel template system**

Provided your objects to be placed are static, nothing stops you from querying a voxel space for the placement of say, a 2- or 4- or n-voxel at once. So let's say you have a nice Roman column, maybe it's 5 metres high and your voxel scale is 1m cubed. So you will need 5 voxels vertically to fit this piece in. Query the voxel space in the grid at the player's chosen placement location (on the ground in front of them) and the four above it - place if all 5 spaces are free.

**pros** Voxels provide a nice neat grid in which to work / place objects. They forego the need for physics since one can use the grid structure and assume they adhere to that (e.g. Minecraft). Collapsing straight down due to gravity is easy enough to accomplish.

**cons**: Can be costly to check spaces for multi-placement as described above. Your template meshes, e.g. the column, need to be built to fit the underlying voxel system.

**Also... Chunks**

Chunks are a means of breaking up a large map into smaller, square sections. You only load in certain chunks depending on where the player is currently standing in the world. Each chunk will typically be nxn voxels in depth and width, and m in height (all depends on your coding choices).
> 1 votes

# Answer
The best approach is probably to save the "Pre-made gameobjects" as vertex arrays (x,y,z coordinates) just like you probably would with the terrain mesh. These can be smaller than the array you use to generate the entire terrain. If you find the correct positions in the array you use to generate the terrain mesh by looping through, you can define the position of the "Pre-made gameobject" within the terrain array and adjust the vertex height positions. This should allow the player to click on a location on the mesh and spawn a pre-defined mountain etc...
> 1 votes

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


# Question
Title: Detecting on which side did the objects collided unity 2d
I have a ball and a rectangle in my game.

The rectangle has a box collider 2d attached to it. How can I calculate or check when the ball hits the top of my collider, when it hits the bottom, left and right, so basically any side of the collider and also a corner of the collider, I have searched over the internet and not one answer that I found helped me into solving my problem. If anyone can help I would appreciate it.

# Answer
> 2 votes
I know this is a bit old, just thought that someone else might find this useful. **The transforms of the GameObjects has its anchor point in the center.**

I did like this to check. In the circles OnCollisionEnter2D-method:

```
  void OnCollisionEnter2D(Collision2D coll) {
        if (coll.gameObject.tag == "Block_that_got_hit") {
            if ((this.transform.position.x - coll.collider.transform.position.x) < 0) {
                print("hit left");
            } else if ((this.transform.position.x - coll.collider.transform.position.x) > 0) {
                print("hit right");
            }
        }
    }

```

Things to account for is that this only divide the rectangle into two sections, left and right.

To get the size of collider called coll you could do: `coll.collider.bounds.size.x`

# Answer
> 1 votes
First, you find their position relative to each-other (a vector subtraction of their positions), normalize that, and then you have the direction from one game object to the other. From there, it's fairly trivial. Just if statements and checks of that direction.

An untested example:

```
void OnCollision2D(Collision2D col)
{
    Vector3 dir = (col.gameObject.transform.position - gameObject.transform.position).normalized;

    if (dir.y > 0)
    {
        // hit top
    }
    else if (dir.y < 0)
    {
        // hit bottom
    }
}

```

# Answer
> 0 votes
One solution:

Build your rectangle of 4 pieces, and which one registers the collision tells you which side it happened on. If two register, you know it was on a corner.

Another solution:

Use the relative positions of the two objects and their velocities to figure out where it happened. For example, if the ball is above the rectangle, and the xcoords are almost the same, you know the collision happened on top.

The velocity is a sanity check. If the ball's y coord is below the rect's y coord, but the velocity indicates the ball was moving down, you know it moved too far in one frame and should have bounced back up first.

# Answer
> 0 votes
I would rather use Raycast than OnCollision2D.

Here is the code.

*Circle : no rigidbody 2d and no collider attached. Just having this script.<br>Box : box collider 2d attached.*

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

public class CircleThing : MonoBehaviour
{
    float       _radius = 0.5f; //radius of the circle
    Vector3     _prevPos, _dirV;
    Transform   _transform;

    void Start() {
        _transform = transform;
        _prevPos = _transform.position;
    }

    void FixedUpdate() {
        if(_transform.position == _prevPos)
            return;

        _dirV = _transform.position - _prevPos;
        RaycastHit2D hit = Physics2D.Raycast(_transform.position, _dirV, _radius);
        if (hit.collider != null) {
            //Debug.Log ("Collided :" + hit.collider.name + " / " +  hit.normal);
            if(hit.normal.x != 0f)
            {
                if(hit.normal.x>0f)
                    Debug.Log ("Left Side");
                else
                    Debug.Log ("Right Side");
            }
            else if(hit.normal.y != 0f)
            {
                if(hit.normal.y>0f)
                    Debug.Log ("Top Side");
                else
                    Debug.Log ("Bottom Side");
            }
        }

        _prevPos = _transform.position;
    }
}

```

You can use reflection normal to identify collision side.

# Answer
> 0 votes
You can use contact point so first you check for collision and then you have an if statement to check which side it way eg. Vector3.up, here's an example:

```
public class NewBehaviourScript2 : MonoBehaviour {

   void OnCollisionEnter(Collision other){

       //This will print the first point of contact in Vector3
       print (other.contacts[0].point);

//if the contact of collision is equal to Vector3.up destroy the collided object
       if (other.contacts [0].point == Vector3.up) {

           Destroy(other.gameObject);
       }
   }
}

```

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


# Question
Title: How to calculate “real” distance between cursor and distant object?
I don't really know how to formulate the title, but the problem is the following:

I'm using a scripting language called "SQF" which has been created by a company named "Bohemia Interactive" (no, I do not work for them) and it's for modding their games. So I won't fill up these lines with code. If somebody else knows it and wants to see, comment and I'll add what I've tried so far.

The issue anyway is rather abstract, so I'm going to explain it with an archer and his target. Ratios may not be correct as they are only for explanation.

Say I (as the player) am the archer (first person), the target is **10m away**, has a **diameter of 2m** and **appears 200px** in diameter on the screen. Now I aim **50px** left of the target edge, execute my desired function and and get the info that this is **1m** away from the target (2m from its center).

Now, I move 90m back, so the target is **100m away** and **appears 100px** in diameter (don't know if that's correct, but you get the idea). Now I am aiming **25px** left of the target and again, execute my desired function and it should tell me again that the distance is **1m**.

Now, the "real" distance was 1m in both cases, but on my screen it was 50px at the first aim and 25px at the second.

So, what I am looking for is a (mathematical/programmatical) model to get the "real" distance between the target and where I aimed, no matter how far away I was from the target. I do have the positions of both archer and target in 3D coordinates. Though SQF is a very special language, it does provides a function to calculate the distance in meters and to dertermine certain geometrical values:

https://community.bistudio.com/wiki/Category:Command\_Group:\_Math

... so there's no need for that.

I know, this is very abstract, but I am hoping, somebody could give a hint or knows a mathematical procedure to do that.

If somebody knows how to do it in C, C++ or Java, I can write these languages, so that would be great!

# Answer
You cannot count with px, px are irrelevant because of different resolutions.
Cast a ray onto plane at your target location perpendicular to the direction(target loc - actor loc) vector. Then calculate the distance between ray(aiming direction) intersection with that plane and your target location on the plane.
*Note, this is one way of doing it. If you dont need exact results or have only one resolution or have the situation simplified in any other ways, there could be easier solution.*
**tl;dr** you will have to do math and read some tutorials on ray casting. Code and step-by-step explanation would not fit few paragraphs.

EDIT: another solution could be using trigonometric functions. Because you know hypotenuse is distance / cos(th). Where th is angle between direction to target and aiming direction and distance is...distance. Now you only calculate the length of opposite: sqrt(dist^2 - hypotenuse ^2), and that is your result.
> 1 votes

# Answer
The solution you spoke of in your comment on wondra's answer is unnecessarily complex, the engine has a fairly trivial solution to this problem:

```
// 3D Distance to object cursor is pointing at.
_distToCursorObject = player distance cursorObject;

// Same problem, using map distances.
_mapDistToCursorObject = player distance2D cursorObject;

hint format ["3D Distance: %1\nMap Distance: %2", _distToCursorObject, _mapDistToCursorObject];

```

Note that if the engine doesn't recognize an object (sky, water, non-object terrain features) you'll get a distance of 1e+10.
> 0 votes

---
Tags: 3d, geometry, screen
---


# Question
Title: ArmA 3 Scripting: Delete vehicle depending on present players
I'm fairly new to ArmA 3 scripting, and I'd like to know how to only spawn starting vehicles depending on how many players opt in to the mission. Say, the mission has four slots, but only two people fill them. There would be four vehicles, but two would be deleted on the mission start because those players weren't present. I've tried putting this code in the initialization of each vehicle;

```
sleep 1; if (isNull unit1) then {deleteVehicle this} else {};

```

But it only gives me errors when the mission starts.

# Answer
> 1 votes
You can get the number of human players at any time with:

```
_numHumans = count allPlayers;

```

A better solution may be to have players spawn into vehicles when they load into the game, as they may not be registered in `allPlayers` when `initServer.sqf` is ran.

In `initPlayerServer.sqf` (a script with this filename will run on the server every time a player connects):

```
params ["_player", "_didJIP"];

// Create a vehicle at the player's location and move them to the drivers seat.
_vehicleClass = "O_MRAP_02_GMG_F"; // Ifrit GMG's Type Classname
_veh = _vehicleClass createVehicle (getPos _player);
_player moveInDriver _veh;

```

This script will have the effect of the player spawning in the vehicle requested when they load into the game. You could easily have it spawn near them or at a specified location you can set either in the script or an editor marker.

# Answer
> 0 votes
I wouldn't create a static number of vehicles and then delete them if the max players isn't reached. This doesn't leave much room for join in progress players. Instead, you could create a spawn point for your players and then drop a crate or sign at the spawn location, use an addAction to add a menu item for players looking at the sign to spawn a new vehicle using the command createVehicle.

If you absolutely wanted the player to spawn in a vehicle then you could set the init.sqf script (which is launched when the player picks a side and loads the mission) to perform a createVehicle and moveInDriver to move him in to the new vehicle within a second.

Hopefully this helped you.

---
Tags: modding, arma3
---


# Question
Title: Best way for first person view to look at a note/item and add it to inventory?
Implementation question from a beginner. I would like to implement a functionality to a first person game where the player can pick up notes lying around and have the note align itself to the camera and get bigger for the player to read its contents. The game will have a Myst like feel to it.

I am currently debating whether I should use the UI or just animate the note object in the game world itself and have it "fly" towards the camera.

So far I've implemented a solution which uses a raycast and when the ray hits an item it sends a message to it. If the item can understand this message, then it looks at the camera (using `lookAt()`) and becomes a child of the camera, I then reposition it in front of the camera using the `localPosition`.

All this seems to work fine but my object is still part of the world, I would ideally want it to be unable to collide with objects when it is carried around by the player. My plan was then to have a couple of UI button pop-up each time an item is picked up for the player to either drop it or stash it in its inventory.

Any suggestions ?

Thank you

# Answer
> 3 votes
To expand a bit on the comments with some actual code, this is how you might add to what you already have. By disabling the Collider, you avoid unwanted collisions. By setting isKinematic to true, you avoid unnecessary physics calculations, as well as any conflicts between your scripted movement and the Rigidbody.

```
private Rigidbody body;
private Collider col;

private void Awake()
{
    // Assuming a simple, flat hierarchy
    body = GetComponent<Rigidbody>();
    col = GetComponent<Collider>();
}

private void MessageReceived()
{
    SetCollisionsActive(false);

    // Your camera related logic here
}

private void SetCollisionsActive(bool active)
{
    body.isKinematic = !active;
    col.enabled = active;
}

```

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


title: Animation inside GUI

text:
# Question
Title: Animation inside GUI
Good day. I would like to create a "rich" GUI for my game.

How can i add a 3d model to a GUI Button (with continous rotation ) ? If I can't add a 3d model to a GUI button, what is the best way to visualize a 3d model rotating ?

Maybe creating a video file or animated gif and adding it to my button ?

Thanks

# Answer
> 2 votes
I suppose you're talking about the new UI system (coming with `UnityEngine.UI`) and not the old GUI system.

If you want to display a 3D model in a `GUIButton`, you can simply use a `Render Texture`. In another part of the scene you display the animated 3D model you want to use and put a camera dedicated to watch it. The main difference between this new camera and the main camera is that the new one doesn't render on screen but in a `Render Texture`. Then you can easily use this `Render Texture` like a regular texture in your UI using `RawImage` component.

---
Tags: unity
---


# Question
Title: How to flip a box2d body when it can't move forward? LibGDX
I'm attempting to create a simple enemy for a platformer. It should move forward constantly until it hits something like a wall, and then it should flip and move forward the other direction. How might I accomplish this?

# Answer
There are a few ways you can achieve this.

Detecting point of collision on the `Body`, using a `ContactListener` you can listen to the contacts and react to them, by comparing the contact point from the `WorldManifold` to the world center of your `Body` you can determine if the collision happened on a side of the `Body` (rather than for example the bottom).

Another approach could be to add two `Fixture`s to the `Body`, one a little to the left and one a little to the right, then listen for contacts on them, this approach has the advantage of you not having to compare contact points as you know which side collided.
> 1 votes

---
Tags: libgdx, physics, box2d, movement
---


# Question
Title: Forcing Proportion Lock on Layout Element
I'm trying to develop a Card-Game in Unity3D using 2D mode.

Every **Card GameObject** on my Scene contains a `Layout Element` Component with following parameters:

The parent container, a `Panel` has a `Horizontal Layout Group` Component with this settings:

Now i have this parent control multiply times on my Scene with different sizes. But now its destroys the proportions of my Card, as you can see below on the screenshot.

So is there a way to ensure the proportions of my Card when scaling or shrinking the parent Panel?

# Answer
> 1 votes
It sounds like you want an AspectRatioFitter component, maybe on the parent panel and maybe on the cards themselves.

---
Tags: unity
---


# Question
Title: Why do I get this compiler error when trying to include Allegro headers on a Mac?
I ran `brew install allegro` on OSX while following this tutorial.

My code looks like this:

```
include <allegro.h>

int main(void) {
  if (allegro_init() != 0)
     return 1;

  /* set up the keyboard handler */
  install_keyboard();

  /* set a graphics mode sized 320x200 */
  if (set_gfx_mode(GFX_AUTODETECT, 320, 200, 0, 0) != 0) {
     if (set_gfx_mode(GFX_SAFE, 320, 200, 0, 0) != 0) {
   set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
   allegro_message("Unable to set any graphic mode\n%s\n", allegro_error);
   return 1;
     }
  }

  /* set the color palette */
  set_palette(desktop_palette);

  /* clear the screen to white */
  clear_to_color(screen, makecol(255, 255, 255));

  /* you don't need to do this, but on some platforms (eg. Windows) things
   * will be drawn more quickly if you always acquire the screen before
   * trying to draw onto it.
   */
  acquire_screen();

  /* write some text to the screen with black letters and transparent background */
  textout_centre_ex(screen, font, "Hello, world!", SCREEN_W/2, SCREEN_H/2, makecol(0,0,0), -1);

  /* you must always release bitmaps before calling any input functions */
  release_screen();

  /* wait for a keypress */
  readkey();

  return 0;
}

```

And I get these error messages:

```
1.c:1:1: error: unknown type name 'include'
include <allegro.h>
^
1.c:1:9: error: expected identifier or '('
include <allegro.h>
        ^
2 errors generated.
make: *** [1] Error 1

```

# Answer
`include <allegro.h>`

This isn't valid; preprocessor directives start with a `#`. You probably meant to be typing `#include <allegro.h>`

Your error indicates this:

> `1.c:1:1: error: unknown type name 'include'
>  include <allegro.h>`

You can read this is the compiler reading `include` as a type, but there's no type named `include` that it knows about so it complains. This should make you question why the compiler *thinks* `include` is a type, because you should know you're trying to use the preprocessor to paste in the content of the Allego header file. Not name a type.
> 2 votes

---
Tags: c, allegro
---


# Question
Title: Make something move when no key is pressed
I am new to game programming and I have a question about my game logic. In my game there is a balloon that is supposed to collect some stars. the balloon moves with the keyboard. When the balloon hovers over a star, the star will go in to the balloon. In order to do that I created a script for my balloon and added a cc.eventManager.addListener to it and in update: function (dt) I managed to move the balloon when the keyboard keys are pressed. Now my balloon works fine. Then I added some stars to my mainGame.js script, and there in update: function (dt) for the mainGame, I calculated the distance between the star and balloon, if they are close enough, the star will go into the balloon. Now I want to do something else. In my game there is an evil force that tries to eat the balloon, When the key is not pressed (the balloon is not moving) this evil force(at the top corner of the screen) will pull the balloon to itself (when there is at least one star in it). This means i should implement something like this:

```
var jumpUp = cc.moveTo(this.jumpDuration, evilForcePosition).easing(cc.easeCubicActionOut())
this.ballon.runAction(jumpUp);

```

but I don't know where and how to do so. I tried to put this action in update: function (dt) of mainGame.js but I got weird outcome.

My question is this: How can I force the balloon to go somewhere when the input keys are not pressed?

Here Are some codes:

This is my update function in mainGame

```
update: function (dt) {
    var ballonPos = this.ballon.getPosition();

    for (var j = 0; j< 10; j++){
        var nStar = this.stars[j];
            if(cc.pDistance(ballonPos, nStar.getPosition()) < 50){
            nStar.setPosition(ballonPos.x , ballonPos.y);
        }
    }//end for j
 },

```

So in this script, if the balloon is close enough, the star will be attached to it and move with it in every frame.

And here is the function that governs keyboard movements in balloon.js:

```
setInputControl: function () {
    var self = this;
    // add keyboard event listener
    cc.eventManager.addListener({
        event: cc.EventListener.KEYBOARD,
        // When there is a key being pressed down, judge if it's the designated directional button and set up acceleration in the corresponding direction
        onKeyPressed: function(keyCode, event) {
            self.freeToMove = false;
            switch(keyCode) {
                case cc.KEY.a:
                    self.accLeft = true;
                    self.accRight = false;
                    break;
                case cc.KEY.d:
                    self.accLeft = false;
                    self.accRight = true;
                    break;
                case cc.KEY.w:
                    self.accTop = true;
                    self.accBot = false;
                    break;
                case cc.KEY.s:
                    self.accTop = false;
                    self.accBot = true;

            }
        },
        // when releasing the button, stop acceleration in this direction
        onKeyReleased: function(keyCode, event) {
            self.freeToMove = true;

            switch(keyCode) {
                case cc.KEY.a:
                    self.accLeft = false;
                    break;
                case cc.KEY.d:
                    self.accRight = false;
                    break;
                case cc.KEY.w:
                    self.accTop = false;
                    break;
                case cc.KEY.s:
                    self.accBot = false;
                    break;
            }
        }
    }, self.node);
},

```

And here is the update in balloon.js

```
update: function (dt) {
    if (this.accLeft) {
        this.xSpeed -= this.accel ;
    } else if (this.accRight) {
        this.xSpeed += this.accel ;
    }
    if(this.accTop){
        this.ySpeed += this.accel;
    }else if(this.accBot){
        this.ySpeed -= this.accel;
    }

    if ( Math.abs(this.xSpeed) > this.maxMoveSpeed ) {
        this.xSpeed = this.maxMoveSpeed * this.xSpeed / Math.abs(this.xSpeed);
    }
    if ( Math.abs(this.ySpeed) > this.maxMoveSpeed ) {
        this.ySpeed = this.maxMoveSpeed * this.ySpeed / Math.abs(this.ySpeed);
    }
    //move!
    this.node.x += this.xSpeed; this.xSpeed = 0;
    this.node.y += this.ySpeed; this.ySpeed = 0;

 },

```

# Answer
> 1 votes
If you need something to happen at the moment when the player stops giving input, you can add a "`inputTime`" field that stores the time of the last input. For the keyboard, you could check if the player has released all the relevant keys, for example.

The code to do that can be placed in `EventListener` for keyboard, but you can also do it in `update`. If none of the `acc*` fields is set, it means that currently there is no input. You can update `inputTime` as long as there is input.

Additionally, in `update` you would check how much time has passed since the last update of `inputTime` (by comparing the current time to the time stored in `inputTime`). If *some* time has passed you can apply your custom logic for that situation.

How much is *some*? The technical lower bound depends on the clock resolution and update frequency, the practical lower bound is on how fast humans type... yet, actually, it depends on your game. So, I suggest to experiment with this value.

# Answer
> 1 votes
> Making something move when no key is pressed

is generally down to either AI or physics.

Your stars gravitate toward the balloon - this is a physics-like effect and should be factored out of `update()` into a function called from `update()`, e.g. `for (star in stars) star.doPhysics()` which should contain this existing code:

`if(cc.pDistance(ballonPos, nStar.getPosition()) < 50){
 nStar.setPosition(ballonPos.x , ballonPos.y);`

Evil force is like a spirit, I think? So you may want to treat as some kind of AI, in which case call `evilForce.think()`. This method then holds logic to control where the evil force goes... this would probably be called every `update()` but I don't know cocos2d; maybe it's just called on a single event.

As opposed to `doPhysics()` and `think()` you could just use a single generic method name `act()`. At this stage in your project, it's all the same and keeps things easier to remember. You can always change / differentiate these, later on. This would allow you to run through *all* entities (stars, balloon, spirits) and just call `entity.Act()`.

---
Tags: cocos2d
---


# Question
Title: How to reference a GameObject that shares position with gameObject in Unity C#
Well, thats a weird title. What i am trying to do is identify the object which position matches the gameObjects position that the script is attached to. Hell, that didn't make it better.

Here's my script:

```
  public Vector2 tilePosition;
  public float tileYPiece;

  void Update()
      {
          tilePosition = transform.position;
          tileYPiece = tilePosition.y + 0.5f;

          pieceIdentifier();
      }

  void pieceIdentifier()
      {
          if ((tileYPiece) == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.y && tilePosition.x == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.x)
          {
              //the GameObject I need to reference does something

          }

      }

```

So the tile position is a Vector2(x, y), and the piece's position is a Vector2 (x, y) as well, and I need to reference the GameObject that shares position with the tile.

I'm confused as hell, if you hadn't noticed, and would reeally like some help

Thanks in advance

# Answer
I'd suggest one of these 2 options:

1. (Quick & dirty) Use FindGameObject**s**WithTag("Piece") (note the plural in Objects) to get all the pieces and then iterate (or use a List and Linq) over them to find the one(s) which have that location. Put those into a variable and that's the reference you're looking for.
2. (I like this one better) you could have a data structure for the tile map, say a 2D array of Tile objects. Then in the Tile class, you have the X and Y positions of that Tile and (this is the important bit) a List of Pieces that are currently on that tile. You would update the list on each tile every time a piece is moved to or from that tile. That way you always know all the pieces that are on each tile at any given time. Oh and each Piece could also have a reference to the tile. Then, all you'd need to do is `this.MyTile.PieceList` to get all the objects on the same tile as the object attached to the script.

(That came out a bit wordy... post a comment if anything is not clear)
> 1 votes

---
Tags: unity, game-mechanics, gameobject
---


# Question
Title: How I can I prevent users from downloading games they're not authorized to?
I am building a platform like Steam and, like Steam, I'd like to prevent users from downloading games they have not purchased yet. For example I don't want users to be able to download a game just because they know the SFTP link to it on my servers.

How can I accomplish this?

# Answer
> 2 votes
For this you would require an implementation of user authorisation (wikipedia).

This could be implemented in many different ways. You will need to look at your requirements and see what needs will be necessary to fulfil.

For example, you could create a simple database where you update a user's privileges after having received a legitimate purchase. Your SFTP-server could integrate with this database to retrieve information about the user's access rights. If the user is allowed to download the resource via the link, the SFTP server can return the downloadable resource, or otherwise reject the user's request.

Another option is to add a proxy, that handles the authorisation of the users, in front of the SFTP server so that the SFTP server is hidden on a local network and only accessible from the proxy. Then the proxy will be in charge of only granting access to legitimate customers.

You can make it as complex or simple as you'd like!

---
Tags: security
---


# Question
Title: How and when do the model to world, world to view, et cetera multiplications happen?
I learn matrix transformations for game design and I struggle with some basic concepts. I see the actual multiplication taking place before rendering in this sequence:

1. **MODEL into WORLD**: multiply each model's vertex by worldMatrix. If the model is big it's a bit of a stress for GPU.
2. **WORLD into VIEW**: well, if Model to World was bad, than multiplying the whole world full of models by some matrix is a huge burden on GPU. Why then in every book authors say that is much better to do exactly this? The VIEW is just a point (one vertex) it's much easier to change one vertex than millions.
3. Well any other steps in this sequence are irrelevant to me right now. I just stuck in 2. cause I don't believe that any one will perform such multiplications.

I'm sure no one multiplies world vertexes by any matrix, If i'm right here then and HOW the whole multiplication stack of transformation happens? I guess I'm missing some low level understanding.

P.S. So to stress my point: Why multiply the whole world by anything? I will only see the part of it! How this huge multiplication is avoided in game engines (openGL, ect).?

P.S.S. Thanks for answers guys! Huge job just to help the me\___ Those are the most detailed answers I've evere gotten on any stachexchange forums. :)

P.S.S.S. I come from 2D visualization of financial data. Some of you point out that it can be the reason of my missunderstanding about why every world object must be processed. My pipeline:

1. object\model space = is just a data serie with bunch of bars and prices. It's a 2D object with "bar" units in X direction and "price" units in Y direction. So by using "i" `Serie.bar[i]` one navigates in this array. I usually say that data series is in "array space" since I use "i" to navigate therer.
2. world space = where 2 data series can co-exist. For example you have price of Google and Tesla in the same chart stacked on top of eachother for analisys of correlation.
3. Camera space - a 2D rectangle in world coordinates. For example `camera.width=300bars, camera.X =11000bar, camera.Y=33 $ per share.`

Using mouse, user changing only camera (that's why it's super wired for me when someone says that view should not be moved and the world should be moved around). Camera coordinates change and when it is time to render, you just look inside camera and do such thing: `for (int i = camera.left; i < camera.right; i++)
{
g.DrawSerie(google.bar[i]);
}` So you see, there is no need in and world transformation here. I know all I need before rendering thanks to "camera being in world coordinates". I guess you can't do in in 3D, but some details are still missing for me.

# Answer
> 11 votes
Think about it logically:

**What is your goal when you render something?**
To display it on the screen!

**What are the constraints?**
The model must be visible to the camera (i.e. in the view frustum, not occluded by other objects, etc.)

**What are the inputs?**

1. A collection of vertices in a coordinate system local to the model's origin.
2. A transformation matrix that describes where and how the model is oriented in the game world.

**What are the outputs?**

1. A collection of vertices in view space (i.e. relative to the view, commonly defined by a single "camera") which can be used to generate fragments, which then become pixels in normalized device coordinates (just like a 2D game, the screen is 2D after all).

**The process goes something like this:**

1. First, you start with a list of vertices in model space (relative to model origin/coordinate system). This allows you to easily modify meshes outside of your game (e.g. in Blender) because the coordinate system is self-contained.
2. Then, the vertices are transformed to world space (relative to game world origin/coordinate system, or game chunk origin). This allows you to do collision detection or other game world dependent logic.
3. Next, the vertices are transformed to view space (relative to camera origin/coordinate system) so that you can decide what is visible to the camera. One such technique is called "frustum culling" and calls for the renderer to ignore vertices behind the camera or outside of the field-of-view.
4. Last, the view space vertices are transformed to normalized device coordinates so that the fragments can be depth-tested, blended, and any other post-processing effects can be applied (e.g. shaders). This is necessary because it allows you to calculate the final color to display at each pixel on the screen.

I suppose if you have no game world, you could eliminate the world space calculation step and go directly from model space to view space (essentially, you'd be saying your model space *is* your world space), but this means you can only have one object in the entire world, and there is no way to do any game world specific logic such as collision between multiple objects. In general, this is not very useful.

As you can see, all of these steps are not only necessary, but the later ones are actually *HUGE* optimizations (frustum culling, for instance) because they can save you from rendering the majority of the things in your scene (especially in small, enclosed areas like the inside of a building). Why spend time rendering the 400,000,000 vertex forest outside when you're standing inside of a 3,000 vertex shack with no windows?

# Answer
> 5 votes
> MODEL into WORLD: multiply each model's vertex by worldMatrix. If the model is big it's a bit of a stress for GPU.

It's not actually that much of a "stress." The GPU is hardware that is tailor-built to perform this operation hundreds of thousands of times with ease. This is important since it seems to be the root of your confusion. It's just not nearly as big of a deal as you think it is.

> WORLD into VIEW: well, if Model to World was bad, than multiplying the whole world full of models by some matrix is a huge burden on GPU.

In fact, unless some vertex shader needs to do some work in world space (which isn't always necessary, this step and the prior step are combined. That is, the model-to-world and world-to-view matrices are multiplied together once, before rendering, and every rendered vertex is multiplied just once by the combined matrix. Lighting work is sometimes done in view space, so the transformation tends to pause there, but it's also possible to combine the entire world-\>view-\>clip space transformation into a single matrix if one doesn't need to do anything in view space either.

This further reduces the effective cost of the transformations.

> The VIEW is just a point (one vertex) it's much easier to change one vertex than millions.

No, the view is conceptually a point and a basis (a rotational frame of reference). You can't "just change the view." You need to know the positions of all vertices *relative to* the view's location and orientation eventually, so you *must* transform all the vertices. You could use the position and orientation of your view in world-space to do some lighting work, but ultimately you'll still need coordinates relative to the view frame for clipping them against the view frustum, so that's kind of a moot point.

> I'm sure no one multiplies world vertexes by any matrix, If i'm right here then and HOW the whole multiplication stack of transformation happens? I guess I'm missing some low level understanding.

You're not right. World vertices are multiplied by matrices to bring them into clip space.

The geometry transformation pipeline is fairly straightforward: geometry starts in model space, is transformed to world space, then to view space, then to clip space, where clipping against frustum planes is performed. Then the perspective division is applied, coordinates are transformed to normalized device coordinates and eventually to window coordinates where they are rasterized.

There's no hidden tricks, really, other than the fact that you can sometimes skip spaces you don't need to explicitly be in by combining matrices (e.g., multiply model-space vertices by a combined world-view-projection matrix to go right to clip space). The cost for doing this transformation is extremely small on the vertex-by-vertex basis.

# Answer
> 3 votes
Please allow me to elaborate what the responsibility of the GPU should be in the most common scenarios as well as the responsibilities of the CPU, game-engine, and OpenGL.

---

# Basics to the OpenGL Pipeline

First, in the context of the OpenGL rendering pipeline, the GPU has a vertex shader program which processes only 1 vertex at a time. This vertex is transformed by 3 special matrices (in this order):

1. Model Matrix - the vertex is taken from local model coordinates and placed into world coordinates. This is where you position/orient/scale your model to be in its proper place relative to the whole scene.
2. View Matrix - the vertex is transformed in such a way that it looks like it is being viewed from a particular location, angle, and distance. *This mimics the behavior that a camera might; however, in OpenGL, there is only 1 camera (which is always facing into the screen)*.
3. Projection Matrix - the vertex is transformed according to the parameters of the **viewing frustum**. This is where things like perspective divide occur (in the case of perspective projection).

After being processed by the vertex shader, the transformed vertex is combined with other vertices during primitive assembly, then further operations such as rasterization and fragment processing occur.

---

# Who is responsible for what?

Your initial observation is valid, saying that the GPU could be stressed if it has process each vertex of a large scene. This means we have to be careful about what we send to the GPU. As you indicated, it is pointless to waste GPU time with processing things that never end up on the screen. So, in the context of game-design, a game-engine must decide, in some manner, how to manage which parts of the scene are drawn. There are many methods to doing this, but I'll list a few:

* Game engines can divide the map into sections and only render objects within a certain distance of the observer/player. Optionally, fog is used to make a gradual seam to the parts of the world without content.
* Game engines can control level of detail so low-poly models can be used where the difference is negligible (e.g. models in the distance).
* Game engines can look at which parts of a scene might be occluded by those up front. Rather than relying on a depth test, the game engine can omit all of these vertices from being sent to the GPU in the first place! This is particular useful for rendering cities.
* Rather than relying on mechanics of pre-built engines, you can write your own to control how the GPU is used.

All of the above game-engine optimizations occur on the CPU since they involve making decisions on which data to sent to the GPU. However, there are other optimizations provided by the GPU and the OpenGL pipeline. This includes things such as per-sample operations and tests (such as depth test), but also includes things such as view clipping. In the case of clipping, this prevents vertices outside of the viewing frustum from being further processed.

OpenGL also provides some more methods of optimization by allowing you to offload your models into the GPU memory through the use of Vertex Array Objects and various types of buffer objects. OpenGL also has various rendering modes, such as indexed rendering which can decrease the number of vertices actually sent to the vertex shader.

As far as optimizations go, there are predominantly two places where you save time the most.

1. First, you save a large amount of time by deciding what to send to the GPU (these are the game-engine optimizations).
2. Second, you save a large amount of time by offloading data to the GPU as opposed to sending data from the CPU each time you render a frame. Once in GPU memory, drawing the model becomes very quick.

Many of the other optimizations are still useful, but may only shave off a small amount of processing time.

---

I hope this helps provide you with the "low-level" understanding you were looking for. Feel free to ask questions if anything is unclear!

# Answer
> 1 votes
I think the other answers has already covered the bulk of this, yet I want to make some assertions on the P.S.:

> P.S. So to stress my point: Why multiply the whole world by anything?

Because the world space does not match, it is representation on screen. For instance, in a 2D game, you may be contempt with applying an offset to the world position and drawing only what is in the bounds of the screen... not in 3D. Why? Because you have rotation and perspective. To archive these effects we use matrix transformations.

That is without solving the problem of occlusion. Without changing to camera coordinates you lack a way to tell what object hides another, and thus we need the transformation.

Furthermore, consider that you may need additional geometry (outside of viewing frustum) to make other effects, such as shadows or reflections.

> I will only see the part of it! How this huge multiplication is avoided in game engines (openGL, ect).?

Game engines may resource to additional work to keep the GPU and CPU load low. It should be noted that video games has been using the techniques I describe below for a long time, and modern GPU hardware is much better than it was when they were first introduced.

Combining these techniques allows huge open world games with thousands or millions of objects, where sending everything to the GPU does have an impact on the performance.

For example, game engines no longer rely solely in the painter algorithm for 3D; instead, the engines leave the occlusion problem to the GPU, which can handle, for example, interlaced triangles thanks to the depth buffer. Although there are situation where the engine can optimize occlusion, it is not the general case.

---

*Binary space partioning*

Let's start at the age old Doom. The original Doom was big for the constraints of the hardware of the time. The engine was based on the one from Wolfenstein 3D which worked by ray-casting to find the distance to the walls across the horizontal field of view and scaling them in screen to make the effect of perspective.

Doom added vertical levels to the map, which meant that when a step on the floor was found, the engine had to revisit the area to find what is beyond that step in a recursive proccess... this implies that "complex" vertical structures (stairs) are very taxing to performance.

The solution was a technique known as BPS (Binary space partitioning), which *in general terms* means to divide the world in half (make a binary partition) and then in half again, and so... adding the whole structure to a tree structure that can be navigated to find nearby objects or objects that are in certain general direction from another. This means that they did not have to query the whole geometry each step.

Since, and thanks to Doom, BSP is common in game engines.

---

*Split your world*

We want to avoid loading the whole map at once. Instead, we want to load only the parts we need.

Various games for the original PlayStation would use every door of every room as a load point. It should be noted that loading was (and continues to be) a bottleneck for PlayStation.

But that doesn't means that there weren't clever solutions and workarounds. For instance Crash Bandicoot used narrow and sinuous paths for its levels, this allows hiding fact that only objects near the player are ever loaded, as the path twists often and keeps the distance the player may see limited.

Nintendo 64 had a different set of constraints. Even with better load speed, there is a cap for the size of the map. For instance, Mario 64 could not afford a large open world. Instead the world was divided in regions acceded by the pictures in the walls, and the size of each one was kept in check.

At some, point the same was considered for Zelda: Ocarina of Time (it would be constrained to Hyrule Castle, and you would enter pictures in the walls). Fortunately, improvements on the engine allowed for larger maps, yet there are still load points between regions.

Finally consider old GTA games, which divided the map in smaller ones. GTA Vice City had two main islands loaded separately, when the player is traveling from one to the other there is a load screen... from one city the other is visible at distance, but this is only a low polygon model.

---

*Provessive load*

Consider now Minecraft. In spite of its unsophisticated appearance, it has a high polygon count (consider all the triangles for all the cubes for a virtually endless map, that is a lot of vertex). How does it handle them? Well they are loaded in chunks, the engine only sends to the GPU chunks that are nearby the player.

If you experiment with render distance and other graphics options of Minecraft - or also due to a chunk that failed to load - you may find yourself looking at the void (well, just the skybox, actually) where there should be land.

---

*Level of detail*

GTA San Andreas did not have load screens dividing its map, how did they do it? They use LOD (Level of Detail)... GTA San Andreas works on a low polygon model of the complete game world (including roads and building) that is always loaded, and then other models are loaded on top of it (including roads and building, again). The models are replaced with other of higher level of detail as they get closer they get to the camera.

This means that if you move fast enough (or you PC is slow enough) you can catch up to the edge where models are being loaded... yet, thanks to the basic model that's always there, you will always see roads and a crude version of buildings instead of the void.

---

That much the state of the art (plus any custom optimizations for particular cases and any proprietary algorithms of which I am not aware). These technologies, in addition to the progress done GPU hardware allows huge maps such as those found in GTA, Skyrim, Red Dead Redemption, Breath of the wild, etc...

P.S. OpenGL? Not a game engine.

---
Tags: matrix, transformation, viewport, view
---


# Question
Title: How to display a text in the impact point position
In my 3d game, i would like to display a text 'near' the impact point of a bullet. I think i'm having problems setting properly text position. This is my code. The script is attached to an object Canvas. position is the Vector3 impact position.

```
GameObject obj = new GameObject ();
Text _text = obj.AddComponent<Text> ();

_text.transform.position = position;
_text.text = message;
_text.fontSize = startSize;
_text.color = color;

```

I'm pretty sure i've to convert from a world space to a 'user interface' space. Thanks

# Answer
> 1 votes
Try this:

`_text.transform.position = camera.WorldToScreenPoint(position);`

You'd need to get a reference to the camera first. See an example from the docs

---
Tags: unity
---


# Question
Title: Unity Matrix4x4 to rotate a point around a pivot / axis
I need the Matrix4x4 to rotate around a given axis *that does **not** go through (0,0,0)*. Is there some built in straightforward way to do this in the Unity libraries, or do I need to build and maintain my own?

Below is the formula I'd use to build my own in case somebody needs it:

> We will define an arbitrary line by a point the line goes through and a direction vector. If the axis of rotation is given by two points P1 = (a,b,c) and P2 = (d,e,f), then a direction vector can be obtained by ⟨u,v,w⟩ = ⟨d-a,e-b,f -c⟩. \[...\] Assuming that ⟨u,v,w⟩ is a unit vector so that L = 1, we obtain \[...\]
>
> Source

I do need the rotation Matrix, not just the rotation. If I didn't need the Matrix I could use (not tested, may contain flaws, but you get the idea):

```
public Vector3 RotatePointAroundAxis(Vector3 point, Ray axis, float rotation) {
    return Quaternion.AngleAxis(rotation,axis.direction) * (point - axis.origin) + axis.origin;
}

```

So far the best I've got is the equivalent of the above (not tested, may contain flaws, but you get the idea), but it looks quite wasteful:

```
public Matrix4x4 RotationMatrixAroundAxis(Ray axis, float rotation) {
    return Matrix4x4.TRS(-Axis.origin, Quaternion.AngleAxis(rotation, Axis.direction), Vector3.one)
         * Matrix4x4.TRS(Axis.origin, Quaternion.identity, Vector3.one);
}

```

# Answer
> 1 votes
I don't believe that Unity has a built-in method for this. I believe that Transform.RotateAround is the closest, but if there's a utility function being used there then it isn't a documented one.

Your proposed method seems clear and straightforward, and not particularly wasteful. After the compiler gets done with it, it's likely to be quite good code for building that matrix.

The main optimization you could do yourself would be to construct only the rotation matrix, use it to help you build the combined translation (pre- and pos-rotate), then set the translation of the matrix to the result. This would make your intent a little more clear to the compiler.

In my opinion, unless you're calling this function in a very hot inner loop, it probably doesn't matter which way you do it.

---
Tags: unity, rotation, matrix, axis, pivot
---


# Question
Title: Game launcher / updater download delta diff
I'm making a launcher for my game (using Unity3d).

I want it to have the following features :

```
Compare game version to latest version and update if necessary
Check files integrity and update if differences are found
Download/patch needed files

```

So comparing the game version is easy : I just parse a version.txt file and compare it's value to the latest server version.

Checking file integrity sounds easy too : Make a list of all files in the game folder, order the list, get a checksum and check if it corresponds.

Now here's the difficult part : Downloading the required files.

My first idea was : If a file checksum is different, download that file. But unity assets are compressed into large files, so even a simple change will lead to the download of a 2gb file...

So I'm now looking for a way do download only the different parts. I heard about VCDIFF / xdelta, apparently they can be useful to get a "delta patch" of different binaries. Cool. But how can I compare two folders if one of them is distant, without downloading it all before ?

Could torrent be an answer ? How are game/unity devs doing this ?

* Maybe rsync can be useful, but is it safe if hundreds of clients are simultaneously updating using rsync ?
* I heard about Unity's AssetBundles. Is that useful and is it ok to put ALL my assets in bundles ?
* How would I display a progress bar in unity showing the rsync progression ?

# Answer
You need to start by separating the concept of updating from the concept of repairing.

The algorithm is roughly the following:

* Get the claimed version of the client.
* Ask the server for that version.
* The server returns the checksums for that version, and whatever or not there is a new version.
* Check the integrity of the files with the provided checksums.

Now, you have either a good or a corrupted copy. In addition, there may or may not be a newer version. Depending on those two variables, you pick:

* Good Copy, No new version: Nothing to do.
* Good Copy, New version: Patch update.
* Corrupted Copy, No new version: Repair.
* Corrupted Copy, New Version: Potential Full update.

Note: you can do this decision file per file.

Let us see how each one works:

---

## Nothing to do.

Done.

---

## Patch Update

You need to have precomputed, on the server, the patches from the old versions to the current one (e.g. with bsdiff, xdelta, etc...). Since this is on the server, both the last and the old version are available for comparison, so you can create the patch files. You would keep them around because a client may fall behind more than one update.

It works like this:

* Ask the server for the patch notes starting from the client version.
* The server looks for the patch files...
* If there are not patch files, return failure and fallback to Full update.
* If the patch files are available, return the list of patch files from the requested version to the current one.
* The client then downloads and applies the patches in order.
* Check version and integrity again at the end of the process.

---

## Repair

To find the corruption, you can split the file in pieces of fixed size (e.g 4MB) and compute checksum corresponding to each piece. In the server, you would have detailed data about the files; this includes the length of the file and the checksums for the pieces.

This is the process:

* For the file that failed checksum, ask the server for detailed data.
* The server returns the size of the file and the checksums of the pieces.
* The client compares the size, if it does not match then truncate (or grow) the file to the right length.
* Compute the checksum of each piece of the file and compare it with the one you got from the server.
* If the checksum does not match, download that piece from the server and update it in the client.

---

## Potential Full Update

You will run the full update (download the full file and replace it) for a file that is missing, or for a file for which there are no patch files. However, if you have a corrupted file, you need to decide if you want to repair it and the patch update or you want to download the full file and replace it. So, consider computing the piece checksums as part of the process that computes the full checksum of the initial check^... this way you will have them available already for the repair process.

^: For instance, the global checksum of the file can be the hash of the checksum of the pieces. Do not use partial checksums, doing that will make the checksums not match after the first corruption is found, and we don't want that.

This optimization will allow you to see how corrupted is the file before deciding if you want to repair it.

Now your criteria need to be based on:

* How corrupted is the file
* How much have the file changed (how big are the patches)

Compute how much do you have to download to fix the damaged pieces plus the patches, it is accounts for more than the full size of the file... download the full file instead. Otherwise, do a repair and then a patch update.

---

## Addendum

You may want to add rules to avoid repairing and patching certain files. For example, do not bother repairing or patching files that are too small. In addition, you want to black list executable files, because many antivirus will not be happy with your updater editing executables (besides, executables should be small; the bulk should be in the assets).
> 1 votes

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


# Question
Title: Null reference exception any time I try to access an array member, referenced from another class
I'm not sure what's going on. The error is coming from something like that very bottom line. I feel like I've tried a million different things and I'm at a loss. Any sort of data that I try to access from one of the members of my "dogButtonScriptArray" can be read just fine but when I try to copy it over to a local variable I get the error. Also btw, in the inspector, I can see clearly that each member of the array is filled correctly.

```
public class GameControl : MonoBehaviour {

public static GameControl control;

public int gold;
public DogSelectorButtonScript[] dogButtonScriptArray;
private bool[] unlockedDogsArray;

void Awake(){
    if (control == null){
        DontDestroyOnLoad (this);
        control = this;
    }
    else if (control != this){
        Destroy (gameObject);
    }
}
void OnLevelWasLoaded(){
    if (SceneManager.GetActiveScene ().buildIndex == 2) {
        dogButtonScriptArray = FindObjectsOfType <DogSelectorButtonScript> ();
        bool test = dogButtonScriptArray [2].isUnlocked; // this works fine
        unlockedDogsArray [1] = test; // error here
    }
}

```

# Answer
> 5 votes
At no point in this code do you allocate `unlockedDogsArray`. You declare it near the top of your class, but you don't initialize it to anything, so the array is a null reference. You never do anything like `unlockedDogsArray = new bool[size]" or`unlockedDogsArray = someOtherArray\` in the code you've posted.

Unless you do that elsewhere, the `unlockedDogsArray` remains null when you go to access it on the last line (`unlockedDogsArray [1] = test`) and thus you get a null reference exception.

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


# Question
Title: How can I tell if I can use a song from YouTube in my game?
I am in the middle of creating a game and I'm confused about the copyright law for the following songs as I want to use them in my game.

How can I legally use these songs in my game?

# Answer
I am not a lawyer. If you want serious legal advise, ask one. Do not trust anonymous strangers on the internet with providing legal advise to you. But my layman interpretation of international copyright laws would be as follows:

National anthems are usually (but not always) in the public domain. Either because the copyright has expired or they were released as public domain in the first place. But that does only apply to *the composition and lyrics*. It does not apply to *a specific rendition* of it. When someone plays a public domain song and records it, they might not own the copyright to the song, but they own the copyright to that recording of the song. So you can not just take any recording of *The Star-Sprangled Banner* from YouTube and put it in your game. You either need to perform it yourself (for example by entering the notes into your favorite digital audio workstation), ask the performer for permission (who might not be the person who uploaded it) or find a vintage recording which is so old that it is public domain.

In the last case the audio quality will likely be so bad that it won't be suitable unless you *want* it to sound vintage. But even then you need to be careful. If someone digitalized it and did some filtering touchups ("digital remastering"), that might be enough work for them to claim a copyright.
> 6 votes

# Answer
When a book becomes public domain (say Shakespeare), that doesn't mean you can just grab the book - that'd still be theft. There's a difference between the words and the object that contains them.

With videos and music, there's an additional layer: There's the song, the recording of the song, and the object that holds the recording. If a song is public domain, you can't just grab the CD, that's still theft. Similarly, if a song if public domain, you can't just use the recording without permission. What you can do is make your own recording - time to start singing classes.

If you want to legally use a recording someone else holds the rights to, you need to ask them for permission. If they agree, you can use the recording.
> 0 votes

# Answer
The linked mariachi song is marked as "Jarabe Tapatio" by "Mariachi Silvestre Vargas" who died in October 7, 1985 in Guadalajara... Mexican Copyright law goes for 100 years after the death of the author. Therefore, this work is yet to go into public domain.

With that said, you should be able to find similar music under public domain. Look for something older; anything prior 1800 will be public domain. Yes, the Jarabe Tapatio dance is that old.

---

I will expand on this since I got comments saying "Jarabe Tapatio" is a folk song with no credited author.

What happens is that the version from the Mariachi Vargas de Tecalitlán is quite old, and it is what you hear everywhere. However, it is not as old as Jarabe Tapatio, which is of unknown author. Now, if the OP wants the version from Mariachi Silvestre Vargas, then that is under copyright.

It is similar to what happened with the Lambada. It was a folk dance from Brazil, and many musicians had lambada songs. Then the group Kaoma popularized the Lambada with their song also called Lambada. Now, when you search Lambada, you find Kaoma's Lambada.

---

How can you use "Jarabe Tapatio" by "Mariachi Silvestre Vargas" legally? You need to contact Mariachi Vargas de Tecalitlán and negotiate a license.

Alternatively, as I said above, you can find similar music by another author. Hopefully something on public domain.

---

As per the Mexican anthem, it is considered public domain in U.S.A. and the Mexican government holds the moral rights, but no property rights. This means there is no copyright on it. Although, you still need to credit it as the Mexican anthem.

You should be careful about the interpretation you use, take an official version from the goverment. This is because musicians still have rights over their performance.

You may also use the instrumental version of the Mexican Anthem from Wikimedia

---

Ok, the U.S.A Anthem. The original music and lyric for The Star-Spangled Banner are fully in public domain. Again, musicians still have rights over their performance.

The Library of Congress has recordings of the Star-Spangled Banner available... although, you would want to remaster this recordings.

So, instead try a version from NASA or one from the U.A Air Force Recordings. There are published under the Freedom of Information Act, and are not under copyright.
> 0 votes

---
Tags: copyright, music
---


# Question
Title: How can I implement pre-rendered 2D sprites that can face any direction?
I've been Googling how games like Clash of Clans render their troops, and it appears they are pre-rendering 3D models to 2D sprite sheets before runtime, and rendering those 2d images at runtime. However, troops in Clash of Clans can face any direction.

In my similar game, if I were to create an image for every orientation (0-360 degrees) for every troop type (there are 18 types) at each frame in their animation, they would have to produce a *massive* amount of images. I can't imagine this is what other developers are doing, so how can I actually accomplish this?

# Answer
1. Typically there are less than 360 directions. Common case is 8 or 16. Animations are quite short too.
2. **Automation is your friend.** Write a Blender/3DMax/etc script to load a model from the list, render it in every required frame and direction to an image. Tag images according to content and address them from the game.
3. Pack everything into texture atlases (aka sprite sheets) for faster access.

In the end, you will end up with several throusands of sprites, neatly packed into just dozen of atlases. Not such a big deal ;)

I could not find an image from CoC, but here is Diablo II, which used the same approach to characters animations. E.g. Amazon melee attack:
> 45 votes

# Answer
Also keep in mind the low resolution of these images. There are a couple more things you can do to save space, although I don't know which of these are used by Clash of Clans:

* You can bias the positioning for troops to face standard directions (N,E,S,W,NE,SE,SW,NW) more often than not, then optimize only for standard directions.
* You can do a combined approach, where you pre-render only some directions. During the frame, you can render the troops which don't match an existing image, or use the closest image if you run out of time.
* Use left/right symmetries whenever possible to cut the number of stored frames in half.
* You can prioritize certain animations like walking and resting, storing more directions and frames for these. Then deprioritize other animations, like the swinging of a sword, where you store fewer directions and frames (I suggest keeping more directions for the first and last frame of the swing).
* You can fake the remaining directions by using the closest image then stretching it.

Overall, we might be talking about 18 units, up to 8 directions, maybe 2 seconds of animations at 20 frames per second, an average of 64x64 pixels, and about 2 bytes per pixel. That's 18x2x20x64x64x2 = 50 MB. They might also scale the number of directions, resolution, and number of frames based on the capabilities of the device and number of units used on the map.
> 8 votes

# Answer
In addition to @Kromster answer, note that images are often compressed significantly, and in large "atlas" images where there are many repeating elements (e.g. blank background) the compression is significant. So the final "size" of the images is not just a straight multiplication of individual image size.
> 2 votes

# Answer
For a classic example, I suggest you download the original Doom, which used 2D sprites in a pseudo-3D environment. The sprites had 8 facing directions (relative to the player's viewpoint), and from memory about 8 different sizes as they got closer. This was very visible, but it was acceptable enough for gameplay. In Clash or other isometric-viewing games there's no need to consider distance, of course.
> -2 votes

---
Tags: 3d
---


# Question
Title: C++/GLEW strange artefacts when drawing a 3D cube
I'm working on a bad 3D game engine in C++ with the help of GLEW, GLM and GLFW. I made the engine halfway through in 2D, but I wanted to rewrite it for 3D. I skipped the part with the per-vertex color, and just set the color solid red with the fragment shader. But I have these strange, flickering artefacts appearing. I don't have any clue where this comes from...

**Note that the flickering got much worse while recording.**

**EDIT:**

How I set up my window:

```
glfwWindowHint(GLFW_DOUBLEBUFFER, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

glfwWindow = glfwCreateWindow(int(size.x), int(size.y), title.c_str(), NULL, NULL); /* Creates window (GLFW)*/
glfwMakeContextCurrent(glfwWindow); //Binds OpenGL

setClearColor(color);

/* GLEW Stuff */
glewExperimental = GL_TRUE;
int glewState = glewInit();
if(glewState != GLEW_OK){ /* If glewInit() fails */
    throw(AmethystException("Could not glewInit(). GLEW Error: " + std::string((const char*)glewGetErrorString(glewState))));
}

//TODO: Move openGL related shit out of here
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_BLEND);                                 /* Transparency */
glEnable(GL_DEPTH_TEST);

glDepthFunc(GL_LESS);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* Transparency */

```

And how I clear every frame at the end:

```
int errorCode = glGetError();
if(errorCode != GL_NO_ERROR){
    Logger::error("GLEW error (" + std::to_string(errorCode) + ")");
}

glfwPollEvents();
keyboard.pollKeyInformation(glfwWindow);

if(glfwWindowShouldClose(glfwWindow)){
    Logger::info("Received close request", 3);
    return false;
}else{
    glfwSwapBuffers(glfwWindow);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    return true;
}

```

Is there anything that stands out? I also added a second video. There should only be solid red cubes.

# Answer
Ok, I found out what it was. My fault for using code I don't fully understand what it does.

```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

This was the cause for the flickering. Removing them fixes everything. I don't know why tho. Those two lines are back from my unfinished 2D engine.
> 0 votes

# Answer
What you're seeing is a partially rendered image.

The flicker is due to the glClear() command erasing what you just drew to the front buffer (the window) and the squares are due to the way the GPU draws its triangles tile by tile.

You are rendering to the front buffer which is being displayed.

You need to render to the back buffer and swap the buffers (possibly with vsync) or an off-screen frame buffer and then copy it to the front buffer (no vsync possible).

Create a context with both a front and back buffer, use `glDrawBuffer(GL_BACK)` to draw to the back buffer and then call your platform's swap buffer command (`wglSwapLayerBuffers` on windows, `glXSwapBuffers` on X11, `glSwapAPPLE` on OSX, etc).
> 0 votes

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


# Question
Title: How should I make realistic electricity?
I am currently designing electricity for my game. If you've ever played or seen Factorio, this is pretty much the exact way I want it to be.

Okay, on to theory: What I came up with is some sort of power source produces a certain amount of Watts per frame. Most power sources cannot store any energy, so at the end of the frame, it is all lost.

Machines connected by wires to energy sources will perform a Dijkstra-style flood-fill from themselves through all connected wires, ignoring wires that have already been processed. The Watt cost will slightly increase for each wire it passes through (to simulate energy loss) and when it reaches a battery or power source, it will drain as much as it needs. If the source doesn't have enough, it continues to search for more power. If, by the end of the frame, it doesn't have enough Watts, it simply works slower or stops working entirely.

After all machines have done this, all batteries will perform a similar flood-fill, but ignoring other batteries, and will attempt to take ALL of the energy from sources (up to its storage capacity).

Then, all power sources discard all energy.

Is this how it actually works? I want to use numerical values, so just being connected to an energy source is not enough. Thanks.

# Answer
Factorio handles all energy-relevant machines (generators, consumers and storage) by "power grids". A "power grid" is a network of all machines which are connected to each other by the same mesh of electricity poles.

That means when you place a power pole, you can perform one flood-fill to enumerate all objects which belong to that power grid and puts them into a list. Caching the machines which are on the same electric grid has the advantage that you don't need to perform an expensive flood-fill every frame.

(this is a simple solution, but not necessarily the most efficient one in every situation. You might want to check out this article on the Factorio Dev Blog. It gives more insight into the Factorio electric grid system)

Now the math isn't difficult anymore. You just sum up the consumption of all consumers and the production of all generators on each grid. If one outnumbers the other, you check if the difference can be fulfilled by storage. If it can't, you proportionally reduce the output of all generators (they run on reduced capacity) or proportionally reduce the efficiency of all machines (lack of energy).
> 6 votes

---
Tags: physics
---