# Question
Title: In Unity, why do I get a "does not implement right interface" error when trying to sort my list of objects?
I am trying to create a crafting panel that sorts the list of items you can make alphabetically, yet I cannot figure out why `.Sort()` is not working.

What I have is a game object that holds a list of all the items you can make and the requirements, then in my crafting script I access the game object for the list and display the info.

Everything works fine until I try to sort anything. `craftDatabase` is what I need to be sorted. Also, it needs to be sorted by `ItemID`.

---

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

public class CraftDatabase : MonoBehaviour
{
    public List<Blueprint> craftDatabase = new List<Blueprint>();
}

[System.Serializable]
public class Blueprint
{
    public string itemId;
    public int itemAmount;
    public float itemCraftTime = 1f;
    public CraftPanel.subsections subsection;
    public CraftPanel.workstations workStation;
    public List<requiredItem> requiredItems = new List<requiredItem>();

    [HideInInspector]
    public string desc;

    [System.Serializable]
    public struct requiredItem
    {
        public string itemId;
        public int itemAmount;
    }

    public Blueprint()
    {
    }
}

```

---

When I try to throw in `craftDatabase.craftDatabase.Sort();` it gives me this error:

> `ArgumentException: does not implement right interface`

How do I fix this error to use `Sort()`?

# Answer
Before we can use `Sort()`, we need to know how to sort between instances of the *type* we are using. The error is complaining that you *do not* have the required sorting functions, which are sought out through an `interface`.

An `interface` is basically a set of method signatures. Any class that *uses* that `interface` must implement the same methods. If you are unfamiliar with using interfaces, I suggest you follow this Unity scripting tutorial.

In this context, this allows us to take a *generic type* and *guarantee* that it can be sorted; we can write our own methods to handle comparing two instances.

---

According to official documentation, you need to implement either `IComparable` or `IComparable<T>`. The key difference is that the inclusion of `<T>` makes the method *generic* and more adaptable. This also makes it more confusing, and it looks like we do not need to use *generics*, so let's use `IComparable`.

---

According to official documentation, to implement `IComparable`, we only need to implement `CompareTo(Object)`. This method must return an `int` value, which represents the approximate compared order of the local `Object` and the `Object` that was passed in.

* If the local `Object` is greater, we need to return a **positive** number.
* If the passed in `Object` is greater, we need to return a **negative** number.
* If the two `Object` types are equal, we must return **zero**.

---

This actually becomes quite easy, in context. You want to compare a `String`, which should already implement a variation of `CompareTo()`.

To allow sorting in a generic list, your `Blueprint` class should look as follows:

```
class Blueprint : IComparable
{
    public string itemID;

    ...

    public override int CompareTo(Blueprint other)
    {
        return itemID.CompareTo(other.itemID);
    }
}

```
> 2 votes

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


# Question
Title: Unity - Access to svPosition in fragment shader
I am trying to access to the `svPosition` in my fragment program in Unity but I keep having this error.

> invalid input semantic 'POSITION': Legal indices are in `[1,15]` invalid `ps_3_0` input semantic 'POSITION'

Here are some information about my whole shader.

```
struct : float4 pos : SV_POSITION;
vertex : o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
fragment : col.rgb = i.pos.xyz;

```

Any idea how to access this value?

# Answer
> 1 votes
According to the error, you're using shader model 3.0. According to the documentation of System Value Semantics, they are not available in DX9. You will have to use shader model 4.0 or you will simply not be able to use this semantic.

Add this to your shader:

```
#pragma target 4.0

```

# Answer
> 0 votes
I found this thread in the Unity Answers, maybe it will be of some assistance?

edit(after being reprimanded ;D ): apparently, you cant just pass the SV\_POSITION to the pixel(fragment) shader. this link shows a workaround by storing the SV\_POSITION in a separate texcoord, and giving the fragment shader as input a struct with both texcoords (TEXCOORD0 and TEXCOORD1). Then inside the pixel shader you can use TEXCOORD1 to you liking.

https://forum.unity3d.com/threads/utilizing-position-in-your-fragment-output-causes-semantic-error-in-d3d9-mode.345200/

---
Tags: unity, opengl, shaders, directx, cg
---


# Question
Title: How to create a transparent mask in Love2D
Since Love2D doesn't support SVG, I'm looking for other ways to create solid, compound shapes. Anything that has straight edges can be drawn using a polygon, but I haven't yet found a way to mask an circle or ellipse, or in other words, subtract a circle or ellipse from the object being drawn. Is this possible with Love2D?

# Answer
I found the answer -- What I was calling a mask is called a stencil in Love2D. See https://love2d.org/wiki/love.graphics.stencil and Make some black pixels transparent in Love2D.
> 2 votes

---
Tags: love2d
---


# Question
Title: Animated textures for models; How to write a shader?
Was watching some Rocket League and notice there was animated decals and wheels.

.

I would like to implement something similar to the effects in the image above.

How would I go about writing a Unity Shader to do the wheel effect?

I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect?

# Answer
> 17 votes
I'll build this up in a few layers so you can see how it comes together.

Start by creating a new shader in Unity by choosing `Create --> Shader --> Unlit` in either the Assets menu or the right-click context menu in the Project window.

In the top block we'll add a `_ScrollSpeeds` parameter to control how fast the texture moves in each direction:

```
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
    _ScrollSpeeds ("Scroll Speeds", vector) = (-5, -20, 0, 0)
}

```

This exposes a new 4-component float property in the material inspector, with the friendly name "Scroll Speeds" (similar to adding a `public` or `Serialized` variable to a `MonoBehaviour` script)

Next we'll use this variable in the Vertex shader to shift the texture coordinates (`o.uv`), by adding just two lines to the default shader:

```
sampler2D _MainTex;
float4 _MainTex_ST;
// Declare our new parameter here so it's visible to the CG shader
float4 _ScrollSpeeds;

v2f vert (appdata v)
{
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.uv = TRANSFORM_TEX(v.uv, _MainTex);

    // Shift the uvs over time.
    o.uv += _ScrollSpeeds * _Time.x;

    UNITY_TRANSFER_FOG(o,o.vertex);
    return o;
}

```

Slap that on a quad (with a lovely free giraffe texture by Kenney) and you get:

To get the texture scrolling outwards in a ring, we could just use a mesh subdivided like a spiderweb, with the uv v coordinate increasing from the center out. But that will give some sawblade-shaped artifacts on its own. Instead, I'll show how we can calculate our UVs per fragment.

This is a bit more costly, both because of the trig & length operations (which are more expensive than basic math) and because it's not as efficient to predict & cache texture data in the hardware when calculating texcoords per fragment, compared to just interpolating them between vertices. But for a little special effect like this, it's not excessive.

```
v2f vert (appdata v)
{
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);

    // Shift the UVs so (0, 0) is in the middle of the quad.
    o.uv = v.uv - 0.5f;

    UNITY_TRANSFER_FOG(o,o.vertex);
    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    // Convert our texture coordinates to polar form:
    float2 polar = float2(
           atan2(i.uv.y, i.uv.x)/(2.0f * 3.141592653589f), // angle
           length(i.uv)                                    // radius
        );

    // Apply texture scale
    polar *= _MainTex_ST.xy;

    // Scroll the texture over time.
    polar += _ScrollSpeeds.xy * _Time.x;

    // Sample using the polar coordinates, instead of the original uvs.
    // Here I multiply by MainTex
    fixed4 col = tex2D(_MainTex, polar);

    // apply fog
    UNITY_APPLY_FOG(i.fogCoord, col);
    return col;
}

```

That gives us something like this (here I increased the tiling parameters in the material so it's clearer what's happening - wrapping only a single repeat of the tile around the circle looks distorted and weird)

Lastly, to tint the texture by a scrolling gradient, we can just add the gradient as a second texture and multiply them together.

First we add the new texture parameter at the top:

```
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
    _TintTex("Tint Texture", 2D) = "white" {}
    _ScrollSpeeds ("Scroll Speeds", vector) = (-5.0, -20.0, 0, 0)
}

```

And declare it in our CGPROGRAM block so the CG shader can see it:

```
sampler2D _MainTex;
float4 _MainTex_ST;

// Declare our second texture sampler and its Scale/Translate values
sampler2D _TintTex;
float4 _TintTex_ST;

float4 _ScrollSpeeds;

```

Then update our fragment shader to use both textures:

```
fixed4 frag(v2f i) : SV_Target
{
    float2 polar = float2(
           atan2(i.uv.y, i.uv.x) / (2.0f * 3.141592653589f), // angle
           length(i.uv)                                    // radius
        );

    // Copy the polar coordinates before we scale & shift them,
    // so we can scale & shift the tint texture independently.
    float2 tintUVs = polar * _TintTex_ST.xy;
    tintUVs += _ScrollSpeeds.zw * _Time.x;

    polar *= _MainTex_ST.xy;
    polar += _ScrollSpeeds.xy * _Time.x;

    fixed4 col = tex2D(_MainTex, polar);
    // Tint the colour by our second texture.
    col *= tex2D(_TintTex, tintUVs);

    UNITY_APPLY_FOG(i.fogCoord, col);
    return col;
}

```

And now our giraffe gets really trippy:

With a slightly more artistic selection of textures and scrolling rates, this can create an effect quite similar to the one shown in the question.

---

You may notice two small artifacts with the version I've shown above:

* The faces near the center of the circle get a stretched/skinny/pointy, then as they move toward the outside they get squashed/wide.

This distortion happens because we have a fixed number of faces around the perimeter, but the circumference they're spanning gets wider as the radius increases, while their height stays the same.

We can fix this by remapping the vertical component of the texture sample to follow a logarithmic curve, so repeats of the texture are further apart as the radius increases, and closer together toward the center. (In fact,this gives us an infinite regress of smaller and smaller giraffes...)
* There's a row of one or two blurry pixels along the middle-left of the quad.

This happens because the GPU looks at two adjacent texture sample coordinates to figure out what filtering to use. When the samples are close together, it figures the texture is being displayed large/close and shows the most detailed mip level. When the samples are far apart, it guesses we must be showing the texture at a tiny zoom or far away, and it samples from a smaller/blurrier mipmap to ensure we don't get sparkly aliasing artifacts.

The trouble is here, we're at the wrap-around point in polar coordinates, from -180 to 180 degrees. So we're actually sampling from very similar points in our repeating texture space, even if their numeric coordinates make them look like they're far apart. So we can provide our own sampling gradient vectors to correct for this.

Here's a version with these corrections:

```
fixed4 frag(v2f i) : SV_Target
{
    float2 polar = float2(
           atan2(i.uv.y, i.uv.x) / (2.0f * 3.141592653589f), // angle
           log(dot(i.uv, i.uv)) * 0.5f                       // log-radius
        );

    // Check how much our texture sampling point changes between
    // neighbouring pixels to the sides (ddx) and above/below (ddy)
    float4 gradient = float4(ddx(polar), ddy(polar));

    // If our angle wraps around between adjacent samples,
    // discard one full rotation from its value and keep the fraction.
    gradient.xz = frac(gradient.xz + 1.5f) - 0.5f;

    // Copy the polar coordinates before we scale & shift them,
    // so we can scale & shift the tint texture independently.
    float2 tintUVs = polar * _TintTex_ST.xy;
    tintUVs += _ScrollSpeeds.zw * _Time.x;

    polar *= _MainTex_ST.xy;
    polar += _ScrollSpeeds.xy * _Time.x;

    // Sample with our custom gradients.
    fixed4 col = tex2Dgrad(_MainTex, polar,
                           _MainTex_ST.xy * gradient.xy,
                           _MainTex_ST.xy * gradient.zw
                         );

    // Since our tint texture has its own scale,
    // its gradients also need to be scaled to match.
    col *= tex2Dgrad(_TintTex, tintUVs,
                          _TintTex_ST.xy * gradient.xy,
                          _TintTex_ST.xy * gradient.zw
                         );

    UNITY_APPLY_FOG(i.fogCoord, col);
    return col;
}

```

---
Tags: unity, shaders, textures, animation
---


# Question
Title: Sprite Animation of Tank Turning - how many items in sheet
I have a question about this tank you can see below. It's from a game called Command and Conquer from the 90s. My question is, how is something like this animated as the tank is turning? Did the game designers draw the tank at a basic position and then draw it again +1 degree and then draw again +2 degrees, etc. until they get all the way around?

http://cnc.wikia.com/wiki/Mammoth\_tank\_(Tiberian\_Dawn)?file=CNCTD\_Mammoth\_Tank\_Ingame.png

# Answer
> 1 votes
I have no concrete evidence that the game in question uses 2D graphics, other than my intuition. I played some Command and Conquer in the past and I think they are 2D, for how they look and for the age of the game. If they hand draw the sprites or if they used renders from a 3D editor like 3D Studio is another topic.

What libraries the game installed/required, like DirectDraw, Direct3D, etc, I don't remember. So I cannot guess based on that.

OK, now for the problem at hand. If I have to use sprite sheets for whatever reason: I don't want to mess with 3D data, target hardware doesn't handle 3D very well, etc. I would design the tanks in at least two parts. This means that the body of the tank (lower part) will be rendered/drawn separated from the cannon (upper part).

Why this design? Because I can rotate the cannon independently of the body without having to save an entire sprite for each possible combination of body/cannon positions.

Also I would use Blender (place your 3D editor/modeler of choice here) to design the tank parts and then produce renders of the different positions of the parts and combine all of them in a single sprite-sheet.

So, with this design, you have the freedom of moving the parts of the tank individually without having a super large sprite-sheet at the negligible cost of multiplying the calls needed to render a single tank by a factor of 2 (there are worse things you can do to hurt the performance of your game).

For example, if we want, as many old RTS games, for each thank, the positions: left, up-left, up, up-right, right, down-right, down, down-left (turns of 45 degrees). We only need 8 renders of the body and other 8 of the cannon. If we want turns of 22.5 degrees, to have more appealing visuals, we need 16 renders of each part, for a 32 in total, so we end with a 32 sprite long sprite-sheet.

If we were to render all the tank as a single sprite, and we still want to be able to turn the cannon without turning the whole tank, then we need a render of the tank for each possible combination of body/cannon positions. So, in the case of the 22.5 degrees, the following formula should tell us the required renders: (360 / 22.5) ^ 2 = 256

The reasoning begin that formula is, that for a full 360 turn in steps of 22.5, we need 16 renders per part, but if we were to render the full tank retaining the individuality of the cannon, then we need 16 renders per body position (because each body position will have 16 versions, each one with a different cannon position).

Note that, some game out there, for whatever reason, may opt for using a 256 sprite long sprite-sheet. Maybe because they don't like the increase in code complexity required to render each part in the correct place (probably not so complex) or they just don't care because the tanks graphics are low-res and the saving in storage/RAM doesn't convince them.

I don't have concrete evidence that the game in question do the rendering of tank parts separate, but I guess It does.

Also note that the game you put as example doesn't allow +1 or +2 degrees of rotation. RTS games of the time had only a very limited set of positions per unit, never +1 degree, is more in the order of +22.5 or +45. Even in the case of hand drawing the sprites with an artistic sense of isometric perspective, they still only have to draw 8 or 16 positions. The limit is imposed by both: artist time and hardware capabilities.

For example, Age of Empires 2 sprite-sheet example: http://vignette1.wikia.nocookie.net/ageofempires/images/a/ad/Hussar.png/revision/latest?cb=20160126073526

And another evidence: I still remember that when you clicked on an unit in the map editor of AOE 2, you see an octagon at the bottom of the unit. If you have this game around don't try this in an actual match because during matches the game shows an isometric rectangle, the octagon is shown in the map editor when placing units. This gives us the clue that the units has 8 possible directions. I'm sure they rendered more than 8 sprites per unit as the units moves in place and have fighting, moving and standing animations, but that's another topic.

---
Tags: sprites
---


title: How to make a long highway in unity?

text:
# Question
Title: How to make a long highway in unity?
I'm planning to make a long highway for a Racer game. What is the best way to do it ?

Do you make it in a single scene which I think is difficult to manage ? Or do you make multiple scenes or anything else ?

# Answer
> 1 votes
You will probably want to chunk up your large level into multiple smaller levels. Then, depending at what point on the track the player is on, load and unload sub-levels as needed to provide the illusion of one larger level. This essentially involves using the Unity Scene as a 2nd level prefab.

You can load a scene into your current scene with SceneManager.LoadLevel() and SceneManager.LoadLevelAsync() but making sure to pass the LoadSceneMode.Additive parameter.

Here are some links to those methods on the Unity docs:

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html

Here's a slightly out of date answer on the Unity stack exchange. Same principle applies but Application.LoadLevelAddative was just made obsolete.

http://answers.unity3d.com/questions/223782/prefab-of-a-whole-scene.html

# Answer
> 2 votes
Beside an applicable but tough solution of Honeybunch, I think that your question can be answer through developing an infinite road dyanmically which can be consider as endless runner type of game. Please have a look

1. 3D Infinite Runner Game Tutorial
2. Lets Make a Game: Infinite Runner
3. Creating an infinite 3D runner game in Unity (like Temple Run, Subway Surfers)
4. Your Own Subway Surfer/Temple Run Like Game

---
Tags: unity
---


title: Flipping Textures in Modern OpenGL

text:
# Question
Title: Flipping Textures in Modern OpenGL
How do I flip a texture in modern OpenGL (3.1+)?

This is the unflipped render, keep in mind it is drawn with 8x8 tiles from a texture atlas, so I edited green squares below him into the image to represent it. Rendered without horizontal flip:

I have tried doing `1-texCoord.x` in my vec2 texCoord in my vertex shader. It gave me... this result:

This is how texture atlas is laid out, if it matters:

Attempting other methods such as inverting texture coordinates of the VBO gave me similarly garbled results. What should I actually be *doing*, to flip the texture, or more accurately each individual tile? I know I would also have to change each tile's coordinates, but that's for after.

# Answer
> 1 votes
If your texture coords normally go from `x0` to `x1` then any given coordinate `x` between those values can be flipped by doing this:

```
flippedX = x0 + (x1 - x);

```

# Answer
> 1 votes
In modern OpenGL and for your specific use case - equally sized tiles in a texture atlas - you have the option of not actually using a texture atlas at all.

Instead you would use a texture array, meaning that your texcoords for each tile are in the 0..1 range and flipping becomes trivial. You also gain the advantages of having wrap modes, clamp modes and mipmapping work as expected.

---
Tags: opengl, c++, data-structure, color, palette
---


# Question
Title: Best way to add and remove quads in a VBO?
What's the best way to handle adding and removing 2D sprites (quads) in a VBO?

I am working on a mobile board game and sometimes game pieces (represented by quads graphically) need to be added to or removed from the screen. Currently, I store all of my quad vertices in an array. When I need to add new quads to the screen, I append this list with the new vertices. However, removing quads is more cumbersome. I track the positions of each quad in the VBO array with a dictionary, and when I comes time to remove it, I remove that block of four vertices from the array. I then have to update the values stored inside the dictionary since the VBO array has been resized.

I am not satisfied with this solution, and I feel like there could be a better way to achieve what I want. I couldn't find any related questions about storing 2D sprites which need to be added or removed during runtime like this. Since the game is really simple graphically, I am thinking it may be easiest to make a draw call per sprite. I can't use instancing since I am restricted to OpenGL ES 2.

# Answer
You don't need a dictionary for this, just use an infinite array (c++ - vector, java - arraylist, c# - list) and store an id in the order they can be found in the vbo. If you want to remove one of them, find the location of this id, multiply it with the amount of vertices per quad, remove the quad and shift everything back 1 (a lot easier than shifting a dictionary)

If you only have quads, then storing one for each piece is unnecessary.

You should only put the data for 1 quad in the vbo, then when you need to render the scene you should bind the vbos and load them in the shader at the beginning of the rendering, then when you want to render one you just liad the necessary uniforms and call the render function.

If you want to keep the current approach with all the quads in the vbo you don't need to remove any of them from the array, just put it somewhere far away where it can't be seen.
> 2 votes

---
Tags: opengl-es, opengl-es2, data-structure, vbo, memory-efficiency
---


# Question
Title: Setting time for a particular action to be happened-LibGdx
In my LibGdx game,enemies are coming in to the screen one by one.

I want to make enemeies appear at a particular time after the game starts.

How can I do it efficiently?

# Answer
I'll do it this way

In your game class

```
float time = 0; // This will contain the time

```

In your game loop

```
time += Gdx.graphics.getDeltaTime(); // This will add to your time variable the time between two frames

```

And something like this when you want to do something

```
if (time > 5) // If 5s happened
{
    // Make ennemy appear
}

```

This would do the trick ! Simply put time to 0 again to restart the timer.

```
time -= 5; // Restart the timer by substract of elapsed time

```
> 3 votes

# Answer
you could use delta time

for example :

```
private final static float TIME_OUT = 5;
private float time = 0;

private update(){
     time += Gdx.graphics.getDeltaTime();
     if (time > TIME_OUT){
          attack();
          time -= TIME_OUT; // or set to 0 to repeat the process
     }
}

```
> 2 votes

---
Tags: libgdx
---


# Question
Title: Avoid if statements in DirectX 10 shaders?
I have heard that if statements should be avoid in shaders, because both parts of the statements will be execute, and than the wrong will be dropped (which harms the performance).

It's still a problem in DirectX 10? Somebody told me, that in it only the right branch will be execute.

For the illustration I have the code:

```
float y1 = 5; float y2 = 6; float b1 = 2; float b2 = 3;

if(x>0.5){
    x = 10 * y1 + b1;
}else{
    x = 10 * y2 + b2;
}

```

**Is there an other way to make it faster?**

If so, how do it?

Both branches looks similar, the only difference is the values of "constants" (`y1, y2, b1, b2` are the same for all pixels in Pixel Shader).

# Answer
> 17 votes
Many rules for micro-optimising shaders are the same as for traditional CPUs with vector extensions. Here are a few hints:

* there are built-in test functions (`test`, `lerp`/`mix`)
* adding two vectors has the same cost as adding two floats
* swizzling is free

It is true that branches are cheaper on modern hardware than they used to be, but it is still better to avoid them if possible. By using swizzling and test functions you can rewrite your shader without tests:

```
/* y1, y2, b1, b2 */
float4 constants = float4(5, 6, 2, 3);

float2 tmp = 10 * constants.xy + constants.zw;
x = lerp(tmp[1], tmp[0], step(x, 0.5));

```

Using `step` and `lerp` is a very common idiom for choosing between two values.

# Answer
> 6 votes
Generally it's OK. Shaders will execute in groups of vertices or pixels (different vendors have different terminology for these so I'm keeping away from that) and if all vertices or pixels in a group take the same path then branching cost is negligible.

You also need to trust the shader compiler. The HLSL code you write should not be seen as a direct representation of the bytecode or even assembly that it will compile down to, and the compiler is perfectly free to convert it to something that's equivalent but avoids the branch (e.g. a lerp may sometimes be a preferred conversion). On the other hand, if the compiler determines that performing a branch is actually the faster path, it will compile it down to a branch. Viewing the generated assembly in PIX or a similar tool can be very helpful here.

Finally, the old wisdom still holds here - profile it, determine if it's actually a performance problem for you, and tackle it then, not before. Assuming that something *may* be a performance problem and acting according to that assumption will only incur a huge risk of bigger problems later on.

# Answer
> 4 votes
Quote from the link/article posted by Robert Rouhani:

> "Condition codes (predication) are used in older architectures to emulate true branching. If-then statements compiled to these architectures must evaluate both taken and not taken branch instructions on all fragments. The branch condition is evaluated and a condition code is set. The instructions in each part of the branch must check the value of the condition code before writing their results to registers. As a result, only instructions in taken branches write their output. Thus, in these architectures all branches cost as much as both parts of the branch, plus the cost of evaluating the branch condition. Branching should be used sparingly on such architectures. NVIDIA GeForce FX Series GPUs use condition-code branch emulation in their fragment processors."

As mh01 suggested ("Viewing the generated assembly in PIX or a similar tool can be very helpful here."), you should use a compiler tool to examine the output. In my experience, nVidia's Cg tool (Cg is still widely used today because of its cross platform capabilities) gave a perfect illustration of the behavior mentioned in the GPU gems *condition codes (predication)* paragraph. Thus, regardless of the trigger value, both branches were evaluated on a per fragment basis, and only at the end, the right one was placed in the output registry. Nevertheless, the computation time was wasted. Back then, I thought that branching will help performance, especially because *all* fragments in that shader relied on an uniform value to decide on the right branch - that did not happen as intended. So, a major caveat here ( e.g. avoid ubershaders - possibly the greatest source of branching hell).

# Answer
> 2 votes
If you're not already having performance issues, this is fine. The cost for comparison against a constant is still **extremely** cheap. Here's a good read about GPU branching: http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter34.html

Regardless, here's a snippet of code that's going to preform much worse than the if statement (and is far less readable/maintainable), but still gets rid of it:

```
int fx = floor(x);
int y = (fx * y2) + ((1- fx) * y1);
int b = (fx * b2) + ((1 -fx) * b1);

x = 10 * y + b;

```

Note that I'm making the assumption that x is limited to the range `[0, 1]`. This won't work if x \>= 2 or x \< 0.

What that snipped does is convert x to either `0` or `1` and multiply the wrong one by 0 and the other one by 1.

# Answer
> 2 votes
There are multiple instruction able to do conditions without branching;

```
vec4 when_eq(vec4 x, vec4 y) {
  return 1.0 - abs(sign(x - y));
}

vec4 when_neq(vec4 x, vec4 y) {
  return abs(sign(x - y));
}

vec4 when_gt(vec4 x, vec4 y) {
  return max(sign(x - y), 0.0);
}

vec4 when_lt(vec4 x, vec4 y) {
  return max(sign(y - x), 0.0);
}

vec4 when_ge(vec4 x, vec4 y) {
  return 1.0 - when_lt(x, y);
}

vec4 when_le(vec4 x, vec4 y) {
  return 1.0 - when_gt(x, y);
}

```

Plus some logical operators;

```
vec4 and(vec4 a, vec4 b) {
  return a * b;
}

vec4 or(vec4 a, vec4 b) {
  return min(a + b, 1.0);
}

vec4 xor(vec4 a, vec4 b) {
  return (a + b) % 2.0;
}

vec4 not(vec4 a) {
  return 1.0 - a;
}

```

source : http://theorangeduck.com/page/avoiding-shader-conditionals

---
Tags: c++, directx, shaders, hlsl, directx10
---


# Question
Title: How could I implement origin re-base on my large world server?
I wish to make a game set in space where the world is empty space, mostly empty but *continuous* (i.e. no sectors with jump gates separating them) and extends to long distances like a few hundred or a thousand kilometres, where players move around at realistic speeds of spacecrafts. I'm thinking of something like *"Star Citizen"*.

One approach I thought of was scaling down everything and moving slowly to effectively make an illusion of large world but this approach tends to suffer with problems in precision of calculations, specifically floating point calculations. Then I found out about the concept of origin re-basing.

I'm having trouble understanding how I could implement that on the server: clients can have objects relative to their origin but the server needs to have the entire world in the same co-ordinate system since there is only one world on the server in which everything interacts.

How could I manage both client and server coordinates systems on the server for my *very large* space environment in a realistic way in the perspective of the player?

# Answer
> 4 votes
> One approach I thought of was scaling down everything and moving slowly to effectively make an illusion of large world.

As mentioned above, reducing scale doesn't actually increase the usable play space, because the precision limits of a floating point number scale with the magnitude of that number. (So, reducing the size of your ships by a factor of 1024 reduces the error in their positions by only that same factor of 1024, meaning that relative to the game content the errors are still the same size)

So, how would we implement a local origin system for a large continuous world?

1. **Divide the world into zones.**

* You can do this based on a **regular grid**, where each zone is identified by an integer grid coordinate tuple. You can find the offset between two nodes implicitly, by taking the difference in their coordinate values multiplied by the grid spacing.

    (eg. the 1024 km cube of space in the "middle" of your world is zone(0, 0, 0), beside it there's another 1024 km cube called zone(1, 0, 0)...)
    * Or you can do this based on **local landmarks**, where each zone is a node in a graph. Nodes can either have explicit positions in some global coordinate system (either using higher precision or rounding to representable coordinates), or you can store just the offset between two neighbouring nodes in the edges of the graph.

    (eg. you might have a zone for each space station, planet, or interesting space feature/anomaly - locations where you expect gameplay interactions will usually gather. You might need to scatter empty zones in between to maintain even coverage. Instead of a grid, your zone boundaries form a collection of Voronoi cells)
2. **Treat all "Positions" in your game as tuples**, combining:

* a zone ID, and...
    * a local offset relative to that zone's centre.

As a dynamic object travels outside its current zone, it can update its position to one relative to the new zone it enters, like so:

`localOffset += newZone.GetOffsetFromZone(currentZone);
currentZone = newZone;`

By keeping your zone spacing small, you can ensure you retain the desired level of precision throughout these operations. You can consult the table in this answer to find at what magnitude of number you hit a particular error threshold that's significant for your game, and then back up an order of magnitude or two for safety.
3. **For a client, convert all visible entities to your local zone.** (Simplest Case)

That keeps one coordinate system for simplicity, while still guaranteeing the desired precision for everything near the player - whether they're natively in the player's own zone or one immediately adjacent. Objects in more distant zones will have less accuracy on the client machine, but their sheer distance should make this unnoticeable.

When the client needs to convert their position to a new zone, they apply the new offset to everything at once, so from the player's eye view nothing happened at all - they're just sailing continuously through space.

If you have a mechanic that involves fine-precision sniping across multi-zone distances then you may need to take a somewhat more robust approach...
4. **For the server, sort dynamic entities into "islands"** (General Case)

This is a common step in many physics engines to limit the complexity of collision checking & constraint solving. You perform a crude range or bounds check to determine which objects are close enough together to potentially influence each other, grouping them into clusters you can solve in isolation.

Once you have your islands, you can update them accordingly:

* If an island is contained entirely within a single zone, all of its interactions can be resolved in that zone's local coordinate system.
    * If an island spans multiple zones, then they need to agree on a *lingua franca* first. Convert their positions into a common zone (either pick the one closest to the center of the island, or invent a one-off zone for the purpose), then resolve the interactions in this space.

This should handle cases where your world is sparse, so you never have a single object or chain of mutually-interacting objects spanning a more than a small cluster of adjacent zones. This is pretty typical for space. Megastructures like the Ringworld would of course require somewhat exotic treatment. ;)

Each island can potentially be farmed-out as a separate work unit for scaling across multiple threads / multiple servers. The island sorting itself can be handled incrementally, as very few objects will need to change islands in any given tick (especially if your island assignment is conservative or includes some hysteresis, so an object skimming the interaction range of another doesn't get added & removed repeatedly)

---
Tags: architecture, client-server
---


# Question
Title: How can I make a spaceship auto level while in orbit?
I’m trying to make a ship auto level so that the belly of the ship stays facing the planet. I found the answer in 2.5D\*, but I can’t get it to work in 3D.

```
//world rotation * up
Vector3f spatialY = control.getPhsicsRotation().mult(Vector3f.UNIT_Y);
Vector3f cross = spatialY.crossLocal(Vector3f.UNIT_Y).normalizeLocal();

```

*<sub> Stuck on the ground with no roll (like Doom, COD, etc.).</sub>

---

I’m trying to find a rotation perpendicular to the center/surface of the planet. The math is at the edge of my understanding. I found a great link on wiki, but I don’t understand the formulas.

I can not tell if I am looking for

* The final vector to adjust, over time,
* The cross-product difference between what I have and what I want,
* A ‘normal’ perpendicular to a plane,
* A normal to the tangent plane,

Or if I am trying to align the x and z angles to the plane. How do I get the plane?

---

The next step will be to rotate the ship on the Y (up) axis and face prograde – with orbit, retrograde – opposite orbit, orbit +/- to align the plane with another orbiting body.

```
Vector3f startVector;
Vector3f currentVector;
Vector3f endVector;
Vector3f upVector;
Vector3f tempVector;
Vector3f spatialY;
Vector3f cross;
Vector3f v;
public void autoLevel(String action, boolean isPressed){
    autoLevel = (autoLevel == false);
    if (autoLevel){
        upVector = Vector3f.UNIT_Y;
        //start
        float[] rad = new float[3];
        spatial.getWorldRotation().toAngles(rad);//local
        //start vector
        startVector = new Vector3f(rad[0], rad[1], rad[2]);
        //current vector
        currentVector = new Vector3f(rad[0], rad[1], rad[2]);
        //end vector
        endVector = new Vector3f(rad[0], rad[1], rad[2]);
        //test
        spatialY = endVector.mult(Vector3f.UNIT_Y);
        cross = spatialY.cross(Vector3f.UNIT_Y);
    }
}

private void doAutoLevel(float tpf){
    //current
    float[] rad = new float[3];
    spatial.getWorldRotation().toAngles(rad);
    currentVector = new Vector3f(rad[0], rad[1], rad[2]);
    //if cross it the difference between my current and end rotations...
    massControl.rotate(cross);
    autoLevel = false;//shut off for testing
    if (true) return;
    //Or...
    if (currentVector.x < endVector.x - 0.01f)
        pitchDown("PitchUp", true);
    else if (currentVector.x > endVector.x + 0.01f)
        pitchUp("PitchDown", true);
    else{
        currentVector.x = endVector.x;
        pitchDown("PitchDown", false);
        pitchUp("PitchUp", false);
        massControl.setSpin(0, 0f);
    }

    if (currentVector.y < endVector.y - 0.01f)
        yawRight("YawRight", true);
    else if (currentVector.y > endVector.y + 0.01f)
        yawLeft("YawLeft", true);
    else{
        massControl.setSpin(1, 0f);
        yawLeft("YawLeft", false);
        yawRight("YawRight", false);
        currentVector.y = endVector.y;
    }
    //
    if (currentVector.z < endVector.z - 0.01f)
        rollLeft("RollLeft", true);
    else if (currentVector.z > endVector.z + 0.01f)
        rollRight("RollRight", true);
    else{
        massControl.setSpin(2, 0f);
        rollLeft("RollLeft", false);
        rollRight("RollRight", false);
        currentVector.z = endVector.z;
    }
}//doAutoLevel

//And the gravity routine that I found after searching for years...

private synchronized void doGravity(){
    //delay -= 1.0f;
    //if (delay > 0) return;
    //delay = app.getTimer().getFrameRate();
    //ArrayList<Node> bodyList = getBodyList();
    List list = getMasses(rootNode);
    for (int a = 0;a < list.size();a++){
        Node p1 = (Node)list.get(a);
        MassControl massControl = p1.getControl(MassControl.class);
        float m1 = massControl.getMass();
        //System.out.println("EnvironmentalControl.doGravity()" + ", processing p1=" + p1.getName());
        Vector3f acc = new Vector3f();
        if (list.size() > 1){
            //if (p.getName().equals("Moon")) System.out.print("acc=");
            for (int b = 0;b < list.size();b++){
                Node p2 = (Node)list.get(b);
                if (p1.equals(p2)) continue;
                Vector3f unit = new Vector3f(p2.getWorldTranslation().subtract(p1.getWorldTranslation()));
                float magnitude = (float)Math.sqrt((unit.x * unit.x) + (unit.y * unit.y) + (unit.z * unit.z));
                float m2 = p2.getControl(MassControl.class).getMass();
                //if (p1.getName().equals("Ship 01") && p2.getName().equals("Earth") || p2.getName().equals("Ship 01") && p1.getName().equals("Earth"))
                    //System.out.println("OrbitMaker.doGravity(" + p1.getName() + ")(" + p2.getName() + ") m1=" + m1 + ", m2=" + m2 + ", unit=" + unit + ", magnitude=" + magnitude);//do gravity
                if (magnitude != 0.0f && (m1 * m2 != 0.0)){
                    float factor = (G * (
                                    (m1 * m2) / (magnitude * magnitude * magnitude)
                                    )) / m1;
                    unit = unit.mult(factor);
                    //if (p1.getName().equals("Ship 01")) System.out.println("OrbitMaker.doGravity(" + p1.getName() + ")(" + p2.getName() + "): factor=" + factor + ", unit=" + unit + ", acc=" + acc);
                }
                else{
                    unit.set(0.0f, 0.0f, 0.0f);
                }
                acc = acc.add(unit.clone());//.mult(tpf));
                //collision check
                if (areClose(p1, p2)){
                    collisionQueue.add(new CollisionGroup(p1, p2));
                }
            }
        }

        //if (p.getName().equals("Moon")) System.out.println(acc + ", ");
        //Vector3f velocity = p.getControl(MassControl.class).getVelocity();
        //if (p.getName().equals("Moon")) System.out.println("OrbitMaker.doGravity(" + p.getName() + "): acc=" + acc);
        massControl.addToVelocity(acc);
    }
    //System.out.println();
}//doGravity

```

# Answer
> 1 votes
Here is a simple way to keep the belly of the ship facing the planet as the ship orbits. On real orbiting spaceships this does not happen but I can see where it would look good on a video game.

The only thing you have to do outside this method is increment the ship's orbital position by whatever physics approximation method you what (like your `doGravity()`). If you want to steer the ship to give it a new orbital direction, you could squeeze that in after the 2nd line in the method.

This method assumes you've already incremented the ship's position from last frame and this is passed as `newShipPosition`. It also assumes you saved the result from last frame and this is passed as `lastFrameMatrix`.

```
Matrix GetNewWorldMatrix(Matrix lastFrameMatrix, Vector3 newShipPosition, Vector3 planetCenter)
{
   Matrix result = Matrix.Identity;

   Vector3 directionShipIsTraveling = lasteFrameMatrix.Forward;
   Vector3 newMatrixUp = newShipPosition - planetCenter;
   Vector3 newMatrixRight = Vector3.Cross(directionShipIsTraveling, newMatrixUp);
   newMatrixUp.Normalize();
   newMatrixRight.Normalize();
   Vector3 newMatrixForward = Vector3.Cross(newMatrixUp, newMatrixRight);

   result.Up = newMatrixUp;
   result.Right = newMatrixRight;
   result.Forward = newMatrixForward;
   result.Translation = newShipPosition;

   return result;

}

```

# Answer
> 0 votes
final code

```
public void autoLevel(){
    currentMatrix = getNewWorldMatrix(currentMatrix, spatial.getWorldTranslation(), parent.getWorldTranslation());
}

//static final int LR = 0;//right/left
//static final int UD = 1;//up/down
//static final int FR = 2;//front/back

public Matrix3f getNewWorldMatrix(Matrix3f oldMatrix, Vector3f currentTranslation, Vector3f parentTranslation){
    Matrix3f result = new Matrix3f();
    //lastFrameMatrix = spatial.getLocalRotation().toRotationMatrix();
    Vector3f walkDirection = oldMatrix.getColumn(FR);
    Vector3f newUp = currentTranslation.subtract(parentTranslation).normalize();
    Vector3f newRight = walkDirection.cross(newUp).normalize();
    Vector3f newForward = newUp.cross(newRight).normalize();
    result.setColumn(LR, newRight);        //LR = 0
    result.setColumn(UD, newUp);        //UD = 1
    result.setColumn(FR, newForward);    //FR = 2
    result.normalizeLocal();
    return result;
}

```

---
Tags: 3d, rotation, orbit
---


# Question
Title: C++ Assimp - Models incorretly drawn/loaded
I've followed a tutorial about using Assimp to load models, but the loaded models are incorrectly drawn:

These should be a spheres

I've checked my code multiple times but I can't seem to find what I did wrong could someone help me with this problem?

Code: https://github.com/DaanSander/Polygon-Engine/tree/master/Engine/src/geometry

Mesh.h

```
#pragma once

#include <string>
#include <vector>
#include <sstream>
#include <GL\glew.h>
#include <assimp\scene.h>
#include "../math/Math.h"
#include "../graphics/Shader.h"

namespace engine { namespace geometry {

struct Vertex {
    math::Vector3f position, normal;
    math::Vector2f uvCoord;
};

struct Texture {
    GLuint id;
    std::string type;
    aiString path;
};

class Mesh {

    GLuint VAO, VBO, EBO;

public:
    std::vector<Vertex*> vertices;
    std::vector<GLuint>  indices;
    std::vector<Texture> textures;

    Mesh(std::vector<Vertex*> vertices, std::vector<GLuint> indices, std::vector<Texture> textures);

    ~Mesh();

    void setupMesh();

    void setupTextures(graphics::Shader* shader);

    GLsizei getVertexCount() { return vertices.size(); };

    inline GLuint getVaoID() { return VAO; }

    inline GLuint getEboID() { return EBO; }
};

}}

```

Mesh.cpp

```
#include "Mesh.h"

namespace engine { namespace geometry {

    Mesh::Mesh(std::vector<Vertex*> vertices, std::vector<GLuint> indices,     std::vector<Texture> textures) {
        this->vertices = vertices;
        this->indices = indices;
        this->textures = textures;

        setupMesh();
    }

    Mesh::~Mesh() {
        glDeleteBuffers(1, &VBO);
        glDeleteBuffers(1, &EBO);
        glDeleteVertexArrays(1, &VAO);
    }

    void Mesh::setupMesh() {
        glGenVertexArrays(1, &VAO);
        glGenBuffers(1, &VBO);
        glGenBuffers(1, &EBO);

        glBindVertexArray(VAO);

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

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * this->indices.size(), &this->indices[0], GL_STATIC_DRAW);

        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) 0);

        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal));

        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, uvCoord));

        glBindVertexArray(0);
    }

    void Mesh::setupTextures(graphics::Shader* shader) {
        using namespace std;
        using namespace graphics;
        GLuint diffuseTexureNr = 1;
        GLuint specularTextureNr = 1;
        for (GLuint i = 0; i < textures.size(); i++) {
            glActiveTexture(GL_TEXTURE0 + i);

            stringstream ss;
            string number;
            string name = this->textures[i].type;
            if (name == "texture_diffuse")
                ss << diffuseTexureNr++;
            else if (name == "texture_specular")
                ss << specularTextureNr;

            number = ss.str();

            glUniform1f(shader->getUniformLocation((char*) ("material." + name + number).c_str()), i);
            glBindTexture(GL_TEXTURE_2D, this->textures[i].id);
        }

        glActiveTexture(GL_TEXTURE0);
    }
}}

```

Model.h

```
#pragma once

#include <string>
#include <vector>
#include <assimp\Importer.hpp>
#include <assimp\scene.h>
#include <assimp\postprocess.h>

#include "Mesh.h"
#include "..\graphics\Texture.h"

namespace engine { namespace geometry {

class Model {

    std::vector<Mesh> meshes;
    std::string directory;

public:
    Model(GLchar* path);

    inline std::vector<Mesh> getMeshes() { return meshes; }
private:
    void loadModel(std::string path);

    void processNode(aiNode* node, const aiScene* scene);

    Mesh processMesh(aiMesh* mesh, const aiScene* scene);

    std::vector<Texture> loadMaterialTexture(aiMaterial* material, aiTextureType type, std::string typeName);
};

}}

```

Model.cpp

```
#include "Model.h"

namespace engine {
namespace geometry {

    Model::Model(GLchar* path) {
        this->loadModel(path);
    }

    void Model::loadModel(std::string path) {
        Assimp::Importer importer;
        const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);

        if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
            std::cout << "An error ocurred while loading model at path: " << path << " log: " << importer.GetErrorString() << std::endl;
            return;
        }
        this->directory = path.substr(0, path.find_last_of("/"));

        this->processNode(scene->mRootNode, scene);
    }

    void Model::processNode(aiNode* node, const aiScene* scene) {
        for (int i = 0; i < node->mNumMeshes; i++) {
            aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
            if (mesh == nullptr) {
                std::cout << "MESH IS NULL" << std::endl;
                system("pause");
            }
            Mesh gMesh = this->processMesh(mesh, scene);
            meshes.push_back(gMesh);
        }

        for (int i = 0; i < node->mNumChildren; i++) {
            if (node->mChildren[i] == nullptr) {
                std::cout << "NODE IS NULL" << std::endl;
                system("pause");
            }
            processNode(node->mChildren[i], scene);
        }
    }

    Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene) {
        using namespace math;
        using namespace std;
        vector<Vertex*> vertices;
        vector<GLuint> indices;
        vector<Texture> textures;

        for (int i = 0; i < mesh->mNumVertices; i++) {
            Vertex vertex;

            Vector3f vector;
            vector.x = mesh->mVertices[i].x;
            vector.y = mesh->mVertices[i].y;
            vector.z = mesh->mVertices[i].z;

            vertex.position = vector;

            Vector3f normal;
            normal.x = mesh->mNormals[i].x;
            normal.y = mesh->mNormals[i].y;
            normal.z = mesh->mNormals[i].z;

            vertex.normal = normal;

            if (mesh->mTextureCoords[0]) {
                Vector2f uvCoord;
                uvCoord.x = mesh->mTextureCoords[0][i].x;
                uvCoord.y = mesh->mTextureCoords[0][i].y;

                vertex.uvCoord = uvCoord;
            } else
                vertex.uvCoord = Vector2f();

            vertices.push_back(&vertex);
        }

        for (int f = 0; f < mesh->mNumFaces; f++) {
            aiFace face = mesh->mFaces[f];
            for (int i = 0; i < face.mNumIndices; i++)
                indices.push_back(face.mIndices[i]);

            for (GLuint i = 0; i < mesh->mNumFaces; i++)
            {
                aiFace face = mesh->mFaces[i];
                for (GLuint j = 0; j < face.mNumIndices; j++)
                    indices.push_back(face.mIndices[j]);
            }
        }

        if (mesh->mMaterialIndex >= 0) {
            aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];

            vector<Texture> diffuseMaps = this->loadMaterialTexture(material, aiTextureType_DIFFUSE, "texture_diffuse");
            textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());

            vector<Texture> specularMaps = this->loadMaterialTexture(material, aiTextureType_SPECULAR, "texture_specular");
            textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
        }

        return Mesh(vertices, indices, textures);
    }

    std::vector<Texture> Model::loadMaterialTexture(aiMaterial* material, aiTextureType type, std::string typeName) {
        using namespace std;
        vector<Texture> textures;

        for (GLuint i = 0; i < material->GetTextureCount(type); i++) {
            Texture texture;

            aiString str;
            material->GetTexture(type, i, &str);

            graphics::Texture* gTexture = new graphics::Texture(str.C_Str());

            texture.id = gTexture->getTextureID();
            texture.type = typeName;
            texture.path = str;
            textures.push_back(texture);
        }
        return textures;
    }
}}

```

# Answer
The problem was that I was passing vertices by reference and at the end of the scope it would be deleted.
> 0 votes

---
Tags: opengl, c++, assimp
---


# Question
Title: Reliably synchronising SDL animation with VSYNC in windowed mode
I have an SDL/OpenGL program which creates a rendering context with `PRESENTVSYNC` enabled, then enters an animation loop which calls `SDL_GL_SwapWindow` each time around. On my own machine, the animation works fine at a sensible speed, but on my office machine it runs with no vsync delay at all resulting in the animation running at breakneck speed and tearing all over the frame. Adding a sleep() to the animation loop slows it down sensibly.

I know that I can use `SDL_GL_GetSwapInterval` to see if swapping is being synchronized or not, but is there a way to find out what the actual refresh rate of the screen is in order to know how long or short the sleep should be?

# Answer
You need to use `SDL_GL_SetSwapInterval`. Pass in 1 to enable VSYNC.

`SDL_PRESENT_VSYNC` is a `SDL_Renderer` flag and has no effect on pure OpenGL rendering. It only affects rendering performed using the SDL's rendering module.
> 1 votes

# Answer
You can use `SDL_GetDisplayMode` or `SDL_GetCurrentDisplayMode`, which will copy data into an `SDL_DisplayMode` you pass it, including the screen's refresh rate.

https://wiki.libsdl.org/SDL\_GetDisplayMode
> 0 votes

---
Tags: opengl, windows, sdl2
---


# Question
Title: How do I create a maze without drawing each individual line or using sprites?
I am currently trying to create a maze game by following some online tutorials, and putting my own spin on them. I found a pretty good tutorial at pythonspot.com, but I am not sure what some of the code means, and if I have to use images and sprites to create this maze.

---

The piece that is confusing me is this:

```
class Maze:
    def __init__(self):
       self.M = 10
       self.N = 8
       self.maze = [ 1,1,1,1,1,1,1,1,1,1,
                     1,0,0,0,0,0,0,0,0,1,
                     1,0,0,0,0,0,0,0,0,1,
                     1,0,1,1,1,1,1,1,0,1,
                     1,0,1,0,0,0,0,0,0,1,
                     1,0,1,0,1,1,1,1,0,1,
                     1,0,0,0,0,0,0,0,0,1,
                     1,1,1,1,1,1,1,1,1,1,]

    def draw(self,display_surf,image_surf):
       bx = 0
       by = 0
       for i in range(0,self.M*self.N):
            if self.maze[ bx + (by*self.M) ] == 1:
               display_surf.blit(image_surf,( bx * 44 , by * 44))

           bx = bx + 1
           if bx > self.M-1:
               bx = 0
               by = by + 1

```

---

I know that you can make a maze with `1`s and `0`s to print to the screen, and this is easier for me to make levels with, because I can visualize them in the `1`s and `0`s.

Do I have to use images like the tutorial is (`display_surf.blit(image_surf)`), or can I use `pygame.draw` to create a square for use multiple times as a wall?

I was also wondering what the `self.M`, `self.N`, `bx` and `by` variables do

---

I have tried looking at other mazes, on the Internet, but they tend to either draw all of the walls as lines in individual `draw` statements without using `1`s and `0`s, or they use sprites to create the player and walls. This leads me to believe that I have to use sprites for this drawing method, but I thought I would check here to make sure. I would ask the creator of the tutorial, but I can not create an account for the website, and can not ask questions or leave comments without an account.

# Answer
Yes, you can use simple rectangles instead of the sprites. The tutorial uses sprites to probably make it more interesting.

`self.M` is width of the map and `self.N` is the height. `bx` and `by` are used to loop trough the tiles. Basically it scans trough the tiles from left to right, and when it reaches the right side it goes 1 line lower. It basically works like an old typewriter.

I seriously have no idea why he chose to do this instead if 2 simple nested for loops, or why he uses such obscure variable names in a tutorial.

Your other question is about replacing the current draw function to pygame.draw. Looking at the code it looks like the tiles are 44 pixels wide (I take this opportunity to say that such hardcoded values are bad), so you can just draw a rectangle from `(bx * 44; by * 44)` to `((bx + 1) * 44; ((by + 1) * 44)`. I don't know pygame, but I assume it's something like this:

```
DISPLAY = pygame.display.set_mode((500,400),0,32)
pygame.draw.rect(DISPLAY, (255, 0, 0), (bx * 44, by * 44, 44, 44)

```

Edit: I actually looked it up, this should work.
> 0 votes

---
Tags: python, pygame, maze
---


# Question
Title: Recognize that user has traced a path of vector points with mouse
How can I check if a player has traced a closed vector shape from an arbitrary starting point all the way around to the beginning?

**Setup**

Given are the vector points A through E, which form a closed path. The created shape can be convex or concave and even have sharp elongated corners. P1 is the point where the player decides to start tracing. The point can be anywhere on the path and will be set as soon as the mouse or touch is first close to the path.

**Requirements**

The player starts moving along a visual representation and traces the entire shape until he reaches P1 again. If his mouse path differs too greatly, misses a point or goes outside of a given margin, I want to start over. The player may either have to trace around in the direction from which he first starts without backtracking or just have to fill the entire path even if going back and forth on the path.

How can I approach this problem? Ideally, I would like to implement a vector-math solution. I don't have any pixel data to sample from and it would be rather cumbersome in my real world implementation to generate a suitable image and map world space coordinates to it.

**My Attempt**

* Consider each corner a waypoint with a collision area.
* Track each entered collider and when all were hit, solve.
* While valid colliders are pending, project mouse position onto the closest point on the path.
* If the distance between projected point and mouse is too great, abort.

This approach however doesn't give me perfect results. Firstly, it's not entirely what I want, since in my ideal case the user "draws" or traces the path with the mouse, not just hits the corners. Also, when moving around a sharp corner, the project point will snap from one line segment to the next, giving me ugly visuals, when showing progress.

**Possibly Better Solution**

* As soon as player comes close to path start sampling points from mouse.
* Build up a user drawn vector path every time step or distance step.
* Check if the draw vectors are similar to the given path.
* Problem: user drawn path needs some sort of processing or more complex algorithm until it is comparable to given path.

Thank you for any suggestions! I will post some of my own code as soon as my implementation gives me good results.

# Answer
Maybe something like the p$ algorithm for gesture recognition would serve your purpose? Just remove the normalizing from the gesture comparison so it cares what size your gesture is. http://depts.washington.edu/madlab/proj/dollar/pdollar.html
> 1 votes

---
Tags: unity, algorithm, software-engineering, linear-algebra, path
---


# Question
Title: Direct3D11 HLSL ConstantBuffer Driver Stopped Responding
I have a simple HLSL shader with a few constant buffers, 1 of them holding an array of Light structs which causes my display driver to crash when the array size goes over 3.

Does anybody have an idea what causes my display driver to crash when MAX\_LIGHTS is higher than 3? I don't believe I am exceeding the maximum allowed number of elements right? Which is supposed to be somewhere near 4096 elements). I also don't think I have set up my constant buffer wrong. It is a multiple of 16.

(I have excluded the other 3 constant buffers because these are not so interesting. They only contain world/view/proj matrices.)

I don't mind posting more code, if required.

```
#define MAX_LIGHTS 4 // Black Geometry / Crash
//#define MAX_LIGHTS 3 // Properly Shaded & Textured Geometry / No Crash

struct Light {

    // 16
    float4 lightPosition;

    // 32
    float4 lightDirection;

    // 48
    float4 lightColor;

    // 52
    float lightRange;

    // 56
    float lightIntensity;

    // 60
    float lightIsEnabled;

    // 64
    uint lightType;
};

cbuffer CBLights : register(b3) {
    Light lights[MAX_LIGHTS];
    uint numLights;
    float cbLightsPadding1;
    float cbLightsPadding2;
    float cbLightsPadding3;
};

```

# Answer
The crash was because I did set numLights to an extremely large number by accident. However, I still had a similar problem; all my objects were rendered in black when I used \> 3 lights. The geometry went black when the light array size (in bytes) went over 256.

The black geometry problem was caused by my c++ code. Somewhere I have a GetSize() function which returns the size of a constant buffer parameter as an uint8. So when the parameter size became larger than 256, it returned an incorrect value. Edited to return a uint16 type.
> 1 votes

---
Tags: directx11
---


# Question
Title: How should I prepare for pitching a game to potential sponsors?
We have developed a mobile game, and are preparing ourselves for demo day. We will be presenting our game to potential sponsors, and we are having trouble deciding how to make a quality presentation.

**Specifically, what are the unique challenges and opportunities in pitching a *game*, in contrast with product demos generally?**

Being developers, we are worried we might wrongly focus on elements important to developers, but not to investors. How can we go about identifying them?

For demoing game play, in what situation should we consider switching to a separate app, embedding the game in a slide show, showing canned game footage, or something else?

# Answer
> 11 votes
It sounds like your potential sponsors are similar to publishers in that you’re hoping to get financial backing from them & they’re hoping to get a return on their investment based on how well your game sells.

A good starting resource is Cameron Davis’ Gamasutra piece, How To Pitch Your Project To Publishers (backup link). The entire article is very good, but a bit long, so I’ve attempted to summarize the parts that seem to most directly address your question:

In order of effectiveness, the best ways to convey your game to your audience are:

* interactive gameplay prototype
* non-interactive video presentation of gameplay
* concept art and environment views cut like a trailer
* spoken presentation with supporting materials

Provide a gameplay walkthrough, from the point of view of the player, describing key gameplay mechanics and event sequences they would experience during a particularly interesting moment in the game. Promote the best aspects of the game, elaborate on the unique selling points.

Don't get bogged down in minor details (features that little or nothing to do with the core gameplay mechanics). If it's a minor part of the experience, your publisher will assume you're going to come up with during the course of development anyway.

In response to the article, Carlo Delallana & Jake May, commented that you need to sell your team as well as the game.

Another great resource is Rami Ismail's presentation from GDC Europe 2014, In 3 Sentences or Less: Perfecting Your Pitch (backup link & transcript). Again, the entire thing is great, here’s a summary of the part that seem to address your question.

The important questions are “the what, who and why,” & your goal is to be able to give fast, concise, interesting answers:

Who are you? Introduce yourself to get credentials before your audience if they don’t already know you and what you’ve done. Knowing what the audience expects from you is important. Publishers want to know: have you got a team that is dependable?

Who are they? Know your publisher & what they usually publish; you’ll need to show that your game is good fit with them. How does it fits in their portfolio?

What are you pitching? Maybe not exactly the game, but something that exists through the game, be it emotional, economical, feelings, history, etc. Construct a sentence that isn’t too long that starts with: The name of the thing you’re pitching is, and finish that sentence. If you’re using more than one comma, you’re doing it wrong.

Why are you pitching that? This is all about the value proposition. What are you adding, what are they getting they wouldn’t get otherwise? Publishers want to know what will this collaboration bring to the game, that you wouldn’t have otherwise?

Why are you pitching that to them? What does this publisher offer that others don’t? What would they gain from what you’re pitching? What would this gain cost them?

Structuring your game pitch is mostly about time. When done correctly, the value of information you’re giving needs to outweigh the time they had to listen to you. It basically comes to, don’t waste people’s time.

Finally, focus on the why before focusing in the what. Why will players have a good experience from this game?

---
Tags: marketing, commercial, demo
---


# Question
Title: Is it alright to have hundreds of canvas object on screen?
I am using html5 to build a game and it is based on Canvas not webGL. I am trying to build sprites from canvas object not from images. Because there will be many sprites on the screen and each of them has different size and moves to different direction I would be using many canvas objects. I wonder if it's OK to put so many canvas objects on the browser screen. Will this make the game very slow?

# Answer
> 1 votes
Elements not in tbe DOM don't affect the rendering performance because they aren't used by the DOM renderer. They only take up a bit of memory but until you have couple thousand of them or they each have insane resolutions, then you won't have a problem with this.

# Answer
> 1 votes
Whileit is possible to have hundreds of canvas elements being dynamically resided using CSS, it is not recommended because your code can get very ugly very fast. it is far easier to render sprites on the same canvas if you are building a serious game. If this is just a theoretical question, then yes, expect a severe increase in load time simply because CSS, being a style sheet language, was not built to handle advanced keyframing and animation. Just use one canvas.

# Answer
> 0 votes
Having more than one canvas is a good way of improving performance actually.

And from my tile-world example I had two canvases with one of them being 3840px wide and high. But performance was still good. You can try it out here and/or look at the code on github if you are into that stuff.

If I didn't use two canvases I'd have to redraw a whole 3840px world or you'd have to come up with a method of knowing who's within the player's sight range and only draw them. Doing that again a single canvas is a bad idea, a better idea would be to draw the background/world on one canvas and never touch it again. Then add enemies and the player on their own respective canvases. You can read the full explanation here: Camera movement, Draw grid

Anyway...

You can check out this jsperf, this tutorial on making your own html5 game engine, and this section on canvas performance on html5rocks for more info and proof.

Hope this was helpful! Have a good day :D

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


# Question
Title: Why Won't Image Drawing Work In JavaScript
In my game at the beginning the first thing that you'll see is a campfire with this code:

```
 var campfire = new Image();
   campfire.onload = function () {
      ctx.drawImage(campfire, campfireX, campfireY);
 };
 campfire.src = "Sprites/Campfire.png";

```

However, it doesn't work, I put an

```
alert("All systems a-ok");

```

at the end and i get the alert so i don't understand why it's there. You can find the actual image file here and the full code here. Sorry if I didn't format this well or something, I'm not very good at this =3

This may seem similar to an older question of mine in which I stated how to add a sprite **onto** the canvas, though in this case, I'm asking why the image doesn't **appear** on the canvas at all, even though there's no errors.

# Answer
> 2 votes
You should use this (literally):

```
var campfire = new Image();
campfire.onload = function () {
    ctx.drawImage(this, campfireX, campfireY);
};
campfire.src = "Sprites/Campfire.png";

```

---
Tags: javascript, sprites, coordinates, image
---


title: Javascript Canvas Drawing Efficiency

text:
# Question
Title: Javascript Canvas Drawing Efficiency
I have just recently started some experiments with game development in Javascript/HTML5, and so far it has been going pretty well. I have a simple test scene running with some basic input handling, and a hundred-ish drawImage() calls with a few transforms. This all runs great on Chrome, but unfortunately, it already chugs on Firefox. I am using a very large canvas ( 1920 x 1080 ), but it doesn't seem like I should be hitting my limit already. So on that note, I was hoping to ask a few questions:

1) What exactly is done on the CPU vs. the GPU in terms of canvas and drawImage()? I'm afraid the answer is probably "it depends on the browser", but can anybody give me some rules of thumb? I naively imagined that each drawImage call results in a textured quad on the GPU with the canvas effectively being a render target, but I'm wondering if I'm pretty far off base there...

2) I have seen posts here and there with people saying not to use the translate(), rotate(), scale() functions when drawing on the canvas. Am I adding a lot of overhead just by adding a translate() call, as opposed to passing in the x,y to drawImage()? Some people suggest using "transate3d", etc., which are CSS properties, but I'm not sure how to use them within a scene. Can they be used for animated sprites within a single canvas?

3) I have also seen a lot of posts with people mentioning that pre-building canvases and then re-using them is a lot faster than issuing all the individual draw calls again. I am guessing that my background should definitely be pre-built into a canvas, but how far should I take this? Should I maintain an individual canvas for each sprite, to cache all static image data when not animating?

Thank you much for your advice!

# Answer
If you are redrawing the entire canvas several times a second this can be slow on any browser (had the same problem when testing on the g/f's low spec laptop).

Could you look into only redrawing the areas you need, and therefore reducing the amount of canvas that is redrawn in each frame?

This is how I got the greatest performance increase in my small demo app.
> 2 votes

# Answer
You can check out my answer for this question: Is it alright to have hundreds of canvas object on screen?

Since both questions are performance related.
> -1 votes

---
Tags: javascript, performance, html-canvas
---


title: Unity store data in database

text:
# Question
Title: Unity store data in database
Is it possible to store assets used in a Unity game (2D or 3D) in the database? I think it is less efficient but want to have single source of truth and maybe have the game contact the database everytime it loads to get the new updates.

# Answer
First, storing large binary data in a database rarely ends well. Even if it works well at first just wait for backup and replication issues.

If you want a central source of truth for your files you can use a content delivery server/network. This way you can update your files and use the usual file backup and replication strategies.

Either way, Unity can download asset bundles from a server. If you chose to store your assets in a DB you will have to provide an HTTP server to let unity download the files.

Then once you have started deploying your assets you can use WWW to download your assets as stated here https://docs.unity3d.com/Manual/DownloadingAssetBundles.html
> 0 votes

---
Tags: unity, assets, databases
---


# Question
Title: How would I process accelerometer data to use it for camera rotation?
I'm using Three.js to make a web-based 3D first-person game. I would like the player to be able to control the camera rotation with their device's accelerometer.

The sensor data is received via the `DeviceMotionEvent` event listener. Here is an example of what it returns:

How should I proceed with this?

# Answer
> 1 votes
You don't need to use the accelerometer, there's already a way to get the device's orientation with the `deviceorientation` event:

```
addEventListener("deviceorientation", function(e) {
    // This function is called when the phone rotates
    // e.alpha is the angle around the y axis (yaw)
    // e.beta is the angle around the x axis (pitch)
    // e.gamma is the angle around the z axis (roll)
});

```

If you really want to use the accelerometer, then here's how to do it:

Take the `acceleration` vector and subtract it from the `accelerationWithGravity` vector, the result is the gravity vector. This always points down (except if you are in space), so you can normalize the vector, get the angles of it and negate them. This should result in the orientatiom of the device.

---
Tags: javascript, three.js, accelerometer
---


# Question
Title: Efficient Storage of Objects in a 2D Grid
When trying to store data related to objects in my 2d top-down tile based game (specifically, blocks), I realized that I don't have an efficient solution to storing them. I could have, for example, a 2D array of them, but that would be extremely inefficient considering the amount of possible locations there are. Also, an ArrayList is inefficient becauase number one, it severly impacts cpu usage when adding/subtracting/looking up elements, and number two, it isn't ordered.

Therefore, my question is how would I go about setting up an efficient way to store objects so as to be able to find them within a certain area and also to add and subtract from them quickly?

# Answer
> 1 votes
If your area is very sparse you can use a Quadtree.

https://en.wikipedia.org/wiki/Quadtree

However I doubt your grid is large enough to be an issue on any modern computers. For example, a 1024x1024 grid of pointers (references) to objects would only be 4MB or 8MB depending on pointer size.

# Answer
> 0 votes
Just use a 1 dimensional array, it's quite easy to look thing up in it with the formulae:

```
index = x + y * width

```

Getting the coordinates from index is also simple:

```
x = index % width
y = floor(index / width)

```

Also, it's one of the smallest way in terms of memory usage

---
Tags: java, 2d, efficiency, tiles
---


# Question
Title: Can not access GUIText in instantiated prefab
I have a prefab with the following component structure:

* Block
    + `Quad`
    + `RawImage`
    + `GUIText`

---

When I instantiate it and try to access the `GUIText`, I get the output of 'null'.

Here is the code, I am using to access the `GUIText`:

```
public GameObject Block;

GameObject obj = Instantiate(Block, position, orientation) as GameObject;
GUIText myText = obj.GetComponent<GUIText>();
print(myText);

```

---

How do I fix this?

# Answer
> 1 votes
There are actually *at least* two problems:

1. Your trying to access the *text*, but your only referencing the *container*.
2. There still does not appear to be a `GUIText` component attached to your game object.

---

First and foremost, `GUIText` is a *class* that contains the text as one of the variables. If you want to access the *text*, itself, you need to use `GUIText.text`.

That said, that does not account for `GUIText` outputting a `string` value of `null`. Unfortunetly, the only thing that really does is if `GetComponent<GUIText>` initially returns a `null` reference. It is hard to say *why* this is the case, but ultimately, it does not sound like there actually *is* a `GUIText` directly attached to the game object.

---

It is difficult to assess the *exact* cause as of this point, but there are a few possible causes and solutions.

* Perhaps you mean to say that `Block` contains a *child* that contains a `GUIText`? We need to use `GetComponentInChildren(type)`, if that is the case.
    + Note that this works off the assumption that there is *still* only one `GUIText` in the entire hierarchy of `Block`. If this is not the case, you will have to further ensure you have the correct reference.
    + You will also note that this method does not use a generic (`<T>`). Instead, you would write it as `GetComponentInChildren(type of(GUIText))`.
* Perhaps, through human error, your actually referencing an object or instance that does not *have* a `GUIText` component. If you want to account for the possibility, which is considered a good practice, you have two options:
    1. Place any code accessing `myText` inside an `if` statement that checks that `myText != null`. Remember, *trying to retrieve a component that does not exist will not cause errors, but further access will*. You can have an `else` statement follow, if you want somewhere to put debug output if the check fails.
    2. If you *must* have a `GUIText` object directly on that object, you can mark use the `[RequireComponent]` attribute on a script that is attached to that object. Simple include `[RequireComponeny(type of(GUIText))]` directly above the main class, and if your object does not have one, the class will automatically create one. If you do not have a script attached to the object that is *unique* to the object (or rather, unique to game objects that should contain a `GUIText` component), create one just for this purpose.
* Failing all this, it might be worth setting up the `GUIText` as a pre-setup `public` reference on a local script. This script would be attached to your prefab object, ideally with all required references set up, internally. You would than grab a reference to the script using `GetComponent<T>`, as you are, now. The core difference is that you would only have to do it *once* to have the access you require, assuming you require reference to the other components. This also acts as a way around issues that may be isolated to the exact way you have the `GUIText` set up.

---

Do *not* use `GameObject.Find` to clarify your reference to the initial game object, as suggested by an alternate answer.

* `GameObject.Find` can be *slow*. It is not ideal, especially if you frequently run this code.
* `GameObjevt.Find` returns the *first* game object that is found to match. There is no guarantee *which* instance this will be, if you have multiple, so it can be especially unreliable.

---
Tags: unity, unityscript
---


# Question
Title: How do I use data-orientated programming without object-orientated programming?
I have been reading many resources about data oriented programming, and one thing I understand about it is that it's about keeping chunks of memory together to improve performance. Other than that, I find it hard to understand. can someone tell me if this counts as DOP or if I am doing it all wrong?

I can't tell if my pseudocode counts as data-orientated programming:

```
// attempted non-OOP format since I am bored of standard OOP and trying C instead of C++,
// where object_ids is array of objects holding their type id's

update() {
    for (int i=0;i<nObjects-1;i++) { // where i is the object id
        // get the update function for the type of object
        object_update_functions[object_ids[i]](i);
    }
}

// example
void * object_update_functions[0](int id) {
    // // object #0's update function
    object_x[id] += 2;
}

```

I'm still unsure of how to use data-orientated programming, without object-orientated programming. Unfortunately, all of the examples I've seen of data-orientated programming still use class-based object-orientated programming.

As far as I know, back in the day of the NES, they didn't have object-orientated programming like they did, today. They had to store object variables in different arrays, consequently leading to better-performing, data-orientated code.

I want to avoid making the mistake of writing pseudo data-orientated programming, and not really getting the benefits of caching and modularity. How do I use data-orientated programming without object-orientated programming?

# Answer
Without really commenting on the whole mess that is "data oriented programming" versus "object oriented programming," (because largely those arguments get in the way of actually getting things done), the crux of your concern seems to be: is this code going to make efficient utilization of the cache?

Making efficient use of the memory cache is fairly straightforward at the high level: it means structuring your code so that if you touch some address, the next addresses you touch are *near* (ideally *next to*) the last address you just touched.

Typically this kind of code looks like "put a bunch of data in a big array, loop over that entire array and do something."

With that said, your code

```
for (int i=0;i<nObjects-1;i++) { // where i is the object id
    object_update_functions[object_ids[i]](i); // get the update function for the type of object
}

```

is *not* necessarily doing that. What you're doing is looping over an array of object IDs. If you were going to do something with each of those object IDs, that would probably be taking advantage of the contiguous nature of the object ID array. However, instead you use the ID to *index into another array*. This other array is (potentially) nowhere near `object_ids` in memory. In the worst-case scenario both arrays fit exactly into one cache line and every iteration of the loop causes a cache miss, because first the memory containing `object_ids` must be fetched to read `object_ids[i]`, and then the memory for `object_update_functions` must be read in to index into that array.

Further, you're using the result of this indirection to simply call out to some other block of code, which may do who-knows-what. Generally you'd want to consider organizing your code so you do some operation `F()` on a bunch of data, and then some other operation `G()`. Not, as you are potentially doing, calling `F()` then `G()`, then `K()`, then `F()` again.

---

What you'll want to do instead is start thinking about organizing data in terms of the operations that might need it. The operation "update the position" needs a certain set of data: the current position, the velocity, the acceleration, maybe other things. Try to organize your data so that all the "position data" for all your objects is in a big, contiguous list. Then blast through that list updating the positions of everything.

Similarly if your next task is "update the shield and HP status of every object," then you'll want to similarly have every object's shield level and HP stuffed into a contiguous array, and blast through *that*.

You can have, somewhere, a mapping from object ID to the set of position properties, and object ID to the set of shield properties. But the key is that you'll want both of those sets of properties to be stored contiguously for their respective operations already. You don't want to *have* to indirect through the object ID table to get to them; you just have that functionality around for other places in the code where you don't need to be maximally cache-coherent.

Similarly, I'd venture to say your "update" function pointers are leading you into a trap and you probably don't need them. Your top level game update function (the one you call in your game loop directly) can just call these individual update operations directly. There's really no particular need to abstract them into function pointers:

```
void UpdateTheGame(float elapsedSeconds) {
  UpdateAllPositions(elapsedSeconds, positionDataArray);
  UpdateShieldStatus(elapsedSeconds, shieldDataArray);
}

```

where `positionDataArray` is an array of `PositionData`:

```
struct PositionData {
  float x, y, z;
  float vx, vy, vz; // velocity
};

```

and so on. This means your "game objects" might end up looking like:

```
struct GameObject {
  int positionDataIndex;
  int shieldDataIndex;
};

```

so that you can retrieve the relevant data for any individual game object if you need to. The point is you want to avoid having to follow the object to get the data during the important, cache-sensitive update of all that data if you can.
> 5 votes

---
Tags: data-structure, c, data-oriented
---


# Question
Title: Place an UI Image between two 2D sprites in Unity
I am developing a 2D game with Unity.

I have two sprite objects rendered using `SpriteRenderer`.

With the new UI system, I want to use it to display an image **between** my two sprites. That is, my first sprite has a sorting order of 100, then my UI Image has a sorting order of 200 and then my second sprite has a sorting order of 300.

Is that possible?

I tried using sorting layers, but no matter what, the UI image seems to always overlay my two sprites.

# Answer
This is fairly simple to do, Weexe actually was on the correct path just didnt give the entire information you seem need.

First create your 2 sprites and a Canvas holding your image you want inbetween. ***Set "Order in Layer" to 2 and 0 for the 2 Sprites*** you want in the background or foreground. A higher number means it's in the front. All elements, including the UI will have to be on the same Sorting Layer.

Now, click your Canvas and ***set the Render Mode to World Space***, this is needed so you actually get the option to go between sprites in the world. Cuz now you have the Sorting Layer and Order in Layer Option on your Canvas aswell. ***Set the Order in Layer to 1 and the Sorting Layer to the same as the 2 Sprites***!

**Note:** If you can't find your UI Image note that it is actually super large in the scene, you'll have to heavily reduce it in size and position it the image(not the canvas). If you want to find it just zoom out alot and you'll start to see it ( ***Tip:*** if it's actually a small image you should activate the transform tool so you know where it's currently positioned ).

I just recreated this in a minute with example images, definitly works. If you have any further Questions just comment. I'll gladly help.
> 3 votes

# Answer
I've been fighting with this for an hour and I finally came up with a solution.

I was working with a World Canvas UI and couldn't get it to work correctly with sprites: first, sprites were always on top, then the sprites disappeared completely even if the UI image above them was not fully opaque.

So based on: http://answers.unity3d.com/questions/832834/unity-2d-46b-ui-why-are-instantiated-prefab-sprite.html

You should set the "Order in layer" of your background sprite's "Sprite Renderer" to 0.
Then, set the "Order in layer" of your UI Canvas component to 1.
The foreground sprite "Order in layer" should be set to 2.
The sorting layer was default for the 3 elements.

Basically, you could work with more than one world space canvas and more than one sprite (in case you want many layers of 2d stuff) and set the sorting layers correclty (remember you cannot set the Order in Layer of the UI element individually. That is set by the order of the GameObject in the hierarchy. Instead, you must set the Order in Layer for the UI in the Canvas)
> 1 votes

# Answer
You have to use the Render Mode "World Space" Reference : http://docs.unity3d.com/Manual/UICanvas.html
> 0 votes

---
Tags: unity
---


title: Cube world rendering optimizations

text:
# Question
Title: Cube world rendering optimizations
I'm making a Minecraft like game and I would like to apply some optimizations. Firstly I didn't and I rendered the world using a vbo in which I stored a cube model and I drow all blocks of the worlds and off course it caused lag if there were too many blocks. Then I decided to draw the world face-by-face and check if a face is hidden from another one.

This concept is simple if I have the world made only by cubes of the same size, like this:  Blue and black block are two blocks of the same size and the red face is the face to ignore since is hidden (overlapped) by another opaque face.

As I said if I want to make blocks of different sizes (scale)/position/rotation but by always drawing them from faces, the matter is different since I can't know if a face is completely visible or not. Here's an image of a normal block with a "custom" block on it:

Blue block is the custom block, the black a "normal" block and the red is the face overlapped by the biggest one (then it should be ignored during rendering).

Here the rotation is null but if there's no way to check rotated faces I can simply ignore it and draws all rotated blocks by default (I don't rotate all the world lol)... that's not what I'd like to do but if there's no way or the way is too difficult...

Anyway, finally, how can I check (using GL functions or doing it in my code) if a face is hidden and to ignore it on rendering?

I forgot to say that another optimization I did is if a block is hidden (has a block relative to each face) by other blocks I don't draw it.

# Answer
> 3 votes
*(In this answer I assume that your world is made of separate cubes. If some cubes joined together into grids, then the algorithm can be improved a lot.)*

---

You can check if a side is completely inside of a cube, and only add it to your vertex buffer if it's not.

The algorithm is easy:

```
//  B······•
//  :'.     '.
//  :  A······C
//  :  :      :
//  •  :      :
//   '.:      :
//     D······•

bool point_cube_collision(vec3 point, vec3 a, vec3 b, vec3 c, vec3 d, vec3 size)
{
    // `size` must be equal to `length(b - a)`, but you should remember it instead of recomputing it each time.
    const float eps = 0.0001; // This is used to make block sides disappear if they're not intersecting, but just toucing. The number determines how far the sides can be from each other to still be considered intersecting.
    b -= a;
    c -= a;
    d -= a;
    b /= size;
    c /= size;
    d /= size;
    point -= a;
    float m = point • b; // • means dot product
    float n = point • c;
    float p = point • d;
    return m >= -eps && m <= size+eps
        && n >= -eps && n <= size+eps
        && p >= -eps && p <= size+eps;
}

```

Now if you want to check if an entire side hidden inside of a cube, you just check 4 corners of it, and if all of them a colliding with the cube, then the side is completely inside.

I assume you already use VBOs to render your world. If so, you should add a side to your VBO only if it's not (completely) submerged into a cube.

I think you already understood that performing such check (every time the world is changed) for every cube has `O(n^2)` complexity (for each cube you need to check all other cubes), which means that it will quickly become very slow when your world will get larger.

To make the computations a lot more faster, you could divide your world into chunks. Then instead of checking every cube for each vertex, you can check only those cubes which intersect with a chunk which contains a vertex.

---

If for some reason chunk system won't work well for you, then you can try something more tricky. Something like Dynamic Bounding Volume Tree (which is used in Bullet Physics to check if objects are close to each other). I'm not really sure if it will work well, but I also highly doubt that you will need to try it.

# Answer
> 0 votes
My suggestion would be using a 3D array of Block objects. You should check whether the block next to a block is solid then only render the visible faces

# Answer
> 0 votes
I'm not entirely sure about only rendering the faces themselves, but I know that not rendering objects that the camera cannot see directly would fall under the "culling" umbrella, and specifically I think you maybe want to look at occlusion culling. I'm not intimately familiar with OpenGL, but a quick google search yielded at least several ideas for implementing occlusion culling. Perhaps see this thread or this other one (both from the opengl formums) for some ideas.

There's also an article that I really liked which may give some general ideas as well. In there there's also a mention at Depth Pre-Pass as an option for your specific problem, which will do a rough cull of pixels that are behind other objects. It's not always an efficient method for all applications, but it might be worth your time to look into. I hope this helps a bit to give you some ideas.

---
Tags: opengl, rendering, optimization, voxels, minecraft-modding
---


title: 3D modelling from a picture?

text:
# Question
Title: 3D modelling from a picture?
Can I make a model from a picture? A friend of mine would like to be an NPC in my game ! :P I would like to add him, but I never did 3D modelling!

Is it possible to make 3d model from photo/picture?

# Answer
> 3 votes
Yes, but probably not the way you're thinking of.

You can certainly use a 2D photo or set of photos as reference while creating a 3D model yourself. Many people do. But fundamentally you're still building the model yourself and using the 2D images as reference, the same way a painter or sketch artist might use a photo for reference.

There *are* methods for performing 3D reconstruction from 2D data, it's a reasonably common topic of research and various academic papers. But this often requires multiple images or other forms of data (such as disorganized point clouds) to be useful, and is generally not something that exists in commodity modeling software. The software that does it is usually written one-off for these papers.

If you're hoping to be able to drop a basic photo into a 3D modeling program and have it pop out a high-quality, game-ready model... you're going to be disappointed, as the technology just isn't there yet.

---
Tags: 3d, graphics
---