# Question
Title: Why does VertexPositionColor seem incompatible with Monogame?
This question is a continuation of What causes this InvalidOperationException when drawing primitives?.

I've been dealing with HLSL shaders in Monogame over the past few days. It has been extremely time-consuming and frustrating trying to duplicate shader functionality I was able to achieve easily with vanilla XNA. As an example, rendering a fullscreen quad using VertexPositionColor elements fails with the following error.

Up until this morning, I had been using the BasicEffect class with as many configurations as I could think of without success. After it became clear that BasicEffect couldn't achieve what I wanted, I wrote a simple custom shader that looks like this.

```
struct VertexShaderInput
{
    float4 Color : COLOR0;
    float4 Position : SV_POSITION0;
};

struct VertexShaderOutput
{
    float4 Color : COLOR0;
    float4 Position : SV_POSITION0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Color = input.Color;
    output.Position = input.Position;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return input.Color;
}

technique Technique0
{
    pass Pass0
    {
        VertexShader = compile vs_4_0 VertexShaderFunction();
        PixelShader = compile ps_4_0 PixelShaderFunction();
    }
}

```

The shader above seems reasonable because, as the name VertexPositionColor implies, I only need position and color. But using that effect in place of BasicEffect didn't change anything either. I finally started digging more deeply into vertex declarations (something I had no knowledge of until today) and came across the following source code for VertexPositionColor.

```
VertexElement[] elements = new VertexElement[]
{
    new VertexElement (0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
    new VertexElement (12, VertexElementFormat.Color, VertexElementUsage.Color, 0)
};

```

Based on those lines, the vertex declaration is expecting 1) a Vector3 position and 2) a color. That seemed like the answer I needed, since in my shader, position is float4 rather than float3. But changing position to float3 produced the following error.

So, to recap and describe what I can see so far:

1. I'm trying to render a quad using four VertexPositionColor elements.
2. Rendering fails because the vertex shader input (defined in my shader code above) represents position using float4 rather than float3.
3. I can't change position to use float3 because the shader compiler version (vs\_4\_0) doesn't allow it (I think the shader version is relevant).

This whole this is just very confusing, especially since I've used shaders like this successfully in the past with XNA rather than Monogame. Is there a solution to this problem apart from creating my own custom VertexPositionColor replacement class with its own custom vertex declaration? That all seems overkill considering the simplicity of what I'm trying to do.

This issue echoes a general feeling I've gotten that HLSL shaders in Monogame are, for lack of better phrasing, messed up. Can anyone help clarify all this?

Thank you.

# Answer
> 1 votes
The actual root cause of this problem was identified by Felsir in this question. It turns out that an exception was thrown because no shader was applied when drawing primitives using GraphicsDevice. In other words, there was effectively nothing wrong with the shader itself (either using BasicEffect or a custom one). The exception message was misleading.

I'm not sure about StackExchange conventions on self-answering questions, but I wanted this question to have a correct accepted answer. If this kind of post doesn't fit conventions, please let me know.

# Answer
> 0 votes
```
struct VertexShaderInput
{

float3 Position : POSITION0;
float4 Color : COLOR0;
};

struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;

};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;
output.Color = input.Color;
output.Position = float4(input.Position,1);

return output;
}

```

That is how it should be.

Input does not take SV\_POSITION it has to be POSITION0 and must be first in struct same with output, SV\_POSITION not SV\_POSITION0 and it must be first in the struct.

If u look at the vertex struct in C# it has to match the one in HLSL.

---

I'm not sure if this will work in mono game but if u are talking full screen quad then u can do it like this:

don't set a vb or ib or inputlayout, call context.draw(3) and have the vertex shader like this...

```
// outputs a full screen triangle with screen-space coordinates
// input: three empty vertices
VertexShaderOutput VSQuad(uint vertexID : SV_VertexID)
{
VertexShaderOutput result;

result.TexCoord = float2((vertexID << 1) & 2, vertexID & 2);
result.Position = float4(result.TexCoord * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);

return result;
}

```

I would have color set as a const so u can set it from C# per object

---

Edit: The name of the vertex element does not match the vertex input because in mono game on the back end the elements would look something like this:

```
  Public Shared VertexElements As InputElement() = New InputElement() {New InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                                                                     New InputElement("NORMAL", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                                     New InputElement("TEXCOORD", 0, DXGI.Format.R32G32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0)
                                                         }

```

Notice how the name of POSITION not SV\_POSITION in XNA it didn't matter how u did ur vertex structs the runtime would sort it out but now all names must match so if you put SV\_ in your shader it want match if u decompile the backend I'm sure it will look something like what I posted because that is how u do it in sharp dx.

But I don't even do it like that anymore because input layout building sucks by hand so I wrote this:

```
  Private Function InputLayoutBuilder(_shader As ShaderBytecode) As InputLayout
    Dim blah As New ShaderReflection(_shader)
    Dim Elements As New List(Of InputElement)
    For i As Integer = 0 To blah.Description.InputParameters - 1
        Dim nnn As ShaderParameterDescription = blah.GetInputParameterDescription(i)
        If nnn.SemanticName.Contains("SV_") Then
            Continue For
        End If
        Dim _InputElement As New InputElement
        Dim format As New DXGI.Format
        _InputElement.SemanticName = nnn.SemanticName
        _InputElement.SemanticIndex = nnn.SemanticIndex
        _InputElement.Slot = nnn.Stream
        _InputElement.InstanceDataStepRate = 0
        If i = 0 Then
            _InputElement.AlignedByteOffset = 0
        Else
            _InputElement.AlignedByteOffset = InputElement.AppendAligned
        End If
        If nnn.SemanticName = "WORLD" Then
            _InputElement.Slot = 1
            If nnn.SemanticIndex = 0 Then
                _InputElement.AlignedByteOffset = 0
            Else
                _InputElement.AlignedByteOffset = InputElement.AppendAligned
            End If
            _InputElement.InstanceDataStepRate = 1
            _InputElement.Classification = InputClassification.PerInstanceData
        Else
            _InputElement.InstanceDataStepRate = 0
            _InputElement.Classification = InputClassification.PerVertexData
        End If
        If nnn.SemanticName = "SHID" Then
            _InputElement.Slot = 1
            _InputElement.AlignedByteOffset = InputElement.AppendAligned
            _InputElement.InstanceDataStepRate = 1
            _InputElement.Classification = InputClassification.PerInstanceData
        End If
        If nnn.UsageMask = 1 Then
            If nnn.ComponentType = RegisterComponentType.UInt32 Then
                _InputElement.Format = Format.R32_UInt
            ElseIf nnn.ComponentType = RegisterComponentType.SInt32 Then
                _InputElement.Format = Format.R32_SInt
            ElseIf nnn.ComponentType = RegisterComponentType.Float32 Then
                _InputElement.Format = Format.R32_Float
            End If
        ElseIf nnn.UsageMask <= 3 Then
            If nnn.ComponentType = RegisterComponentType.UInt32 Then
                _InputElement.Format = Format.R32G32_UInt
            ElseIf nnn.ComponentType = RegisterComponentType.SInt32 Then
                _InputElement.Format = Format.R32G32_SInt
            ElseIf nnn.ComponentType = RegisterComponentType.Float32 Then
                _InputElement.Format = Format.R32G32_Float
            End If
        ElseIf nnn.UsageMask <= 7 Then
            If nnn.ComponentType = RegisterComponentType.UInt32 Then
                _InputElement.Format = Format.R32G32B32_UInt
            ElseIf nnn.ComponentType = RegisterComponentType.SInt32 Then
                _InputElement.Format = Format.R32G32B32_SInt
            ElseIf nnn.ComponentType = RegisterComponentType.Float32 Then
                _InputElement.Format = Format.R32G32B32_Float
            End If
        ElseIf nnn.UsageMask <= 15 Then
            If nnn.ComponentType = RegisterComponentType.UInt32 Then
                _InputElement.Format = Format.R32G32B32A32_UInt
            ElseIf nnn.ComponentType = RegisterComponentType.SInt32 Then
                _InputElement.Format = Format.R32G32B32A32_SInt
            ElseIf nnn.ComponentType = RegisterComponentType.Float32 Then
                _InputElement.Format = Format.R32G32B32A32_Float
            End If
        End If
        Elements.Add(_InputElement)
    Next

    If Elements.Count > 0 Then
        Dim newinputlayout As New InputLayout(MainDevice, _shader, Elements.ToArray)
        blah.Dispose()
        Return newinputlayout
    Else
        Return Nothing
    End If

End Function

```

That will pull it all out of the shader and spit out an input layout no need to do it by hand just set in your shader and let this do the rest it also checks for a WORLD tag so u can pass a world matrix to the vertex shader for instancing. Mono game may let you get at all that stuff but it may be hidden under all there abstraction but that bit of code saves all this tweaking for different input strucs.

Try this:

```
Texture2D colorMap;
sampler colorSampler = sampler_state
{

AddressU = Clamp;
AddressV = Clamp;
Filter = MIN_MAG_MIP_POINT;
};

struct VertexShaderOutput
{
float4 Position : SV_Position;
float2 TexCoord : TEXCOORD0;

};
struct PixelShaderOutput
{
float4 Color : SV_Target0;

};

// outputs a full screen triangle with screen-space coordinates
// input: three empty vertices
VertexShaderOutput VSQuad( uint vertexID : SV_VertexID )
{
VertexShaderOutput result;
result.TexCoord = float2((vertexID << 1) & 2, vertexID & 2);
result.Position  = float4(result.TexCoord  * float2(2.0f, -2.0f) + float2 -1.0f, 1.0f), 0.0f, 1.0f);
return result;
}

PixelShaderOutput PShader(VertexShaderOutput input)
{
 PixelShaderOutput output = (PixelShaderOutput)1;
float4 Color = colorMap.Sample(colorSampler, input.TexCoord);
output.Color =Color;
output.Color.a=1;
 return output;
}

technique11 Render
{
pass P0
{

    SetVertexShader( CompileShader( vs_5_0, VSQuad() ) );
    SetPixelShader( CompileShader( ps_5_0, PShader() ) );
}
}

```

---
Tags: monogame, hlsl, vertex-shader
---


title: How does GPU handle texture and VRAM?

text:
# Question
Title: How does GPU handle texture and VRAM?
It's actually a bunch of inter-related questions:

1. Are compressed textures (dxt5/dxt1 etc.) ever completely decompressed while going through rendering pipeline?
2. If the answer to the first question is true, then how is memory managed for several large uncompressed textures?
3. Is framebuffer any different from VRAM in modern GPU?

# Answer
> 30 votes
GPU compressed texture formats like DXT / BC / ETC are specifically designed to be read directly from their compressed form. They don't need to be unpacked into a raw RGBA buffer.

The way this works is each block of texels (often 4x4) takes up some fixed number of bits - so we know exactly how far along in the buffer to look for a particular texel - and these blocks can be decompressed without reading all of the surrounding/preceding texture information. GPUs contain specialized hardware that decompresses just the requested texel blocks as needed to fulfill texture sampling requests from your shaders.

This is in contrast to formats like jpg & png, where the amount of space each texel takes up can vary across the image (detailed areas taking up more data, predictable areas taking up less), so to find a particular texel you have to uncompress the whole image, or at least large/distributed chunks of it. But because they can selectively compress predictable areas of a texture, they tend to compress images to smaller sizes for storage on disc or transmission over a network than what we get from GPU-friendly formats. Different strategies for different uses.

---

Generally, asking multiple questions should be done via multiple posts, but since this is a pretty short answer I'll hit point 3 too:

"Framebuffer" is just a particular bit of video memory that we've decided to use to store the composed image we want to present to the screen. Do note the details in JarkkoL's answer, where on some specialized hardware we might choose to locate this buffer in a particular *part* of our available video memory that's optimized for the bandwidth needs of render targets.

# Answer
> 8 votes
Answers to your questions really depends on the platform. Generally BC formats are kept in compressed form in memory and decompression is done in flight by GPU texture units, but there are exceptions. Namely Xbox 360 is known to decompress complete 4x4 pixel BC blocks to cache before TU fetches the data thus inflating cache usage. I don't know of any platform that would decompress the entire texture to vram upon load though, but I highly doubt it because of the added memory and bandwidth usage.

The same thing goes for framebuffers - it depends on the platform. On Xbox 360 you had 10MB of dedicated high bandwidth EDRAM that you had to use for render targets. On Xbox One you still have 32MB of special ESRAM that is preferred for render targets due to high bandwidth (and can also be fetched from unlike on Xbox 360), but the render targets can also reside in regular DDR3 memory.

---
Tags: textures, gpu, memory
---


# Question
Title: How To Have My Character Turn When The Camera View Moves
So I have recently finished animating my character, having it move with key presses and have applied a camera to it. But I am stumped on how to have the player turn when the camera view moves, and have them both in sink. I want to have this instead of using keys to turn because that can be very awkward and hard to control. I would really appreciate any help I can get on this, as it will allow me to finally finish my character.

Thanks, Nova

# Answer
IMHO its done by attaching camera to the player as a child object, as the player rotate the camera will accordingly be rotated.
> 1 votes

# Answer
I guess you have a Matrix for your camera's rotation and position.

The solution would be to bind the camera's rotation matrix to your Character's rotation matrix, so whenever the camera rotates the character rotates as well.
> 0 votes

---
Tags: unity, animation, camera, control
---


title: Unity3D: Photon syncing physics events

text:
# Question
Title: Unity3D: Photon syncing physics events
I'm making a billiard game and I wanna implement multiplayer in it. Since updating the movement in every frame is inefficient and laggy, I thought I could remake the events in game happen in all clients but for some reason they differ from one another.

The direction that the ball launches is correct but it starts to differ for different users when it collides with other balls(if it collides only with the wall it's fine). Technically this shouldn't happen IMO.

This is the code I use to add force to the player ball:

I use this to launch the player ball

```
photonView.RPC("FireBall", PhotonTargets.All, storedDirection, power);

```

This is the function that adds the force to the player ball.

```
[PunRPC]
    public void FireBall(Vector3 stordDir , float poww)
    {
        rigidbody.AddForce(stordDir.normalized * poww, ForceMode.Impulse);
    }

```

I use this function to get the desired direction of the player.

```
public void UpdateStickPosition()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
        {
            if (Input.GetKeyDown(KeyCode.Mouse0)
            {
                storedDirection = hit.point - transform.position;
            }
        }

    }

```

I appreciate all help given, don't hesitate to ask me any questions.

# Answer
> 1 votes
Unity's physics engine, NVIDIA's PhysX, is not deterministic. You're not going to get the same physics simulation twice *even on the same machine* because the physics engine was just not made to work that way (for good reasons)\[1\].

The solution? You'll need to update the positions and other physics attributes periodically on the clients from whatever client/server has authority. This wouldn't be done every frame but at some coarser time step.

In Photon you need to take these steps to sync your data.

* Implement `OnPhotonSerializeView()` to send position, rotation, velocity, angular velocity, etc.
* Modify your `PhotonView` to use an observer option of `Unreliable on Change` (as is suggested by Photon's documentation for frequent updates, and probably the best for your use case).
* When the stream is deserialized on the client, sync the values as necessary by linear interpolating the current client values with the new values.

If you're using Unity's UNET (needs Unity 5), then it's as simple as just adding a NetworkTransform to the objects that you want to sync and changing the sync mode and sync timestep for your particular use case.

---

\[1\] As for why it isn't deterministic, is refer to the PhysX knowledge base...

> The first problem here is that the PhysX SDK is not deterministic.Especially when running different hardware setups, bus latencies can vary between runs, or on different machines. Even without hardware in the machine, we do not guarantee any type of determinism.

...and to this post on Unity's forums:

> In order for the physics to be completely deterministic then absolutely everything has to happen in the same manor, including the order of collision detection and resolution etc which will require everything to be added or arranged in memory in the same order. As far as I know, Unity's wrapper around the PhysX system makes it impossible for you to garauntee this.

---
Tags: unity, networking, multiplayer, online, photon
---


# Question
Title: Points inside a Polygon, failing for shapes with 0,0
I've been using an algorithm (http://wiki.unity3d.com/index.php/PolyContainsPoint) to tell me if a point is inside a polygon... in fact a few variants (here and here) but they all come back the same. Shapes with (0,0) vertices fail.

Here's the function:

```
private bool IsPointInPolygon(Vector2[] polyPoints, Vector2 p)
{
    int j = polyPoints.Length-1;
    bool inside = false;
    for (int i = 0; i < polyPoints.Length; j = i++) {
        if ( ((polyPoints[i].y <= p.y && p.y < polyPoints[j].y) || (polyPoints[j].y <= p.y && p.y < polyPoints[i].y)) &&
            (p.x < (polyPoints[j].x - polyPoints[i].x) * (p.y - polyPoints[i].y) / (polyPoints[j].y - polyPoints[i].y) + polyPoints[i].x))
            inside = !inside;
    }
    return inside;
}

```

And here's the testing output for a number of 'cloned' squares being translated around the original square (original shown in black in the diagram) - Notice all the squares with the 0,0 fail. Why is this? I don't really know what the algorithm is doing but have tried a few with exactly the same result..

```
Vector origin (0.0, 0.0) to Vector destination (1.0, 0.0)
distance: (1.0, 0.0)
New Shape 1 0
New Shape 2 0
New Shape 2 1
New Shape 1 1
PASS

Vector origin (0.0, 0.0) to Vector destination (1.0, 1.0)
distance: (1.0, 1.0)
New Shape 1 1
New Shape 2 1
New Shape 2 2
New Shape 1 2
PASS

Vector origin (0.0, 0.0) to Vector destination (0.0, 1.0)
distance: (0.0, 1.0)
New Shape 0 1
New Shape 1 1
New Shape 1 2
New Shape 0 2
PASS

Vector origin (1.0, 0.0) to Vector destination (0.0, 0.0)
distance: (-1.0, 0.0)
New Shape -1 0
New Shape 0 0
New Shape 0 1
New Shape -1 1
FAIL

Vector origin (1.0, 0.0) to Vector destination (1.0, 1.0)
distance: (0.0, 1.0)
New Shape 0 1
New Shape 1 1
New Shape 1 2
New Shape 0 2
PASS

Vector origin (1.0, 0.0) to Vector destination (0.0, 1.0)
distance: (-1.0, 1.0)
New Shape -1 1
New Shape 0 1
New Shape 0 2
New Shape -1 2
PASS

Vector origin (1.0, 1.0) to Vector destination (0.0, 0.0)
distance: (-1.0, -1.0)
New Shape -1 -1
New Shape 0 -1
New Shape 0 0
New Shape -1 0
FAIL

Vector origin (1.0, 1.0) to Vector destination (1.0, 0.0)
distance: (0.0, -1.0)
New Shape 0 -1
New Shape 1 -1
New Shape 1 0
New Shape 0 0
FAIL

Vector origin (1.0, 1.0) to Vector destination (0.0, 1.0)
distance: (-1.0, 0.0)
New Shape -1 0
New Shape 0 0
New Shape 0 1
New Shape -1 1
FAIL

Vector origin (0.0, 1.0) to Vector destination (0.0, 0.0)
distance: (0.0, -1.0)
New Shape 0 -1
New Shape 1 -1
New Shape 1 0
New Shape 0 0
FAIL

Vector origin (0.0, 1.0) to Vector destination (1.0, 0.0)
distance: (1.0, -1.0)
New Shape 1 -1
New Shape 2 -1
New Shape 2 0
New Shape 1 0
PASS

Vector origin (0.0, 1.0) to Vector destination (1.0, 1.0)
distance: (1.0, 0.0)
New Shape 1 0
New Shape 2 0
New Shape 2 1
New Shape 1 1
PASS

```

# Answer
Is Your Test Point (0, 0) In All These Cases?
Do You Want To Include Boundary Points Inside The Polygon?

If so, then you would get FAIL for all the pink rectangles but PASS for the black one.

Anyway you can check if a point is on the perimeter/boundary of the polygon using this code

```
private bool IsPointOnPolygon(Vector2[] polyPoints, Vector2 p)
{
    int j = polyPoints.Length - 1;
    bool onPoly = false;

    for (int i = 0; i < polyPoints.Length - 1; i++)
    {
        if ((polyPoints[i].y <= p.y && p.y <= polyPoints[j].y) || (polyPoints[j].y <= p.y && p.y <= polyPoints[i].y))
        {
            if (polyPoints[i].y == polyPoints[j].y)
            {
                if ((polyPoints[i].x <= p.x && p.x <= polyPoints[j].x) || (polyPoints[j].x <= p.x && p.x <= polyPoints[i].x))
                {
                    onPoly = true;
                    break;
                }
            }
            else
            {
                float edgeX = ((polyPoints[j].x - polyPoints[i].x) * (p.y - polyPoints[i].y) / (polyPoints[j].y - polyPoints[i].y) + polyPoints[i].x);
                if (p.x == edgeX)
                {
                    onPoly = true;
                    break;
                }
            }
        }
    }

    return onPoly;
}

```

Since there is a limit on floating number precision, it can give wrong results for near cases. But you can overcome that issue by using error limit check on edge cases like this

```
float errLimit = 0.000001f;
if (Math.Abs(p.x - edgeX) < errLimit)
{
    onPoly = true;
    break;
}

```

Hope I answered your question
> 1 votes

---
Tags: c#, collision-detection, mathematics, geometry
---


title: "Highlighting" Faces/Edges/Corners

text:
# Question
Title: "Highlighting" Faces/Edges/Corners
How would I "highlight" faces/edges/corners? I would prefer an explanation OpenGL if possible.

Here's an example:

# Answer
Depending on your skill level, solid wireframes may be an option.

(Image borrowed from the linked NVIDIA paper)

NVIDIA's example images show highlighting edges of triangles, but that's something you can work around.

You can use a geometry shader to generate barycentric coordinates, and then check them in your fragment shader to determine distance of a fragment from an edge.

If the distance falls below some threshold, set your fragment color to the desired "wire" color, and return. Otherwise, shade as normal.

Another option is to render your model filled, then render it again as wireframe with depth test disabled. However, unlike solid wireframes, this requires a second pass, and just feels inelegant. Also, rendering in wireframe mode is significantly slower than rendering filled primitives.

Or, you could just render with a texture that has a nice border, but that'll look like crap unless you tweak your texture coordinates in the pixel / fragment shader.

Here's a snippet from one of my geometry shaders that does the brunt of the work:

```
void EmitTriangle(vec3 v0, vec3 v1, vec3 v2)
{
    // float a[5] = float[](3.4, 4.2, 5.0, 5.2, 1.1);
    vec3 verts[] = vec3[]( v0, v1, v2 );

    for (int i = 0; i < 3; ++i)
    {
        vec4 p = vec4(verts[i], 1);

        gl_Position = Projection * View * World * p;
        gOut.ObjectPosition = p;
        gOut.WorldPosition = World * p;
        gOut.Color = vec4(1, 0, 1, 1);
        gOut.BaryPosition = vec3(i == 0, i == 1, i == 2);
        //gOut.BaryPosition.rgb = vec3(1.0f);

        EmitVertex();
    }

    EndPrimitive();
}

```

and a snippet associated fragment shader:

```
const float wireDistance = 0.05f;

/// check interpolated BaryPosition to determine distance to edge.
bool showWire = (gOut.BaryPosition.x < wireDistance
                || gOut.BaryPosition.y < wireDistance
                || gOut.BaryPosition.z < wireDistance)
                ;

if (showWire) { // return the desired wire color }

```

You can probably replace the '||' triplet with any(gOut.BaryPosition \< wireDistance), but I don't have time to try it and remember the shader compiler being a bit persnickety about that one.
> 1 votes

---
Tags: opengl, c++, directx, graphics, debugging
---


# Question
Title: How does Hierarchical Pathfinding deal with obstructions in the same chunk?
Aigamedev.com provides this visualization of HPA\*:

All the nodes within the same chunk connect to each other. What if there was an obstruction between nodes in the same chunk? For example:

What would the resulting visualization look like with an obstruction in the center bottom left chunk? How would this be detected?

# Answer
> 2 votes
Partitioning the chunk into two might result in additional entrances (nodes) in the graph, but otherwise there is nothing special that happens. Your statement *"all the nodes within the same chunk \[must\] connect to each other"* is false.

In your example the resulting entrances are the same *(only a few edges are removed from the graph)*, but in the paper the authors give an example where a partition causes the sides of one chunk to be split into multiple entrances.

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


# Question
Title: OpenGL multiple viewports with 3d-2d viewing
I am trying to draw two viewports, the one on top having a 3D stuff into it, and the other at bottom with a 2D stuff fed into it. However, whatever 2D stuff i draw in the bottom viewport is not rendered to the screen. Below is the piece of my code.

```
    void display() {

    //first viewport of height h/8
    glViewport(0, 0, width, height / 8);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    /*glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();*/
    gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0f, 1.0f, 1.0f);
    glRectf(-1.0, 1.0, 1.0, -1.0);
    glFlush();

    //second viewport of height 7h/8
    glViewport(0, 2*height / 8, width, 7 * (height / 8));
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    aspect = (double)8 * width / ((double)height * 7);
    gluPerspective(fieldofview, aspect, nearPlane, farPlane);
    // setup viewing matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.0f, 20.0f, 10.0f,
        0.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 1.0f);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    draw_model(objs[0]); // draw the plane
    draw_model(objs[1]); // draw the first diamond
    glPopMatrix();

    glPushMatrix();
    glRotatef(angle, 0.0f, 0.0f, 1.0f);
    glTranslatef(moving_position.x, moving_position.y, moving_position.z);
    draw_model(objs[2]); // draw the second diamond
    glPopMatrix();
    glutSwapBuffers();
    move(8);
    // set up menus
}

void reshape(int x, int y) {
    width = x;
    height = y;
    if (height == 0)        // not divided by zero
        height = 1;
}

void main(int argc, char* argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(position_x, position_y);
    glutInitWindowSize(width, height);
    winId = glutCreateWindow("Mesh Viewer");
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);       // display function
    init();
    glutMainLoop();
}

```

Below is my output, with no rectangle in 1st viewport:

Moreover, can I apply some background color to the second viewport without using the `glScissor`?

# Answer
> 0 votes
Looks like `glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);` was causing the problem. Removing the second occurence for it resolved the problem.

---
Tags: opengl, windows, visual-studio
---


# Question
Title: What is the fastest algorithm to check if two cubes intersect (where the cubes are not axis aligned)?
I am looking for an algorithm to check if two cubes intersect. One can check if each of the 6 faces of cube A are intersected by each of 12 edges of cube B, but that is 72 checks. I've heard there is a paper from 1997 or so, describing a method that uses just 15 intersection checks, but I can't find it. Can you please share the name of the paper, describing it or describe it in your words.

This question deals with axis aligned cubes which is not really useful. https://stackoverflow.com/questions/5009526/overlapping-cubes

# Answer
Separating axis test. (Also called separating axis theorem, separating axis theorem test, yada yada.)

If you can find an axis (ANY axis), not just regular XYZ basis vectors) where the projections of your two cubes don't overlap, then they don't intersect.

There are a ton of tutorials and implementations available via Google, but this one has pretty graphs:

https://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169

This is what we teach our game dev grad students and they all get jobs. :)

Also, checking intersections of vertices and faces or edges doesn't cover the case where cubes are nested, so it's not a real solution. SAT looks complicated in 3D, but it's just a lot of repetition. Cut, paste, trace and try some edge cases and you'll get it.

A dirt-simple method that's good enough for broad-phase collision detection is to treat the cubes as spheres. (If they're really regular cubes, the error is marginal, though proportional to the scale of the cubes relative to each other.)

Get the distance between the center of the cubes, and see if it is greater than the sum of the half diagonals of the two cubes. (Basically, you're checking bounding spheres instead of worrying about hyperplanes.)
> 4 votes

---
Tags: 3d, algorithm, intersection
---


# Question
Title: Do the sprites inside a PoT spritesheed need to be PoT aswell?
I use *TexturePackerGUI* to create PoT spritesheets. But do the sprites inside the spritesheet need to be PoT aswell? If they need to, do I need to disable trimming? The framework I use is libGDX.

# Answer
**No, they don't need to be POT.**

This is one of the points of spritesheets existence.

However note, if you plan to use mipmaps, colors might blend on lower mipmap levels. Then try to place similarly colored sprites together, or align to POT bounds, or pad them more.
> 0 votes

---
Tags: libgdx, sprites, spritesheet, texture-atlas
---


# Question
Title: Why does the box rotate, spin instead of gliding?
I've just learned that if I want to move an object so it acts depending of physics, I need to use `rigidbody.velocity` instead of `transform.Translate`. When I was using `transform.Translate` the box glided without problem. The only problem was that when it collided with a wall it began to *jump* and spin like crazy. But that problem is fixed now!

But when I added a rigidbody and used `rigidbody.velocity`, another problem stemmed: It doesn't glide. I tried using `rigidbody.velocity` and also, instead, I tried to create a Vector 3 `movement`, and at the end of the code I would write `rb.AddForce (movement);`. However, **it still rotates, instead of gliding**.

What's is generating this weird problem?

This is my updated code:

```
using UnityEngine;
using System.Collections;

public class MoveCharacter : MonoBehaviour {

    public float deltaMovement = 1f;
    public Rigidbody rb;
    // Use this for initialization
    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update ()
    {
        Debug.Log (Time.deltaTime);
        Moving();
    }

    void Moving()
    {
        Vector3 movement = new Vector3(0, 0, 0);
        //Moves the character to where it needs.
        if (Input.GetKey (KeyCode.A)) {
            movement = new Vector3(deltaMovement, 0, 0);
        } else if (Input.GetKey (KeyCode.D)){
            movement = new Vector3 (-deltaMovement, 0, 0);
        }
        float yRotation = Camera.main.transform.eulerAngles.y;
        float movementX = Mathf.Sin ((yRotation * Mathf.PI) / 180) * deltaMovement;
        float movementZ = Mathf.Cos ((yRotation * Mathf.PI) / 180) * deltaMovement;

        if (Input.GetKey (KeyCode.W)) {
            movement = new Vector3 (movementX, 0, movementZ);
        } else if (Input.GetKey (KeyCode.S)){
            movement = new Vector3 (-movementX, 0, -movementZ);
        }
        rb.AddForce (movement);
    }
}

```

By the way, changing between `Update()` and `FixedUpdate()` didn't help...

# Answer
Take into account that Applying a force is not the same as changing the velocity of the object.

Without friction, the result would be very similar, but when an object is standing in a surface, and there is friction between them, the behaviour could be very different.

In the videos you uploaded, the cube is rolling because you are pushing it from a side, just like a regular cube would roll if the friction was strong enough.

If you want the cube to glide as you say, you have to remove this friction. To do so you must assing a new `Phycics material` to your cube, and remove friction from it.

* Create a Physics material

* Select it, and in the inspector, remove friction:

* Assign the new material to the Box Collider

Also, I would highly recommend update Physics behaviour from `FixedUpdate()`

As for the function to move the object, it should look something like this:

```
void FixedUpdate()
{

    //Moves the character to where it needs.
    if (Input.GetKey(KeyCode.D))
    {
        GetComponent<Rigidbody>().angularVelocity = Vector3.up * deltaMovement;
    }
    else if (Input.GetKey(KeyCode.A))
    {
        GetComponent<Rigidbody>().angularVelocity = -Vector3.up * deltaMovement;
    }

    if (Input.GetKey(KeyCode.W))
    {
        GetComponent<Rigidbody>().velocity = transform.forward * deltaMovement;
    }
    else if (Input.GetKey(KeyCode.S))
    {
        GetComponent<Rigidbody>().velocity = -transform.forward * deltaMovement;
    }

}

```

Notice I'm using `velocity`. If you were to use `AddForce`, the object would move faster and faster, as you keep applying force to the object.

If you decide to use `velocity`, you can rise the material friction a bit if you wish.
> 1 votes

---
Tags: unity, physics, rotation, rigidbody
---


# Question
Title: Breaking up a 2d shape into small triangles
I have a "piece of cloth" (2d shape) that I'm applying soft-body physics to. This works great when the shape is a square and I can create a regular grid of vertices between which are hung the cloth's "springs." However, now I'm trying to get this to work with non-square piece of cloth, so I'd like to be able to break the polygon down into thousands of tiny triangles. I've seen lots of libraries to tessellate or triangulate polygons, but they all seem to minimize the number of triangles created, which is exactly the opposite of what I want.

Does anyone know of a library (optimally in JS!) that breaks up a polygon into arbitrarily small chunks? Preferably as regular as possible (i.e., creating a grid-like layout where possible), but not required.

Alternatively, does anyone know if there's a name for this, so I can just look up the algorithm and implement it myself?

# Answer
...and it turns out that "polygon subdivision" is the search term for this, and three.js has a library for it: SubdivisionModifer.js. It can be used as:

```
var modifier = new SubdivisionModifier(2);
modifier.modify(geometry);

```

Note that the first time I ran it I passed in 10 for the constructor and the tab at 1.5GB of memory and crashed: lower is better.
> 0 votes

---
Tags: 2d, javascript, tessellation
---


# Question
Title: Why is the standard on displaying missing textures is via a black and purple checkerboard?
In many different games, such as Minecraft and TF2, the default texture is a black and purple checkerboard. Even games that don't use that exact texture incorporate elements of it. Borderlands 2 uses a white and purple checkerboard, and Skyrim uses a solid purple texture. Why is the black and purple checkerboard so prevalent as a default texture?

# Answer
The main goal of a default/fallback type of asset like this to be noticeable. That's why very high intensity colors (pure white, red, purple, or whatnot) are often used. They generally would not normally appear in the scene.

Checkerboard patterns can create moire effects when used as textures, or simply provide extra visual noise (especially when the pixel coverage of the asset is small), helping to increase the visibility.
> 3 votes

---
Tags: textures, graphics, standards
---


# Question
Title: Unity in c# errors with "the type does not contain a constructor that takes 0 arguments"
This is the problematic line

```
datosAguardar datos = new datosAguardar ();

```

Here is my code

```
public class estadoJuego : MonoBehaviour {

public int puntuacionMaxima = 0;
public static estadoJuego estadojuego;
private string rutaArchivo;

void Awake ()
{
    rutaArchivo = Application.persistentDataPath + "/datos.dat";
    if (estadojuego == null)
    {
        estadojuego = this;
        DontDestroyOnLoad (gameObject);

    }  else if (estadojuego != this)
    {
        Destroy (gameObject);
    }
}

// Use this for initialization
void Start ()
{
    cargar ();
}

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

}

public void guardar ()
{
    BinaryFormatter bf = new BinaryFormatter ();
    FileStream file = File.Create (rutaArchivo);

    datosAguardar datos = new datosAguardar ();

    datos.puntuacionMaxima = puntuacionMaxima;

    bf.Serialize (file, datos);

    file.Close ();
}

void cargar ()
{
    if (File.Exists (rutaArchivo))
    {
        BinaryFormatter bf = new BinaryFormatter ();
        FileStream file = File.Open (rutaArchivo,FileMode.Open);

        datosAguardar datos = (datosAguardar)bf.Deserialize (file);

        puntuacionMaxima = datos.puntuacionMaxima;

        file.Close ();
    }  else
    {
        puntuacionMaxima = 0;
    }
}

[Serializable]
//definiendo la clase
class datosAguardar  //: ISerializable

{
    //propiedades de la clase
    public int puntuacionMaxima ;
    //metodo de la clase
    //constructor de la clase
    public datosAguardar (int puntuacionMaxima) // : base (puntuacionMaxima)
    {

        this.puntuacionMaxima = puntuacionMaxima  ;
    }

}

```

This is the constructor

```
[Serializable]
//definiendo la clase
class datosAguardar  //: ISerializable

{
    //propiedades de la clase
    public int puntuacionMaxima ;
    //metodo de la clase
    //constructor de la clase
    public datosAguardar (int puntuacionMaxima) // : base (puntuacionMaxima)
    {

        this.puntuacionMaxima = puntuacionMaxima  ;
    }

}

```

# Answer
The datosAguardar class only has a contructor that takes 1 argument:

```
public datosAguardar (int puntuacionMaxima)

```

so you either need to supply that argument, e.g.

```
datosAguardar datos = new datosAguardar (5);

```

or define another constructor that takes no arguments, e.g.:

```
public datosAguardar ()
{

    this.puntuacionMaxima = 7;
}

```

or give the parameter in the existing constructor a default value, e.g.:

```
public datosAguardar (int puntuacionMaxima = 8)
{

    this.puntuacionMaxima = puntuacionMaxima;
}

```
> 1 votes

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


title: Altering pixel value in an SDL2 texture

text:
# Question
Title: Altering pixel value in an SDL2 texture
Alright, I have spent a lot of time on this one, so I need some help. I like the ability to draw pixels directly to the screen, sometimes I do this to trace the path of objects for debugging etc. In SDL 1.2 you could do something sort of like this :

```
//make screen
SDL_Surface * screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
//make surface
SDL_Surface * pSurface = SDL_CreateRGBSurface( SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
//get the pixels
Uint32 * pixels = (Uint32 *)pSurface->pixels;
//set a pixel to red
pixels[ x + ( y * pSurface->w ) ] = SDL_MapRGB(pSurface->format, 255, 0, 0);
//blit to screen
SDL_Rect offset = {0,0,0,0};
SDL_BlitSurface( pSurface, NULL, screen, &offset );

```

This would result in a red pixel being displayed, you could make a simple line across the screen with a loop. Now SDL2 is really blowing my mind at the moment, here is what I've got:

```
//setup
window = SDL_CreateWindow("test",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,SCREEN_WIDTH, SCREEN_HEIGHT,SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor(renderer, 32, 32, 32, 255);
//make surface and texture
SDL_Surface * pSurface = SDL_CreateRGBSurface( 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
SDL_Texture * pTexture = SDL_CreateTexture( renderer,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_STREAMING,SCREEN_WIDTH,SCREEN_HEIGHT);
//from texture into surface
SDL_LockTexture(pTexture, NULL, &pSurface->pixels, &pSurface->pitch);
//get the pixels
Uint32 * pixels = (Uint32 *)pSurface->pixels;
//set a pixel to red
pixels[ x + ( y * pSurface->w ) ] = SDL_MapRGB(pSurface->format, 255, 0, 0);
//surface back to texture?
SDL_UnlockTexture(pTexture);
//clear the screen, then copy the texture to framebuffer, then update
SDL_RenderClear( renderer );
SDL_Rect renderQuad = {0,0,0,0};
SDL_RenderCopy( renderer, source, clip, &renderQuad );
SDL_RenderPresent(renderer);

```

This does nothing, except to fill the screen with the RenderDrawColor. What am I doing wrong..?

# Answer
> 4 votes
If you use the SDL2 Renderer, say goodbye to the idea of accessing pixels directly. Of course, it *is* possible but everytime you do this you "download" the pixel from your graphics card and then have to push it up again.

I suggest that you do all pixel manipulation *before* in a `SDL_Surface` and load the result as texture into you graphics card OR use OpenGL complete.

# Answer
> 0 votes
You should read the SDL 1.2 to 2.0 Migration Guide, you still can access pixels but they should be in System memory surface as seem you are trying to do. But, Why you are locking the texture? You shoudn't access texture memory directly, in general accessing GPU memory has low performance. You should work with SDL\_Surface all time then use `SDL_UpdateTexture(sdlTexture, NULL, pSurface->pixels, pSurface->pitch);` when your drawing is done, and finally call `SDL_RenderCopy(renderer, pTexture, NULL, NULL);`

Read the section "If your game wants to do both" in the Migration Guide.

# Answer
> 0 votes
The problem is in a way you use `SDL_LockTexture()`. You use it completely wrongly, you somehow assume you can pass a surface buffer there, which is not the case. Instead, this function fills the passed pointer to point to its own internal buffer, and as the result, the surface's pointer is being messed up in your code.

As was already pointed, you could use `SDL_UpdateTexture()` to copy from surface to texture, but for this you need `SDL_TEXTUREACCESS_STATIC`, while your code uses `SDL_TEXTUREACCESS_STREAMING`. For this texture type the surface is not needed at all, as you can draw directly the the streaming texture, which is also much faster than messing with the drawing surface:

```
void *pixels;
int pitch;
SDL_PixelFormat *fmt;
Uint32 format = SDL_GetWindowPixelFormat(window);
fmt = SDL_AllocFormat(format);
SDL_LockTexture(pTexture, NULL, &pixels, &pitch);
((Uint32*)pixels)[ x + ( y * SCREEN_WIDTH ) ] = SDL_MapRGB(fmt, 255, 0, 0);
SDL_UnlockTexture(pTexture);
SDL_FreeFormat(fmt);

```

# Answer
> 0 votes
There's more than one way to manipulate pixels, lines, rectangles, etc. with SDL2 and one of the easiest, and not so fast, ways to do that is to use texture and renderer.

You need to create renderer and then texture with access SDL\_TEXTUREACCESS\_TARGET. Once that's done, you can use renderer to draw pixels and other (supported) graphics primitives, like this:

```
// app window size
int width = 800;
int height = 600;
SDL_Window *window = SDL_CreateWindow( "Window Title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL );
SDL_Renderer *renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );
SDL_Texture *DrawingTexture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height );

// clear all pixels in the drawing texture with given color
SDL_Color color = {0, 0, 0, 0}; // black
SDL_SetRenderTarget(renderer, DrawingTexture);
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_RenderClear(renderer);
SDL_SetRenderTarget(renderer, NULL);

// draw one pixel
SDL_SetRenderTarget(renderer, DrawingTexture);
SDL_Color pcolor = {0, 255, 0, 0};
SDL_SetRenderDrawColor(renderer, pcolor.r, pcolor.g, pcolor.b, pcolor.a);
SDL_RenderDrawPoint(renderer, x, y);
// this sets renderer back to default target (the window)
SDL_SetRenderTarget(renderer, NULL);

// draw multiple pixels: (100, 110), (10, 50), (14, 22)
SDL_SetRenderTarget(renderer, DrawingTexture);
SDL_SetRenderDrawColor(renderer, pcolor.r, pcolor.g, pcolor.b, pcolor.a);
SDL_Point points[3] = {{100, 110}, {10, 50}, {14, 22}};
SDL_RenderDrawPoints(renderer, points, 3);
SDL_SetRenderTarget(renderer, NULL);

```

Of course, you should call SDL\_SetRenderTarget() once and then use SDL\_SetRenderDrawColor() and SDL\_RenderDrawXXX() function(s) as many times as needed, followed at the end with call to SDL\_SetRenderTarget(renderer, NULL).

---
Tags: c++, sdl
---


title: Change parent object on instantiation

text:
# Question
Title: Change parent object on instantiation
I'm making a game in which I have different weapons. One of them is a hand grenade. Well, the question is:

I made an animation with mecanim (I don't know if is the correct way) with the grenade being is a child of the main character. Then, the animation is correct (the grenade goes to high scale and I have the false sensation that is going up, to the camera).

The problem is that this grenade is attached to the character, and when I move the character, the grenade moves with him. I need the grenade to not be linked to the character when it's launched. And when I instantiate a new grenade, I need this animation playing.

I don't know if I explained the situation well, but this is the idea, an animated grenade launching when the player press the shoot button... what is the best way to do this?

# Answer
For me it should be done in this way:

1. What we need:

* A throw point - a Transform attached to mode's palm of hand
    * Throw animation
    * (Option A ) A event that will be fired during the throw animation, at the moment that the grenade should leave player's hand / (Option B) Or the infomation about how much time it will take from the beginning of the throw animation to the moment when grenade should leave.
2. How we do it:

**Option A**:
In the function (let's call it ThrowGrenade, in class Player), you play Player's throw animation. Make another function called OnGrenadeLeave which will be called from animation (information about how to set up an animation event should be easily found on google ). In this function, the first thing we do is detach the grenade from Player's hand, just use grenade's transform.SetParrent() so set new parent for it (just simple null, it will not have parent object). Next we play animation on the grenade.

**Option B**
We declare function ThrowGrenade as a coroutine, which will do the followings: play Player's throw animation -\> WaitForSeconds (timeTillGrenadeLeaves) -\> detach grenade -\> play grenade's animation.

In game, you just call ThrowGrenade, and that's it.
> 3 votes

# Answer
This is the code I used to make the shoot of the grenade. It works, but now, I'm thinking when I need to destroy the object on collision, is possible that I will need to put de newShoot variable out of the function, or create an array or something similar. I will think this problem on few days.

```
function ShootGrenade()
{
  var newShoot : GameObject;
  newShoot = Instantiate(grenade, lauchingPoint.transform);
  newShoot.transform.SetParent(null);
  newShoot.SetActive(true);
  newShoot.transform.FindChild("grenade_sprite").GetComponent.<Animator> ().Play("Grenade"+grenadeNumber);
}

```

"GrenadeNumber" is the number of animation to play: grenade1 shoots to up, 2 to front, and 3 to front but more far. The number is assigned pressing more or less time the shoot button. Grenade parent is deactivated, and I active it when I create a new one.
> 1 votes

---
Tags: unity, animation, objects
---


# Question
Title: How do I perform an Iris Wipe transition, using C++ in SDL 2.0?
How do I perform image masking/clipping using an arbitrary shape like a circle?

I want to do an Iris Wipe transition, similar to in the movies. By Iris transition, I mean the circle transition effect where it starts with a small circle, and zoomed in to reveal the scene.

How do I accomplish it in SDL 2.0 with C++?

# Answer
Start by creating an image that acts as the mask part.

Next, pick the on-screen location where you want the center of the circle be. Let's call that point `(X, Y)`. So, what you want to do, is gradually increase the size of the circle, and center it around the point you picked. You also want to fill the rest of the screen with black, and only render the game below the mask image. (Note that the circle part of the mask should be transparent.)

So, the program flow would go as follows:

1. At the start of your frame, clear the screen with black (you probably already do this).
2. Calculate the size of your mask texture. Basically you would just declare a variable `int size = 0;`, and increment that each frame by a fitting amount. You would then use this value to calculate the destination rectangle for the sprite. It would be something like `SDL_Rect dest = {X - size / 2, Y - size / 2, size, size};`.
3. Now that you have the destination rectangle calculated, before rendering your actual game objects, call `SDL_RenderSetClipRect(renderer, &dest);`. This assures that nothing is rendered outside of the (square) circle texture area. That way everything outside of the texture should stay black.
4. Finally, simply render your mask texture onto the screen: `SDL_RenderCopy(renderer, maskTexture, NULL, &dest);`.
5. As a last step, you probably need to figure out when the effect has finished. This might be a little tricky, but basically you just want to calculate when your screen "box" fits perfectly inside your circle. That shouldn't be too tricky, as you could probably get away by just checking if all the corners of your screen are within the circle.
> 0 votes

---
Tags: c++, graphics, graphics-programming, sdl2
---


title: C++ Independent Objects?

text:
# Question
Title: C++ Independent Objects?
before I started C++ I digged around in ActionScript3 for a while. The first thing I've noticed is that you apparently have to call all your objects/game-characters individually and tell them to `update()` for example.

My first thought was to sort them into arrays/vectors and do for-loops for efficiency since I don't know about C++ events yet but I'm curious what you guys are doing!

Can you use **Recursive** functions inside the class to make it work independently?

**Let's say I'd want to animate a tree with a spritesheet.** Would I have to call the tree's `update()` every frame or can I tell the object to get stuck in a Recursive loop and handle the animations itself?

# Answer
Well, you *could* use a separate thread to execute an object's update function in a loop, but **that's a really bad idea**. Not only will performance suffer when a system executes more threads than it has CPU cores (thread switches are expensive), but also because it leads to bugs.

Adobe Flash executes the update-function of all objects at a controlled point of the application where the state of the rendering system is consistent. But with C++ timers and threads you would have no control over *when* that update is executed. When you have bad luck, one object reads data which another object is currently writing and reads a weird inconsistent state. This is called a *race condition* and leads to bugs which happen extremely rarely and seemingly at random, making them impossible to reproduce and debug. There are ways to deal with this, like semaphores, mutexes or critical sections, but they have their own pitfalls, like deadlocks.

Multithreading in C++ is a very advanced concept full of non-obvious problems. As a beginner you are well-advised to leave your hands off of it for now and write your game completely single-threaded.

The normal solution is to have a main thread which alternates between calling a global `update()` function and a global `render()` function. The global `update()` would then call the update-function of every object in the game in a for-loop. There are two ways to structure this main loop. Which one you pick is a rather religious question which is further elaborated on in the question "When should I use a fixed or variable time step?".
> 2 votes

---
Tags: c++, software-engineering, game-loop
---


title: Inelastic ball collision

text:
# Question
Title: Inelastic ball collision
I'm trying to implement basic inelastic ball collision.

The example on the link above is for one dimension. It explains that it's the same for 2D but where the velocities are the components in the direction of the normal in the point of collision. I have tried calculating these components by projecting on the normal vector, and then calculating the new velocities. But then I got stuck. How do I get the new velocity vectors? My attempt below does not produce any good result. Can you help me out? (The two balls are intersecting in one common point when I run the code below)

UPDATE: I have edited the code now so that the two last lines is more correct I think. The thing is I have to combine the new velocity vector component with the old velocity vector component that was first subtracted in the projection operation, to get the complete new velocity vector. Now the animation looks a lot better. I still get occasional ball merging and popping but that could be some other part of my code thats wrong.

```
var m = this.Mass + other.Mass;
// normal in the point of collision
var n = (this.Position - other.Position).Normalized;
// velocity component perpendicular to the tangent in the point of collision for ball A
var ua = (float)(this.Velocity.Magnitude * Math.Cos(this.Velocity.Angle(n)));
// velocity component perpendicular to the tangent in the point of collision for ball B
var ub = (float)(other.Velocity.Magnitude * Math.Cos(other.Velocity.Angle(n)));
// the new velocity for ball A
var va = (0.9f * other.Mass * (ub - ua) + this.Mass * ua + other.Mass * ub) / m;
// the new velocity for ball B
var vb = (0.9f * this.Mass * (ua - ub) + this.Mass * ua + other.Mass * ub) / m;

// the new velocity vector for ball A
this.Velocity -= n * (ua - va);

// the new velocity vector for ball B
other.Velocity -= n * (ub - vb);

```

# Answer
From a physical point of view, you need to apply not only the law conservation of energy (with actually a little dissipation represented by the restituctuon factor), but also the conservation of momentum.

Energy this case is the kinetic one, mv^2/2 for each body. Momentum is mv/2 for each body.

See this physics webpage for more detail:

https://isaacphysics.org/concepts/cp\_collisions
> 1 votes

# Answer
Here's a function for the change in momentum and it works in 1D, 2D, 3D, you name it!

```
// Applies momentum with the given object
public void ApplyImpulse(PhysObj objHit, Vector2 n)
{
    // Calculate change in momentum
    Vector2 pHat = (((Vector2.Dot((v - objHit.v), n)) / (1f / M + 1f / objHit.M)) * (1f + E)) * n;

    // Calculate final velocities
    v = v - (pHat / M);
    objHit.v = objHit.v + (pHat / objHit.M);
}

```

Here it is in mathematical notation:

\\$p=(1+e)\frac{(v\_1-v\_2)\cdot n}{\frac{1}{m\_1}+\frac{1}{m\_2}}\*n \\$

Also note that * is the component product not the dot product. Produces a vector like so:

a * b = (a.x * b.x, a.y * b.y)

Oh and n is the normal at the point of contact. That is:

And e is the elasticity. In the range of \[0, 1\]
> 0 votes

---
Tags: physics, collision-resolution
---


title: Problem with Diffuse Lighting

text:
# Question
Title: Problem with Diffuse Lighting
So I am currently implementing Diffuse & Ambient Lighting based off this tutorial: https://www.braynzarsoft.net/viewtutorial/q16390-simple-lighting

I think I have implemented everything correctly, so the Ambient & Diffuse Light should work correctly but I just get Ambient Light. Can someone help me fix this? Here is my code.

**HEADER.H**

```
#pragma once

#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600

// include the basic windows header files and the Direct3D header files
#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
#include <DirectXMath.h>

using namespace DirectX;

// include the Direct3D Library file
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")

// global declarations
IDXGISwapChain *swapchain;             // the pointer to the swap chain interface
ID3D11Device *dev;                     // the pointer to our Direct3D device interface
ID3D11DeviceContext *devcon;           // the pointer to our Direct3D device context
ID3D11RenderTargetView *backbuffer;    // the pointer to our back buffer
ID3D11Buffer* squareIndexBuffer;
ID3D11Buffer* squareVertBuffer;
ID3D11VertexShader* VS;
ID3D11PixelShader* PS;
ID3D10Blob* VS_Buffer;
ID3D10Blob* PS_Buffer;
ID3D11InputLayout* vertLayout;
ID3D11Texture2D* pDepthStencil;
ID3D11DepthStencilView* pDSV;
ID3D11Buffer* cbPerObjectBuffer;
ID3D11Buffer* cbPerFrameBuffer;
ID3D11ShaderResourceView* CubesTexture;
ID3D11SamplerState* CubesTexSamplerState;

XMMATRIX WVP;
XMMATRIX World;
XMMATRIX camView;
XMMATRIX camProjection;

XMVECTOR camPosition;
XMVECTOR camTarget;
XMVECTOR camUp;

XMMATRIX cube1World;
XMMATRIX cube2World;

XMMATRIX Rotation;
XMMATRIX Scale;
XMMATRIX Translation;
float rot = 0.01f;
// function prototypes
void InitD3D(HWND hWnd);    // sets up and initializes Direct3D
void RenderFrame(void);     // renders a single frame
void CleanD3D(void);        // closes Direct3D and releases memory
void InitScene(void);
void UpdateScene(void);

D3D11_INPUT_ELEMENT_DESC layout[] =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};

UINT numElements = ARRAYSIZE(layout);

struct cbPerObject
{
    XMMATRIX WVP;
    XMMATRIX World;
};

struct Vertex
{
    Vertex() {}
    Vertex(float x, float y, float z, float u, float v, float nx, float ny, float nz)
        : pos(x, y, z), texCoord(u, v), normal(nx, ny, nz){}
    XMFLOAT3 pos;
    XMFLOAT2 texCoord;
    XMFLOAT3 normal;
};

struct Light
{
    Light()
    {
        ZeroMemory(this, sizeof(Light));
    }
    XMFLOAT3 dir;
    float pad;
    XMFLOAT4 ambient;
    XMFLOAT4 diffuse;
};

Light light;

struct cbPerFrame
{
    Light  light;
};

cbPerFrame constbuffPerFrame;

```

**MAIN.CPP**

```
#include "Header.h"

// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
    HWND hWnd;
    WNDCLASSEX wc;

    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = L"WindowClass";

    RegisterClassEx(&wc);

    RECT wr = { 0, 0, 800, 600 };
    AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);

    hWnd = CreateWindowEx(NULL,
        L"WindowClass",
        L"Eagle Engine (Alpha)",
        WS_OVERLAPPEDWINDOW,
        SCREEN_WIDTH,
        SCREEN_HEIGHT,
        wr.right - wr.left,
        wr.bottom - wr.top,
        NULL,
        NULL,
        hInstance,
        NULL);

    ShowWindow(hWnd, nCmdShow);

    // set up and initialize Direct3D
    InitD3D(hWnd);

    // enter the main loop:

    MSG msg;

    while (TRUE)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);

            if (msg.message == WM_QUIT)
                break;
        }

        RenderFrame();
    }

    // clean up DirectX and COM
    CleanD3D();

    return msg.wParam;
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_DESTROY:
    {
        PostQuitMessage(0);
        return 0;
    } break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

cbPerObject cbPerObj;

// this function initializes and prepares Direct3D for use
void InitD3D(HWND hWnd)
{
    // create a struct to hold information about the swap chain
    DXGI_SWAP_CHAIN_DESC scd;

    // clear out the struct for use
    ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

    HRESULT hr = S_OK;

    // fill the swap chain description struct
    scd.BufferCount = 2;                                    // one back buffer
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;     // use 32-bit color
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;      // how swap chain is to be used
    scd.OutputWindow = hWnd;                                // the window to be used
    scd.SampleDesc.Count = 8;                               // how many multisamples
    scd.SampleDesc.Quality = 1;
    scd.Windowed = TRUE;
    scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;     // allow full-screen switching// windowed/full-screen mode
                                                            // create a device, device context and swap chain using the information in the scd struct

    hr = D3D11CreateDeviceAndSwapChain(NULL,
        D3D_DRIVER_TYPE_HARDWARE,
        NULL,
        NULL,
        NULL,
        NULL,
        D3D11_SDK_VERSION,
        &scd,
        &swapchain,
        &dev,
        NULL,
        &devcon);

    // get the address of the back buffer
    ID3D11Texture2D *pBackBuffer;
    swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

    // use the back buffer address to create the render target
    dev->CreateRenderTargetView(pBackBuffer, NULL, &backbuffer);
    pBackBuffer->Release();

    // set the render target as the back buffer
    devcon->OMSetRenderTargets(1, &backbuffer, NULL);

    ID3D11Texture2D* pDepthStencil = NULL;
    D3D11_TEXTURE2D_DESC descDepth;
    descDepth.Width = SCREEN_WIDTH;
    descDepth.Height = SCREEN_HEIGHT;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_R32_TYPELESS;
    descDepth.SampleDesc.Count = scd.SampleDesc.Count;
    descDepth.SampleDesc.Quality = scd.SampleDesc.Quality;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    hr = dev->CreateTexture2D(&descDepth, NULL, &pDepthStencil);

    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
    descDSV.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
    descDSV.Texture2D.MipSlice = 0;

    dev->CreateTexture2D(&descDepth, NULL, &pDepthStencil);

    // Create the depth stencil view
    ID3D11DepthStencilView* pDSV;
    hr = dev->CreateDepthStencilView(pDepthStencil, // Depth stencil texture
        &descDSV, // Depth stencil desc
        &pDSV);  // [out] Depth stencil view

    devcon->OMSetRenderTargets(1, &backbuffer, pDSV);

    // Set the viewport
    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = SCREEN_WIDTH;
    viewport.Height = SCREEN_HEIGHT;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;

    devcon->RSSetViewports(1, &viewport);

    //Create the buffer to send to the cbuffer in effect file
    D3D11_BUFFER_DESC cbbd;
    ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));

    cbbd.Usage = D3D11_USAGE_DEFAULT;
    cbbd.ByteWidth = sizeof(cbPerObject);
    cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbbd.CPUAccessFlags = 0;
    cbbd.MiscFlags = 0;

    dev->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);

    ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));

    cbbd.Usage = D3D11_USAGE_DEFAULT;
    cbbd.ByteWidth = sizeof(cbPerFrame);
    cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbbd.CPUAccessFlags = 0;
    cbbd.MiscFlags = 0;

    dev->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer);

    //Camera information
    camPosition = XMVectorSet(-5.0f, 3.0f, -5.0f, 0.0f); //Position X,Y,Z
    camTarget = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);   //Rotation X,Y,Z
    camUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

    //Set the View matrix
    camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);

    //Set the Projection matrix
    camProjection = XMMatrixPerspectiveFovLH(0.4f*3.14f, (float)SCREEN_WIDTH/SCREEN_HEIGHT , 1.0f, 1000.0f);

    D3DX11CreateShaderResourceViewFromFile(dev, L"braynzar.jpg", NULL, NULL, &CubesTexture, NULL);

    D3D11_SAMPLER_DESC sampDesc;
    ZeroMemory(&sampDesc, sizeof(sampDesc));
    sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sampDesc.MinLOD = 0;
    sampDesc.MaxLOD = D3D11_FLOAT32_MAX;

    dev->CreateSamplerState(&sampDesc, &CubesTexSamplerState);
    InitScene();
    UpdateScene();
}

// this is the function used to render a single frame
void RenderFrame(void)
{
    //Clear our backbuffer
    float bgColor[4] = { (0.0f, 0.0f, 0.0f, 0.0f) };
    devcon->ClearRenderTargetView(backbuffer, bgColor);

    //Refresh the Depth/Stencil view
    devcon->ClearDepthStencilView(pDSV, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

    constbuffPerFrame.light = light;
    devcon->UpdateSubresource(cbPerFrameBuffer, 0, NULL, &constbuffPerFrame, 0, 0);
    devcon->PSSetConstantBuffers(0, 1, &cbPerFrameBuffer);

    ///////////////**************new**************////////////////////
    //Set the WVP matrix and send it to the constant buffer in effect file
    WVP = cube1World * camView * camProjection;
    cbPerObj.WVP = XMMatrixTranspose(WVP);
    devcon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
    devcon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
    devcon->PSSetShaderResources(0, 1, &CubesTexture);
    devcon->PSSetSamplers(0, 1, &CubesTexSamplerState);

    //Draw the first cube
    devcon->DrawIndexed(36, 0, 0);

    WVP = cube2World * camView * camProjection;
    cbPerObj.WVP = XMMatrixTranspose(WVP);
    devcon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
    devcon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
    devcon->PSSetShaderResources(0, 1, &CubesTexture);
    devcon->PSSetSamplers(0, 1, &CubesTexSamplerState);

    //Draw the second cube
    devcon->DrawIndexed(36, 0, 0);
    ///////////////**************new**************////////////////////

    //Present the backbuffer to the screen
    swapchain->Present(0, 0);
};

// this is the function that cleans up Direct3D and COM
void CleanD3D(void)
{
    swapchain->SetFullscreenState(FALSE, NULL);    // switch to windowed mode

    // close and release all existing COM objects
    swapchain->Release();
    dev->Release();
    backbuffer->Release();
    devcon->Release();
    squareIndexBuffer->Release();
    squareVertBuffer->Release();
    VS->Release();
    PS->Release();
    VS_Buffer->Release();
    PS_Buffer->Release();
    vertLayout->Release();
    cbPerObjectBuffer->Release();
    cbPerFrameBuffer->Release();
}

void InitScene()
{
    //Compile Shaders from shader file
    D3DX11CompileFromFile(L"Effects.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);
    D3DX11CompileFromFile(L"Effects.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);

    //Create the Shader Objects
    dev->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
    dev->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);

    //Set Vertex and Pixel Shaders
    devcon->VSSetShader(VS, 0, 0);
    devcon->PSSetShader(PS, 0, 0);

    light.dir = XMFLOAT3(0.25f, 1.0f, 1.0f);
    light.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
    light.diffuse = XMFLOAT4(1.0f, 1.0f, 2.0f, 5.0f);

    //Create the vertex buffer
    Vertex v[] =
    {
        // Front Face
        Vertex(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f,-1.0f, -1.0f, -1.0f),
        Vertex(-1.0f,  1.0f, -1.0f, 0.0f, 0.0f,-1.0f,  1.0f, -1.0f),
        Vertex(1.0f,  1.0f, -1.0f, 1.0f, 0.0f, 1.0f,  1.0f, -1.0f),
        Vertex(1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f),

        // Back Face
        Vertex(-1.0f, -1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f, 1.0f),
        Vertex(1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f),
        Vertex(1.0f,  1.0f, 1.0f, 0.0f, 0.0f, 1.0f,  1.0f, 1.0f),
        Vertex(-1.0f,  1.0f, 1.0f, 1.0f, 0.0f,-1.0f,  1.0f, 1.0f),

        // Top Face
        Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 1.0f,-1.0f, 1.0f, -1.0f),
        Vertex(-1.0f, 1.0f,  1.0f, 0.0f, 0.0f,-1.0f, 1.0f,  1.0f),
        Vertex(1.0f, 1.0f,  1.0f, 1.0f, 0.0f, 1.0f, 1.0f,  1.0f),
        Vertex(1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f),

        // Bottom Face
        Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f,-1.0f, -1.0f, -1.0f),
        Vertex(1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f),
        Vertex(1.0f, -1.0f,  1.0f, 0.0f, 0.0f, 1.0f, -1.0f,  1.0f),
        Vertex(-1.0f, -1.0f,  1.0f, 1.0f, 0.0f,-1.0f, -1.0f,  1.0f),

        // Left Face
        Vertex(-1.0f, -1.0f,  1.0f, 0.0f, 1.0f,-1.0f, -1.0f,  1.0f),
        Vertex(-1.0f,  1.0f,  1.0f, 0.0f, 0.0f,-1.0f,  1.0f,  1.0f),
        Vertex(-1.0f,  1.0f, -1.0f, 1.0f, 0.0f,-1.0f,  1.0f, -1.0f),
        Vertex(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f,-1.0f, -1.0f, -1.0f),

        // Right Face
        Vertex(1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f),
        Vertex(1.0f,  1.0f, -1.0f, 0.0f, 0.0f, 1.0f,  1.0f, -1.0f),
        Vertex(1.0f,  1.0f,  1.0f, 1.0f, 0.0f, 1.0f,  1.0f,  1.0f),
        Vertex(1.0f, -1.0f,  1.0f, 1.0f, 1.0f, 1.0f, -1.0f,  1.0f),
    };

    DWORD indices[] =
    {
        // Front Face
        0,  1,  2,
        0,  2,  3,

        // Back Face
        4,  5,  6,
        4,  6,  7,

        // Top Face
        8,  9, 10,
        8, 10, 11,

        // Bottom Face
        12, 13, 14,
        12, 14, 15,

        // Left Face
        16, 17, 18,
        16, 18, 19,

        // Right Face
        20, 21, 22,
        20, 22, 23
    };

    D3D11_BUFFER_DESC indexBufferDesc;
    ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));

    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(DWORD) * 12 * 3;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA iinitData;

    iinitData.pSysMem = indices;
    dev->CreateBuffer(&indexBufferDesc, &iinitData, &squareIndexBuffer);

    devcon->IASetIndexBuffer(squareIndexBuffer, DXGI_FORMAT_R32_UINT, 0);

    D3D11_BUFFER_DESC vertexBufferDesc;
    ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));

    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(Vertex) * 24;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vertexBufferDesc.MiscFlags = 0;

    D3D11_SUBRESOURCE_DATA vertexBufferData;

    ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
    vertexBufferData.pSysMem = v;
    dev->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &squareVertBuffer);

    //Set the vertex buffer
    UINT stride = sizeof(Vertex);
    UINT offset = 0;
    devcon->IASetVertexBuffers(0, 1, &squareVertBuffer, &stride, &offset);

    //Create the Input Layout
    dev->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),
        VS_Buffer->GetBufferSize(), &vertLayout);

    //Set the Input Layout
    devcon->IASetInputLayout(vertLayout);

    //Set Primitive Topology
    devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}

void UpdateScene()
{
    //Reset cube1World
    cube1World = XMMatrixIdentity();

    Translation = XMMatrixTranslation(0.0f, 0.0f, 4.0f);

    //Define cube2's world space matrix
    Scale = XMMatrixScaling(1.3f, 1.3f, 1.3f);

    //Set cube1's world space using the transformations
    cube1World = Translation;

    //Reset cube2World
    cube2World = XMMatrixIdentity();

    //Set cube2's world space matrix
    cube2World = Scale;
}

```

**EFFECTS.FX**

```
struct Light
{
    float3 dir;
    float4 ambient;
    float4 diffuse;
};

cbuffer cbPerFrame
{
    Light light;
};

cbuffer cbPerObject
{
    float4x4 WVP;
    float4x4 World;
};

Texture2D ObjTexture;
SamplerState ObjSamplerState;

struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float2 TexCoord : TEXCOORD;
    float3 normal : NORMAL;
};

VS_OUTPUT VS(float4 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL)
{
    VS_OUTPUT output;

    output.Pos = mul(inPos, WVP);

    output.normal = mul(normal, World);

    output.TexCoord = inTexCoord;

    return output;
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 diffuse = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float3 finalColor;

    finalColor = diffuse * light.ambient;
    finalColor += saturate(dot(light.dir, input.normal) * light.diffuse * diffuse);

    return float4(finalColor, diffuse.a);
}

```

# Answer
So @vtastek spotted that I hadn't set the world matrix for World in my .FX file which meant I had been multiplying my Normals by an Empty matrix.

```
output.normal = mul(normal, World);

```

Basically what solved my problem was setting the World matrix in my main.cpp to

```
cbPerObj.World = XMMatrixTranspose(cube1World);

```

Well spotted vtastek. Man that Diffuse Lighting is looking good ;)
> 0 votes

# Answer
You should add lighting info (specular, ambient, diffuse), then multiply with color. Try this:

```
finalColor = diffuse;
finalColor *= saturate(dot(input.normal, -light.dir)) * light.diffuse + light.ambient;

```
> 1 votes

---
Tags: shaders, directx, hlsl, lighting
---


# Question
Title: Finding when shapes overlap and lines intersect but exclude points/edges
I've been looking for a c# algorithm to help determine if shapes and lines intersect but want to exclude boundary overlaps. Here's an example:

My true problem is finding if polygons intersect but exclude boundary overlaps. I broke down the problem to look at the individual lines of that polygon and check each line segment from the shape1 against each line segment from shape2.

A: Is this an efficient/correct way to do the checking?

B: How do I ignore when they are on the boundary as illustrated above?

Here's some code I found here \- I've been testing for line segments but it fails on fig 2, when the end point of the 2nd line segment finishes on the end point of the 1st segment.

```
private bool DoesLineIntersect(Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2)
{
    float denom = ((end1.x - start1.x) * (end2.y - start2.y)) - ((end1.y - start1.y) * (end2.x - start2.x));

    //  AB & CD are parallel
    if (denom == 0)
        return false;

    float numer = ((start1.y - start2.y) * (end2.x - start2.x)) - ((start1.x - start2.x) * (end2.y - start2.y));

    float r = numer / denom;

    float numer2 = ((start1.y - start2.y) * (end1.x - start1.x)) - ((start1.x - start2.x) * (end1.y - start1.y));

    float s = numer2 / denom;

    if ((r < 0 || r > 1) || (s < 0 || s > 1))
        return false;

    return true;
}

```

# Answer
> 1 votes
You need to change your final check to also check for equality. So change the line

```
if ((r < 0 || r > 1) || (s < 0 || s > 1))

```

to

```
if ((r <= 0 || r >= 1) || (s <= 0 || s >= 1))

```

---
Tags: unity, c#, mathematics, geometry
---


title: Make a 2d top down game with round map

text:
# Question
Title: Make a 2d top down game with round map
Currently, I am making a top down game using Unity. Here is the problem that I’m trying to solve: The player in my game is always centered on the screen, and the since the map is rounded, the agents controlled by AI must acts and be shown base on the distance of the round map. Here is the sketch for the better explanation.

I want to ask for a good way to design and implementing the above task.

And here is my approach for this task:

* I split the map into 4 areas (could be smaller and more in number).
* Each of the 4 areas will have its corresponding area outside of the map area (The outside map areas are trigger boxes).
* When the area that is covered by the main camera has its parts out of the map area, these outside parts will active the trigger boxes that are overlapped by them.
* When a trigger box is activated, all the agents in its corresponding area inside the map will be moved temporally to the trigger box area. This can be done just by adding the difference between the trigger area position and the inside map area that the agent is staying to the agent’s position.
* When the area that is covered by the main camera no longer overlap the trigger box, all the agent will move back to its corresponding position inside the map. This process is done by reversing the moving out process.

Here is the sketch for this.

And the flawless come when there are agents with the flocking or forming formation behavior that requires the agents to have connections with others. When an agent is moved out of it actual position, the other agents in the formation will lose their connection with the moved agent (Like the distance between them suddenly becomes large). I think that this could be somehow solved by storing the actual position of the agent and marking it as moved, but it may be too computational cost, or having too many cases.

I tried to think of a different approach, that the map border is a circle, and to show the round view is just needed to take the symmetric through the center of the map. However, the circular border shows a bad animation when the agents try to move through the border. (I don't have enough reputation attach image about the flocking behavior problem and the circular approach, so you have to imagine it)

If you can solve the problems that I mentioned above or have a different approach, please show me. Thank you.

# Answer
> 1 votes
I am not really understanding how you are implementing your wrapping world rendering. Here is a way to render wrapping worlds.

First, you would get a Start and End X and Y positions of your camera view. The idea is to grab all tiles that are currently in your view, and process/render them.

Going through these values, you run a modulos operation on them in order to wrap the values inside of the game world:

```
for (int x = startx; x <= endx; x += 1)
{
    for (int y = starty; y >= endy; y -= 1)
    {
        int nx = Helper.Mod (x, World.Width);
        int ny = Helper.Mod (y, World.Height);

        TileData tile = World.GetTile (nx, ny);
        tile.Refresh();
    }
}

```

The Mod is a slight modification, to account for proper wrapping in both directions:

```
public static int Mod(int x, int m)
{
    int r = x % m;
    return r < 0 ? r + m : r;
}

```

Reposition the tiles using this Mod technique, and they will render at the right position. It doesn't matter if you go in the negative X,Y coordinate area, as this modulos operation will always normalize to your map size.

This method of course, requires you to have a dynamic way to position your Tile objects. I would highly suggest the use of a Tile Pool here.

---
Tags: unity, 2d, game-design, architecture
---


# Question
Title: What kind of data structure to use for planetary populations?
I am in the process of building out the prototype for my space strategy game, which is focused on empire building type gameplay.

One of the most important elements of the game are the various planets and the population groups on them. I have looked at Unity and Amazon Lumberyard before settling on Unreal Engine 4 to build the prototype on, but I am not sure what the best way to store information about the populations and planets are.

For now, planets are a class of object and store their characteristics as variables (no issue there). The problem arises with the populations, as each distinct group of population will have unique characteristics (i.e. species traits, faction alignment, education level) and game objects that they have possession of (weapons, armor, industrial machinery, trade goods).

What would be the most efficient way to tie the objects owned by the population to them, and to tie the population group to their planet of residence, such that I could compute things like:

*For Faction X, on Planet Y, what is the product of their population's (Education x Industrial Machinery x Planet Mineral Rating)?*

I considered implementing Population as a struct stored inside the Planet class, but that seemed problematic if I needed to move the population to a transport ship and then to a different planet, or add new groups of population during runtime.

# Answer
Potentially, a planet may need to host more than one population. Your Planet class could use a linkedList of Population instances.

Let's assume you choose a Singly LinkedList

Relocating a population from a planet would simply involve:

* locating the population instance in the linked list (fast) \[^1\]
* removing the population instance from the source planet's linked list (fast)
* inserting the population to front of the destination planet's linked list (fast)

*\[^1\]: If a planet can have many populations, then the search will be fast if you use a map to track the location of a population instance in the linked list to avoid having to traverse the whole Linkedlist in the worst case. If a planet has a small maximum number of inhabitant populations, you probably won't need the map.*

Alternatives: Planet class has member array (or vector) of **pointers** to its populations. In this case migration can be made to be fast (you're simply moving a pointer to a new array/vector), but if the array size is exceeded you'll have to bear the cost of the growing vector or expanding the array.

Further, if you don't mind having holes in the array or vector, removing a population from the planet can be done quickly. However, if holes are undesired then you'll bear the cost of shifting the array elements to cover the holes.

Other options probably exist, but these might be simple enough to meet your needs

Finally, if your populations know which planet/ship they reside on, then you can update this following a change i.e.

```
class Population{
    Location* currentLoc;
    void migrate(Location* destination){
        bool isMigrated=currentLoc->migrate(this,destination);
        if(isMigrated) currentLoc=destination;
}

class Planet{
    forward_list<Population> inhabitants;
    bool migrate(Population* populationA,Location* destination){
 //removes populationA from the linkedlist of inhabitant populations and
 //inserts it into the linkedlist of the destination planet or ship
//returns true if migration successful
     }
}

```
> 1 votes

# Answer
I've got a 4X game of my own; it's written in C#, so forgive my ignorance of C++ terminology!

What I use is a `Dictionary<Race, long>` as a property of my colonies to store the population of those colonies. I don't know what you call a `Dictionary` in C++, but in Java it's called a `Map`, in Python it's called a `dict`, and in Perl it's called a `hash`.

The `Race` object stores all the characteristics of any particular race of aliens on the colonies, such as their mining aptitude and their reproduction rate.

If I want to put some population on a transport ship, then, I simply deduct it from the associated dictionary entry on the colony, and add it to the dictionary entry of the transport ship's population storage in its cargo (first checking that the dictionary entry exists and creating it if necessary).
> 0 votes

---
Tags: c++, data-structure, unreal-4, strategy
---


# Question
Title: What are the alternatives to OpenGL arrays for deferred rendering?
I'm trying to build a deferred rendering technique in an OpenGL engine, but I can't figure how I could get more than the limit of 32 lights.

I use an array in my shader, feed light properties into this array then loop through it and compute lightning, but I can't get more than 32 items into my array.

What is a better alternative to this?

# Answer
You can send all the data that you want in a texture.
> 2 votes

# Answer
You use multiple passes and additive blending to solve this.

Traditionally this performs better than using an array and looping over every light, because that approach involves branching and causes pressure on shader register and instruction counts - both of which will impact performance.

It also integrates better with shadows because when drawing shadows you're going to want to draw in the order shadow, light, shadow, light, etc. With the state and shader changes involved here you'll be doing multiple passes anyway.
> 0 votes

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


# Question
Title: Finding if 2 polygons intersect using clipper library
After realising my code was pretty inefficient at checking for polygon overlaps, I've turned to a mentioned library Clipper but finding it difficult to know hot to use it for this operation.

I am using unity Vector2\[\] for my shape descriptions:

```
//Square
Vector2[] square = new Vector2[] {
    new Vector2(0,0),
    new Vector2(1,0),
    new Vector2(1,1),
    new Vector2(0,1)
};

```

I want to be able to do the above boolean comparison of 2 shapes. If anyone knows Clipper well, what methods can I use to do this check?

I've recently tried the following but the result is always true even when the test shapes are completely separate from each other:

```
public bool CheckForOverLaps(Vector2[] shape1, Vector2[] shape2) {

    List<IntPoint> shape1IntPoints = Vector2ArrayToListIntPoint (shape1);
    List<IntPoint> shape2IntPoints = Vector2ArrayToListIntPoint (shape2);

    List<List<IntPoint>> solution = new List<List<IntPoint>> ();

    c.AddPath (shape1IntPoints, PolyType.ptSubject, true);
    c.AddPath (shape2IntPoints, PolyType.ptClip, true);
    c.Execute (ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero);
    return solution.Count != 0;

}

private List<IntPoint> Vector2ArrayToListIntPoint (Vector2[] shape) {

    List<IntPoint> list = new List<IntPoint> ();

    foreach (Vector2 v in shape) {

        list.Add (new IntPoint (v.x, v.y));

    }

    return list;

}

```

And the tests:

```
    //Square
    Vector2[] square = new Vector2[] {
        new Vector2(0,0),
        new Vector2(2,0),
        new Vector2(2,2),
        new Vector2(0,2)
    };

    //Square
    Vector2[] square2 = new Vector2[] {
        new Vector2 (1, 1),
        new Vector2 (3, 1),
        new Vector2 (3, 3),
        new Vector2 (1, 3)
    };

    //Square
    Vector2[] square3 = new Vector2[] {
        new Vector2 (2, 0),
        new Vector2 (4, 0),
        new Vector2 (4, 2),
        new Vector2 (2, 2)
    };

    //Square
    Vector2[] square4 = new Vector2[] {
        new Vector2 (4, 0),
        new Vector2 (6, 0),
        new Vector2 (6, 2),
        new Vector2 (4, 2)
    };

    Assert.IsTrue(tc.CheckForOverLaps(square,square2));
    Assert.IsFalse(tc.CheckForOverLaps(square,square3));
    Assert.IsFalse(tc.CheckForOverLaps(square,square4));

```

Many thanks.

# Answer
I got this in the end.. I had to Clear() out clipper for the next tests to work. Converted everything to IntPoint before hand to improve efficiency.

```
public bool CheckForOverLaps(List<IntPoint> shape1, List<IntPoint> shape2) {

    clipper.Clear();
    solution.Clear ();

    clipper.AddPath (shape1, PolyType.ptSubject, true);
    clipper.AddPath (shape2, PolyType.ptClip, true);
    clipper.Execute (ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero);

    return solution.Count != 0;
}

```
> 1 votes

---
Tags: unity, c#, mathematics, geometry, clipping
---