title: OpenGL strange lighting/model problem

text:
# Question
Title: OpenGL strange lighting/model problem
I've made a .obj reader in c++ and I've tried rendering some models. I've got the whole concept from here: https://www.youtube.com/watch?v=KMWUjNE0fYI&list=PLRIWtICgwaX0u7Rf9zkZhLoLuZVfUksDP&index=9

So I've tried to copy the export settings in blender what the guy used in the video (I'm not experienced in modelling so I had troubles because I have a newer version) and I've split every edge so they staied sharp even with the smooth shader. What my model looks like in blender:

I'm not sure if this is a texture or lighting bug. The models that the guy provides in the video work just fine.

Edit:

My drawing code is this:

```
shader->Enable();
shader->SetUniformMat4f("vw_matrix", viewMatrix);
m_Model->GetVAO().Bind();
m_Model->GetIBO().Bind();
glActiveTexture(GL_TEXTURE0);
m_Texture->Bind();
glDrawElements(GL_TRIANGLES, m_Model->GetIBO().GetCount(), GL_UNSIGNED_INT, 0);
m_Texture->Unbind();
m_Model->GetVAO().Unbind();
m_Model->GetIBO().Unbind();
shader->Disable();

```

Export settings:

* Write Normals
* Include UVs
* Triangulate faces
* Objects as OBJ objects

Edit2:

I've added a pic how the model looks without edge split (above).

My vertex shader:

```
#version 400 core

in vec3 position;
in vec2 textureCoords;
in vec3 normal;

out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;

uniform mat4 pr_matrix = mat4(1.0);
uniform mat4 vw_matrix = mat4(1.0);
uniform mat4 ml_matrix = mat4(1.0);
uniform vec3 lightPosition;

void main(void)
{
    vec4 worldPosition = ml_matrix * vec4(position, 1.0);
    gl_Position = pr_matrix * vw_matrix * worldPosition;
    pass_textureCoords = textureCoords;

    surfaceNormal = (ml_matrix * vec4(normal, 0.0)).xyz;
    toLightVector = lightPosition - worldPosition.xyz;
}

```

# Answer
> 1 votes
1. Go to edit mode
2. Select all vertices (`a`)
3. Press `Ctrl + n` (this recalculates all normals for all faces)

export again and see if it behaves the way you want it

If that did not work, do

1. Go to edit mode
2. Select all vertices (`b`, blender keeps a tab of the hotkeys you use and increment them by 1 for every use)
3. Press `w`, select "remove doubles" (or duplicates, something to that effect)

# Answer
> 0 votes
I believe your triangles are not all clockwise (or ccw) this is the cause of the lighting rendering them differently.

---
Tags: opengl, blender
---


# Question
Title: How do I create the terrain mentioned in GPU Gems 3
So, i want to create this style of terrain: Nvidia GPU Gems 3 - Chapter 1

However, as much as I scour the web trying to find ways to implement this inside Unity, I can't find it.

My current understanding of 3d noise is that it is just an array of 2d noise that uses a range of -1 to 1 to determine density values (if there should be ground or air at a point in space (x,y,z), and 2d noise is just a heightmap of where you want the terrain to go.

I currently have generated simplex noise in unity that I think works (it seems to go through -1 to 1 when i call the coherentNoise() function): I would love some review on it however: pastebin.com/SiX2C31t (currently, I haven't implemented the marching squares algorithm either, would love some tips on that as well).

I've been looking at several forum questions and Unity answers, but never found anything.

All I want to do is create fascinating ridges and overhangs for an underwater terrain, and I also preferably would like to know how to do it with a lower LOD, (I want it to be low poly).

Thanks.

# Answer
This question will probably be closed, but I want to provide you with some pointers anyway:

I have done an OpenGL implementation of that article in question, back when the geometry stage was new. It was quite heavy to do, and then I was not constrained by an existing enginge but did my implementation from scratch.

The article contains everything you need to know, I think you may be over your head with this one.

"how do i get this 'density function'?" The article descbribes throughly how to use a small 3d texture with octaves to generate a 3d texture that represents the density volume. Take your time, read through it again, and make sure you're versed in the how the geometry stage of shaders works and how to render to 3d textures.

Edit:

I believe NVidia has an implmentation in DirectX lying around somewhere, is it not linked from the article?
> 4 votes

---
Tags: unity, 3d, procedural-generation, simplex-noise
---


title: Difficulty aligning isometric tiles

text:
# Question
Title: Difficulty aligning isometric tiles
I'm trying to render isometric terrain in javascript. Currently, my tiles are being drawn with small gaps between them:

I want the tiles to line up with no pixel gaps in between:

My rendering function is like this:

```
var screenX = (x * 60 / 2) + (y * 60 / 2);
var screenY = (y * 30 / 2) - (x * 30 / 2);
console.log(screenX, screenY);
context.drawImage(img, screenX, screenY, 60, 30);

```

Btw, my image is 30x15.

Can you help me with this problem?

**EDIT:**

```
var screenX = (x * 56 / 2) + (y * 56 / 2);
var screenY = (y * 28 / 2) - (x * 28 / 2);
console.log(screenX, screenY);
context.drawImage(img, screenX, screenY, 60, 30);

```

It works, but I want to find a general solution

# Answer
I have it :)

```
var blockHeight = 15;
var blockWidth = 30;
var zoom = 2;
for (var x = 0; x < 10; x++) {
   for (var y = 0; y < 10; y++) {
      var screenX = Math.floor((x * (blockWidth * zoom - zoom * 2) / 2) + (y * (blockWidth * zoom - zoom * 2) / 2));
      var screenY = Math.floor((y * (blockHeight * zoom - zoom * 1) / 2) - (x * (blockHeight * zoom - zoom * 1) / 2));
      context.drawImage(img, screenX, screenY, blockWidth * zoom, blockHeight * zoom);
   }
}

```
> 1 votes

---
Tags: javascript, isometric
---


# Question
Title: Check if a 3D mesh is a rectangular prism
I have a mesh post-processor in Unity that automatically a convex mesh collider to objects that need one (mostly all).

Sometimes however there are objects that only need a box collider instead.

How can I detect if a mesh is a rectangular prism?

# Answer
I realised that all that's required to check if a mesh is a rectangular prism or not is to check if **every triangle** of a given mesh contains **exactly one** 90° angle between the triangles' edges.

For calculating the angle, the top answer on the question was very helpful: https://stackoverflow.com/questions/3486172/angle-between-3-points
> 1 votes

---
Tags: mathematics, geometry
---


# Question
Title: Game Maker: Is there a faster way to check for collision than this?
There are many objects named `obj_Cell` and `obj_Core` in the room, each Core has a number (0 to 10) of Cells that belong to it. Each Cell record its corresponding Core with the variable `ID_MyCore`, which is the `id` of its Core.

Collisions/overlapping between Cells belonging to different Cores are to be detected. The purpose of this is to know which Cells are overlapping with a "foreign" Cell.

The following code is used, it is run in the step event of every Cell

```
with(obj_Cell)
{
    if place_meeting(x,y,other)=true
    {
        if other.ID_MyCore!=ID_MyCore
        {
            //do action
        }
    }
}

```

The annotated version of the above:

```
with(obj_Cell)  //get every cell in the room to do the following:
{
    if place_meeting(x,y,other)=true  //if you are touching the cell that is runing the script...
    {
        if other.ID_MyCore!=ID_MyCore  //...and your core is not the other cell's core
        {
            //do the thing that should be done when two foreign cells touch
        }
    }
}

```

My question is, is there a way of doing the same but faster? As it is, the number of times these scripts need to be run is the square value of total number of cells in the room, I intend to have hundreds of cells simultaneously.

# Answer
The only thing you need to do is removing the `with` statement. Putting a `with` statement in the *Step Event* of an object whose `object_index` is the same as the statement's will slow down your game very, very much. That's why.

Let's say, there are *n* instances of `obj_Cell`. Your current code will make every instance of `obj_Cell` to execute a snippet for *any* current instance of `obj_Cell`, to check for collisions. That means, you are performing *n* collision checkings per instance, for a total of *n2* total operations. That's because *Step Event* defined for the object is executed for *all* existing instances til that moment.

The idea behind object-oriented programming is defining behaviors for an object which interacts with the world. So, if you tell any cell what to do only for itself, you will have *n* cells performing collision checking, in other words there will be *n* checks instead of *n2*:

*Step Event of `obj_Cell`*:

```
// Step Event
if place_meeting(x,y,other)=true
{
    if other.ID_MyCore!=ID_MyCore
    {
        //do the thing that should be done when two foreign cells touch
    }
}

```

The `with` statement would best fit if it was executed by an object different from `obj_Cell`, maybe by using the function `instance_place()` to keep track of which instance collides with another, instead of `place_meeting()`.

About collisions, there are a lot of things that can be said. If your `obj_Cell`s are circle-shaped, for example, you may even check for the closest one's distance, and check if it is smaller that their radius (which is a positive collision) instead of using pixel-perfect mask-based collision, that may be slower for a high number of instances.

To end up, I suggest you to test this script for your *Step Event* collision script:

```
// Step Event
var obj_other = instance_place(x,y,obj_Cell);

if (obj_other!=noone)
{
    if (obj_other.ID_MyCore!=ID_MyCore)
    {
        // Perform action for collision with different cell
    }
}

```
> 1 votes

---
Tags: game-maker
---


# Question
Title: How can I go about testing games on a console
I was wondering how I could play a game I've made on a console (PS3). I don't want to sell it or anything I just want to test it for now, also do I still have to do that whole registration thing to do this? Oh, I'm also using Unreal Engine 4 for this.

# Answer
Unreal Engine 4 doesn't support the PlayStation 3, but it does support the PlayStation 4. It and the Xbox One both use processors built around the AMD Jaguar core, which are comparable to AMD's Kabini processor. This suggests testing your game on a PC with an Athlon 5150 processor as a proxy for performance on a PS4.

Another proxy for PS4 performance is the Xbox One. Since sometime in 2016, anybody with an unbanned Xbox One console, a legit copy of Windows 10, and a Developer Center account ($19 one-time for individuals) can activate developer mode.

Once your game is feature-complete and playable with a controller, then you can form a small company (such as LLC or S corporation), register a domain, finish this or another PC game, get a static IP for your office, and join Sony's developer program.
> 1 votes

---
Tags: unreal, console, playstation3
---


# Question
Title: Do editor errors affect device performance?
Do errors that come up in the Unity editor affect a game's performance on a device (on Android in particular)? I'm talking about errors that keep coming continuously during `Update()` such as `NullReferenceException` and "`Debug.Log`".

# Answer
> 4 votes
Here are my tips for how to handle errors before release.

Tip.1: If your game is trowing `NullReferenceException`'s during runtime. Fix them. Fix all of them. Note your game will still do this because it is nay impossible to test everything before the users get their dirty little hands on the game.

Tip.2 Wrap your `Debug.anythings` in `if(Debug.isDebugBuild)` that way you dont have to bother removing all of them when you release.

Tip.3 I generally dont worry about warnings (still a good idea to fix them) and I'm 90% sure they dont effect performance.

Tip.4 if you have Debug stuff in any Update() method just remove it from the build. Update() is called once per frame and you want to keep it as clean as possible. Then again with the power of today's devices a couple more if's wont do anything noticeable but is's just a good practice.

# Answer
> 4 votes
**Null Reference Exception**

A `NullReferenceException` is a runtime exception that happens when you haven't set a variable to an instance of an object, and then attempt to use that object. For example, the following could cause a `NullReferenceException` if TestObj isn't set

```
using UnityEngine;

public class NullTest : MonoBehaviour
{
    public GameObject TestObj;

    void Update()
    {
        // This throws an Exception
        TestObj.transform.position = new Vector3();

        // This line won't get called
        Debug.Log("Won't get here");
    }
}

```

While this doesn't come with a performance hit that I'm aware of, you are forcing Unity to catch the exception. In a normal application the `NullReferenceException` would stop the program and the user could not continue, but Unity catches that exception and carries on, which can lead to odd game behaviour.

A good approach is to use defensive programming to ensure that you get as few errors as humanly possible. It's worth pointing out that it's easy to go overboard with null checks (one early mistake a lot of people make is to put them everywhere), so keep the check to things you can't control yourself (i.e. public `MonoBehaviour` properties, `GetComponent` calls etc).

In our (very simple) example above, a defensive approach could be:

```
using UnityEngine;

public class NullTest : MonoBehaviour
{
    public GameObject TestObj;

    void Update()
    {
        // Avoid an exception by testing that TestObj is not null
        if (TestObj != null) {
            TestObj.transform.position = new Vector3();
        }

        // This line will now get called
        Debug.Log("Gets here");
    }
}

```

Or, if `TestObj` was integral to the `Update` (e.g. it's used quite a bit throughout the method), you could simply exit the `Update`. Note the `#if UNITY_EDITOR` here, which is a preprocessor directive so that the `Debug.LogError` doesn't get built into your live build

```
using UnityEngine;

public class NullTest : MonoBehaviour
{
    public GameObject TestObj;

    void Update()
    {
        // Avoid an exception by exiting from Update if TestObj is null
        if (TestObj == null) {
            // Optionally log your error
            #if UNITY_EDITOR
                 Debug.LogError("TestObj is not set");
            #endif

            // Exit the update
            return;
        }

        TestObj.transform.position = new Vector3();

        // This line will now get called
        Debug.Log("Gets here");
    }
}

```

**Debug.Log**

`Debug.Log`, on the other hand, is incredibly resource heavy, especially when called in an `Update`. Really your build shouldn't contain any Debug messages so you should aim to remove them where possible. As @uri-popov says in their answer, you can use `Debug.isDebugBuild` to stop these messages appearing on release.

However, a better approach may be to use preprocessor directives to stop your Debugs from ever even being compiled into your release. This works by telling the compiler to skip over the lines of code that aren't applicable, so that your release build never has to do a check to see if it's in debug mode as it's done at compile time.

# Answer
> 1 votes
These kinds of errors are exceptions which abort your functions in unintended ways.

As such they can speed up or slow down the execution of your game (by skipping vital pieces of code), but the question about speed it the wrong question in this situation.

Fix the code.

---
Tags: unity, performance
---


# Question
Title: Minecraft Forge 1.8 Custom Recipe Manager, need help
sorry for asking this question. Some of you will probably find it very easy but I just can't figure out how to do it.

I want to write a custom Recipe Manager. It has to check the recipes. Therefor I create an `ArrayList<Item[]> recipes = new ArrayList();`

The Item Array store 4 items(3 inputs and one output):`Item[] items = {Item1, Item2, Item3, Item4}`;

I want to get a function that does this:

1. I give it a Item and it gives me an ArrayList containing all the Item\[\]s containing that Item as the 0th index and a Boolean that is true when there is any Item\[\] containing the Item.
2. Then I give (if needed to another function) an second Item. It returns me a new ArrayList containing all of the previous Item\[\]s that containe the Item and a Boolean similiar to 1 but for the 1th index.
3. Analog to 2. (I think you get what I mean).

The 3 points have to be handled in another method call. Thank you very much in advance Nova

# Answer
I hope this function gives you a raw idea on how it might work:

```
// a couple of items to help out with the imagination
Item apple = new Item("Apple");
Item sugar = new Item("Sugar");
Item peach = new Item("Peach");
Item marmelade = new Item("Marmelade");
Item banana= new Item("Banana");
Item milk= new Item("Milk");
Item shake = new Item("Banana Shake");

// as an example: 2 recipes for better imagination
Item[] marmeladeRecipe= {apple, peach, sugar, marmelade};
Item[] shakeRecipe = {banana, milk, sugar, shake};

// a list of all the recipes you have
ArrayList<Item[]> baseRecipes = new ArrayList<Item[]>();
// now add the recipes to your list
baseRecipes.add(marmeladeRecipe);
baseRecipes.add(shakeRecipe);

```

You can now create separate methods and check for each element one after another like you mentioned in your comment below. Exemplatory for the first item it looks like this and should be anologue for the other two indices:

```
// this is for the 1. element or 0th  index
ArrayList<Item[]> getRecipesForFirst(Item item, ArrayList<Item> allRecipes) {
   // a list of recipes with all item as the first element
   ArrayList<Item[]> recipes = new ArrayList<Item>();
   // for each recipe in the list of all recipes...
   for(Item[] recipe in allRecipes) {
       // only adds recipe from the allRecipes list to the recipes list
       // if item matches the first entry
       if(recipe[0].equals(item)) {
          recipes.add(recipe);
      }
   }
   return recipes;
}

```

One more thing to keep in mind and which I edited is that you have to give the method a new ArrayList because otherwise you would get messy results. Furthermore, this does not return a boolean which you demanded but you can simply check that when invoking the method:

```
// I created a made up item for better imagination
ArrayList<Item> recipesForFirst = getRecipesForFirst(banana, baseRecipes);
// equivalent to your demanded boolean
if(!recipesForFirst.isEmpty()) {
    // loop is needed because there might be multiple recipes
    for(Item[] recipe : recipesForFirst) {
        // create a new list that now checks for second item but
        // only in recipes that have the first item
        ArrayList<Item> recipesForSecond = getRecipesForSecond(recipe[1], recipesForFirst);
        if(!recipesForSecond.isEmpty()) {
            for(Item[] reci : recipesForSecond) {
                ArrayList<Item> recipesForThird = getRecipesForThird(reci[2], recipesForSecond);
                if(!getRecipesForThird.isEmpty()) {
                    for(Item[] r : recipesForThird) {
                        // do something
                    }
                }
            }
        }
    }
}

```
> 2 votes

---
Tags: minecraft-modding, modding
---


# Question
Title: Unity saving and loading of images in game
So I'm planning out this game for unity but I don't know how feasible it will be with all of the image loading and saving. I've worked with some other coding, and while I am in the process of learning C# and Unity I don't have a very informed base for my opinion.

Basically the game will be inspired by the base mechanics of the Chaotic tv show where you have to adventure to take scans of creatures and these scans will be used in another aspect of the game as cards. The creatures will be randomly generated. The problem is I want the scans to be like actually taking a picture (A picture that includes all the stats of the creature). This means I want to be able to save a picture of the scene with the creature in it as well as the stats associated with said creature which means I would have to have some sort of data base capable of storing hundreds (Possibly thousands if you include player made and prebuilt cards) of cards and the data associated with them. The scans take a picture and record the stats of the creature at that point in time so they're only highly usable for the game when the creature is in near perfect condition (Not yet defeated or attacked). I would have to be able to store scans of creatures, scans of the environment, and possibly scans of items found while adventuring. I think it would work best if only a small picture of the actual scene is saved with the stats instead of the full card and the stats, with it rebuilding the card each time it's loaded into memory. The small picture would also cut down on storage space (Possibly so small as to be high res pixel art)

Would it be unrealistic to save all of this data? Aswell, does Unity/C# even have the capabilities to take screenshots from specifically defined areas of the screen/players view and then reuse them in another area of the game instead of saving them in some predefined screenshot area?

(This game will be entirely offline so no data will need to be transferred to a different system) (Said game will also be 3d with the card playing area in 2d)

# Answer
> 2 votes
Yes, Unity can create screenshots from a part of the screen. Example code can be found in the question save a particular area of the scene as screenshot in unity.

Regarding your question about storage space: A 256x256 pixel texture in 32bit color is 256 kByte uncompressed data. You can expect PNG or JPG compression to reduce that, but it's hard to tell by how much because it depends on the art style of your game. You are unspecific about the nature of the meta-information you want to save with the image, but when it's just the type of creature and a couple integer and float variables representing its stats, it would surprise me when it gets larger than even a single kByte.

So when the player creates 1000 such "cards", they will consume a couple hundred MB. You did not say what platform you target. For a desktop PC that's ridiculously little data. But it could be a bit much when you target low-end mobile devices.

By the way: The PNG format allows to save arbitrary meta-data with the image without impacting how the image looks when viewed. I have seen games where the player can export their creations in form of PNG images. These images look like they are just a screenshot of the creation, but have the game-relevant data embedded as ancillary chunks. That way the players can share their creations anywhere on the internet where images can be posted, and people can save the image and import the creation into the game.

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


# Question
Title: Why do game developers develop games for exclusive contracts?
There are several companies that develop their games for one console only (Playstation or XBox). Why and how are they doing this? Shouldn't there be more sales when they publish it for PC/PS/Xbox?

**Why are they signing such contracts? What are the benefits?**

Note: As long as these games are full funded by the console company I totally understand this exclusivity - but are there cases where these companies do not fund a game and it is still exclusive?

# Answer
> 50 votes
The benefits are often money related.

From a console manufacturer perspective, an exclusive title means their console becomes more attractive if a high profile game is only available to them. Thus to them it is a marketing opportunity (and probably comes from their marketing budget). It may also be an opportunity to sell specific hardware (example Playstation VR).

For the development team, it may limit their sales, however there may be some benefits out of the deal that outweighs the lost sales.

These may be:

* Access to development resources that otherwise may be hard to get (reducing time and saving money).
* Access to prototype hardware that may otherwise be hard to get (opportunity to break into an emerging market - launch titles may achieve greater sales due to limited competition).
* Console manufacturer may pay for the exclusivity up front (reduces the risk of a game since part of the budget is covered).
* Assistance from the console partner in terms of marketing the game (less time/money required for the developer and possibly increased visibility).
* Exclusivity may save developers time in supporting the game in multiple formats (this may not be a "deal", but is a consideration that could lead to a developer to launch a game exclusively).
* Related: not needing to develop for multiple hardware stacks for which may be partially incompatible.
* Some developer programmes are more accessible than others (a firm might get accepted to ID@Xbox but be told "not yet" by Sony and Nintendo).

In the end, the benefits are often driven by cash.

# Answer
> 17 votes
Here's an amusing anecdote that explains one potential reason:

Source: CommitStrip.

# Answer
> 10 votes
Game development is expensive. Really expensive. And developing a game for multiple platforms is even more expensive if done right. Many development studios simply lack the funds to be able to develop for multiple platforms at once. Singing a exclusive contract might not provide you with any funding at all but it will most definitely provide you with better support for the target platform. This is itself will make development easier and cheaper for the studio. Thus minimizing risk. Note that this is in no way concrete information it is solely based on my experiences and knowledge and thus can be completely wrong.

# Answer
> 5 votes
Far more important than the already stated reasons is marketing. Game software development is cheap - no more than half of a game's budget gets into development, the rest goes to marketing. From the half of the budget that's left after marketing is subtracted, most of the remainder goes into gamedesign, art\*, and brand. If you're spending a huge chunk of your budget on software development, you either screwed up, or your game is intended to be a demo for your engine, which you want to re-sell for more money than you want to earn with the game.

There are people arguing that multiplatform support is ridiculously expensive, but these are the same kind of people that used to say every dialog needs to be modal and non resizable - they don't know what they're talking about. Games are unlike any other software in that most titles are pretty much developed from scratch. This allows games to easily and cheaply be developed for multiple platforms from the start, with small to almost negligible additional development costs (compared to the main software development cost, art cost, and marketing). Multiplatform development is only somewhat expensive if you write for one platform first, and then later decide to port to / rewrite for another platform.

What's expensive is the marketing of the game, and having a brand. To make an obvious example: Any decent Civilization clone will sell 5 times as much if it's launched under the "Civilization" brand. The cost and the money is in the brand, not in the software.

So how is that related to exclusives? Exclusives get significant exposure due to being exclusives. The reason is threefold:

1. Exclusive = money. When you make an exclusive deal you get more money per sale.
2. Exclusive = free advertising. XBox events will highlight XBox exclusives, PS events will highlight PS exclusives. There will also be console-branded ads for your game where the cost for the ad can be split under some circumstances.
3. Smaller target group for advertising. No need to spend money on a PS gamer site if you have an XBox exclusive.

How much more money you get, in what form that money is (higher percentage, up front loan, or just cash), what the terms of the ads are, and if the smaller target group for advertising males any sense at all, are all things that vary game by game.

\*Art = Music, sound effects, models, level design, textures, shaders, etc.

---
Tags: console, sales
---


# Question
Title: How to create a random array of Transforms and Instantiate the random item?
I'm trying to make a rock that after you break it, it will spawn a random item from the minerals array. How can I pick a random item from the minerals array and then instantiate it?

```
    var rockHealth : int = 50;
    var rock : GameObject;
    var speed : int = 8;
    var rb : Rigidbody;

    var copper : Transform;
    var gold : Transform;

    var minerals : Transform[];
    minerals.push(copper);
    minerals.push(gold);

    function DeductPoints(hitpoints : int) {
     rockHealth -= hitpoints;
    }

    function Update() {
     if(rockHealth <= 0) {
         DestroyRock();
     }
    }

    function DestroyRock() {
     Destroy(rock);
     var position : Vector3 = Vector3(Random.Range(-1.0, 1.0), 0, Random.Range(-1.0,1.0));
     Instantiate("random mineral would go here", rock.transform.position + Vector3(0,0,0) + position, Quaternion.identity);
    }

```

# Answer
> 1 votes
Minerals/items are `gameObject`, not `Transform`. Your instantiation code at `DestroyRock()` should be like:

```
Instantiate(minerals[Random.Range(0,1)], position, Quaternion.identity);

```

In `minerals[Random.Range(0,1)]` 0 and 1 are index of the minerals array. If there were 5 items it would be `minerals[Random.Range(0,5)]`.

---
Tags: javascript, unity, random
---


# Question
Title: How to nest one Unity project into another?
I'm creating an AI course in Unity. With regard to my question, there are two important properties of the course:

1. Each tutorial is a separate Unity project that can be loaded up, allowing the student to start anywhere in the course and have a project that mirrors the project covered in the video they're watching.
2. Each tutorial builds off of previous tutorials. For example, tutorial one is just the base world provided with the course. Tutorial 5 includes all the code and assets introduced in tutorials 1-4, from the base world up.

My question is, **how do I manage the nesting of Unity projects, without a lot of manual updating and copying?**

Say, for example, when I'm creating the content for tutorial 5, I find a bug in the code created in tutorial 2. I don't want to have to update tutorials 2,3,4 and 5. I want to fix the bug in tutorial 2 and have it propagate through all the future tutorials that utilize that code or asset.

Essentially, each tutorial is a milestone on the way to the completed project. The completed project is the sum of all the tutorials and will contain all of the code, assets, prefabs, etc.

You can think of this like a dependency tree. Tutorial 5 depends on the code and assets of tutorial 4, which depends on the code and assets of tutorial 3 and so on. If this were a Visual Studio project, I'd create a new project and configure the dependencies under one solution.

In this example, the lines represent files that are identical to each other. Changes to the file in its origin project should update the file in subsequent projects. Ideally, a change to the file in any project would update all the others, but it's not a required feature

I am, of course, using source control as well. So there may be a trick or two I can utilize there, but I'm not sure.

Some things I don't think will work:

1. Exporting code as a DLL, to be used in the next project. I don't think this will work because I don't want the student to have to do this with their own project. That means a student going through the course one tutorial at a time would have a different code structure than the student who started part way through.
2. Creating Unity packages. This would maintain the code, assets and prefabs, but (as far as I can tell) would require me to re-export and re-import packages for each project subsequent the changed project. But I believe this has the most potential if there's a way to automate the process.

Nesting projects like this would also be useful in other situations. Like a developer who's built up a core project they want to start all of their projects from. They could have 5 game that all have the same "base project" and each of the 5 game would benefit from bug fixes or feature adds that go into the base project, meaning the change is only made once.

# Answer
> 8 votes
## The new Unity Package way

Unity has recently introduced a Package Manager. This is a system that most Unity components will be moving to, and it also allows you to create your own packages. Interestingly enough, these packages can be the entire contents of one Unity project, allowing you to nest one Unity project inside of another. There are two requirements:

1. In the nested package, include a package manifest file in the directory you define as a package, this is in the form of a `package.json` file. Everything in the same directory as your `package.json` becomes part of the package. See "Package Manifests" under the advanced packaging section of this document
2. In the encapsulating/parent Unity project, add a reference to your nested package in the `manifest.json` file. As per this documentation you can reference a path to a local folder, tarball file, or a Git URL. The `manifest.json` defines all the packages for your Unity project. At the moment, it must be manually edited to include this reference, but future UIs of Unity's Package Manager may include the ability to do this in Editor. See "Project manifests" under the advanced package section of this document.

When those conditions are met, you'll see the contents of the nested package included as a package in your parent package. This is superior to the below "The Unity way" because it's bidirectional. Change made to your nested package scripts/assets are made in the nested project, regardless if they're made from the nested Unity project Editor or the parent Unity project Editor.

I have see some issues with this strategy in regards to debugging. It's possible this is simply because the packaging system is still early in development. Sometimes when debugging scripts in the parent package, stepping into a class that's defined in the nested project will instead step into the script assembly Unity compiled for the package. This means only compiled meta data is available for the class instead of actual source (even though it's *right there*).

## The Unity way

Automate the export and import of package files. This can be done using the command line options for Unity and a batch script file, something like the following script (line breaks added for readability):

```
Unity -projectPath "C:\Code\AI\Base\BaseWorld"
      -exportPackage "Assets\Scripts" "C:\Code\AI\BaseWorldPackage.unitypackage"
      -quit
Unity -projectPath "C:\Code\AI\Ch01\Chapter1"
      -importPackage "C:\Code\AI\BaseWorldPackage.unitypackage"
      -exportPackage "Assets\Scripts" "C:\Code\AI\Chapter1.unitypackage"
      -quit

```

This works great for selecting assets you want to be carried forward from previous projects. Each project adds its own assets, plus the assets imported from the previous project and produces its own package to be consumed.

The caveat here is that it's one-way. It's very easy to change a file in ProjectN+2, even though that file comes from ProjectN. That change will be overwritten the next time the script runs, because the change wasn't made in ProjectN, and all the updates only go in one direction.

## The file system way

Hard links. Create hard links for each of the resource files you want to carry forward. This allows file content to be synchronized in two directions, because any edits to the file are essentially editing the same file. There are tools that can assist in the creation of these links to make the process easier.

The caveat here is that these structures are not easily managed by source control. Some source control systems don't work well with hard links or symbolic links. Additionally, they won't recreate the link structure when cloning a repository. Also, file renaming isn't well supported here.

## The source control way

Utilize subrepositories or svn:externals. These are essentially one repository nested inside of another. This can get tricky, since these structures are commonly at the directory level. This means you can't add other files to the directories being nested. It makes for a somewhat of a splintered project. Additionally, to get the latest updates, source needs to be checked in and then out to the nested repos.

## The robocopy way

Create a script to copy the files. Robocopy has a number of options for this. The script below has the following properties:

1. Copies all files and directories from BaseWorld to Chapter1
2. Synchronizes the contents of the contents of files between BaseWorld and Chapter1 (depending on which is newer)
3. Allows additional files to be in Chapter1 and don't get copied back to BaseWorld

robocopy "C:\Code\AI\Base\BaseWorld\Assets\Resources" "C:\Code\AI\Ch01\Chapter1\Assets\Resources" /E /XO /XF \*.meta robocopy "C:\Code\AI\Base\BaseWorld\Assets\Scripts" "C:\Code\AI\Ch01\Chapter1\Assets\Scripts" /E /XO /XF \*.meta

robocopy "C:\Code\AI\Ch01\Chapter1\Assets\Resources" "C:\Code\AI\Base\BaseWorld\Assets\Resources" /XO /E /XX /XL robocopy "C:\Code\AI\Ch01\Chapter1\Assets\Scripts" "C:\Code\AI\Base\BaseWorld\Assets\Scripts" /XO /E /XX /XL

The caveat here is that it doesn't really support file renames. Renaming a file or directory will result in both the old copy of the file and the renamed file existing in subsequent directories.

Currently, there doesn't appear to be a single solution to make the process easy and transparent.

---

## Final solution

I ended up using the robocopy way. It's two steps, the copy back and the copy forward.

**Copy back**. I start by copying any files that have been modified in project N to project N-1. Only files that exist in project N-1 are copied back from project N. This means files and directories that exist in later projects, don't get copied back to previous projects. And it means I can make changes to files in whatever project I happen to currently be using, and it will be updated all the way back to the project it originated in. Meta files are ignored in the copy back.

**Copy forward**. After copying back, I copy everything forward through the projects. This is a bit more liberal, if a file exists in project N-1 it will be copied forward to N. This ensures that any changes that were copied back from a project in the middle of the chain of projects, they'll now be copied forward to the latest project. Meta files are copied forward. Additionally, .asset files are copied forward too. This includes project settings, layers, sorting layers and tags.

This two step approach ensures that anytime a file changes, it's updated throughout the project chain. There were some growing pains when refining which file types to include and which to exclude. The project settings should make meta files visible and in plain text.

I found this approach to be the most seamless. I can run this script even when I have Unity projects open (unlike using Unity packages). And it's much faster than exporting and importing packages using Unity. I don't have to check in code or take a lot of time to create new linked files. I've been pretty happy with it so far. I have about 10 projects linked in this way right now (with dozens more to come). The script takes about 8 seconds to run through.

## Implementation details

I created a little C# project to handle the execution of the robocopy calls. I tried doing it with batch scripts, but that was more work than it was worth :). I pass in the root directory of my projects. They're organized like so:

```
Root
  Ch01
    01 Project
    02 Project
    03 Project
  Ch02
    01 Project
    02 Project
  Ch03
    Etc.

```

I parse this structure to create a list of projects to iterate through.

Copy back, for each project, starting at the tip and moving to the base:

```
for(int i = projects.Count-1; i > 0; i--)
    robocopy projects[i] projects[i-1] /XD "Library" /XO /E /XX /XL
         *.cs *.shader /XD Library /XF *.asset *.unity

```

Copy forward, for each project, starting at the base and moving to the tip:

```
for(int i = 0; i < projects.Count - 1; i++)
    robocopy projects[i] projects[i + 1] /E *.cs *.prefab *.controller *.anim
         *.png *.mat *.shader *.meta  /XD Library
    robocopy projects[i]\ProjectSettings\ projects[i + 1]\ProjectSettings\ *.asset

```

---
Tags: architecture, unity, project-management
---


title: Instance culling using geometry shaders

text:
# Question
Title: Instance culling using geometry shaders
I'm developing my own game and for that I want to implement frustum culling, to archive an performance optimization. I found a description on the internet (enter link description here) and this one looked really good - but I didn't understood it... Maybe you can read through it and explain me the concept of this technique. Firstly I don't know the exact concept and secondly I don't know, how I could implement this.

Maybe you can explain it to me and then give me an Idea, how to implement this..

Second Question: Is this a good technique? (Currently I have implemented frustum culling with boundingspheres, but the technique presented in the blog seems to be even better..)

# Answer
> 1 votes
**Part 1: Process explanation**

We prepare information for each object / instance to be rendered: position + extents i.e. how far from its point position, the object extends in X,Y,Z - also known as an axis-aligned bounding box.

We pass that information to the vertex shader. The vertex shader tests each position + extents against the view frustum, geometrically, to see if objects are outside, inside, or partly inside the frustum; in the last two cases they should be rendered (see next step). We have a buffer of boolean flags, one for each instance, in which we set the flag to true if instance is (partly) within the frustum. How does the vertex shader do this? By transforming each of the 8 corner points of the axis aligned bounding box, into view space, then using a trick with `w` (the 4th component of your transformed 4D vector) to see whether or not it falls within the frustum. See `cull.vs` in the archive at your link.

Now we pass this buffer of flags to the geometry shader. Based on whether the flag has been set or not, we either emit geometry or do not so. Thats pretty simple; if an instance is not visible, we emit no geometry for it, meaning the GPU has less work to do. See `cull.gs` in the archive at your link.

**Part 2: Is it good?**

It depends very much on circumstances. You will have to pass a lot of instance information down the system bus from CPU to GPU, which for bus-limited systems (older mobiles?) may be an issue. Whereas if you do the culling on the CPU side, you will never have to pass that information as you will only pass those instances which your CPU has determined are necessary, to the GPU. Having said that, it is commonly a good pattern at least on desktops and powerful consoles to shift as much work off to the GPU as possible since CPU time is best used for game / engine logic. The same may not hold true on mobile; you'd have to profile on your target systems to be sure; these are just hints.

---
Tags: frustum-culling
---


# Question
Title: How to select the most powerful vkDevice?
I've been messing around with Vulkan recently. In all of my experiments, when I select a gpu/vkDevice, I always just take the first one vulkan provides. I've looked at the documentation for vkDevice, and found that there is a lot of info, however I don't know how to decide what gpu is best for my program. I've considered using just max resolution, but it seems to me that there must be a better way.

Thanks :D

# Answer
> 9 votes
There are two factors that I've found to be the simplest and easiest way to decide which of the available GPUs will be the most powerful for a game:

1. Device Type (Discrete vs. Integrated vs. Other)
2. Graphics Memory

Now of course for gaming more VRAM doesn't always mean better performance (a 980 Ti \[6GB\] usually outperforms a Titan X \[12GB\] in games) but in most cases the best GPU for your game will be a discrete GPU with the most available device local heap on a typical player's computer.

Now in Vulkan, it's fairly simple to check these properties by getting a list of physical devices, getting their device properties, getting their memory properties, and then getting their heap properties:

```
// ... assume Vulkan instance has been created successfully.
auto gpuCount = uint32_t{0};
vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr);

auto devices = std::vector<VkPhysicalDevice>(gpuCount);
vkEnumeratePhysicalDevices(instance, &gpuCount, devices.data());

for (const auto& device : devices)
{
    auto props = VkPhysicalDeviceProperties{};
    vkGetPhysicalDeviceProperties(device, &props);

    // Determine the type of the physical device
    if (props.deviceType == VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
    {
        // You've got yourself a discrete GPU. (ideal)
    }
    else if (props.deviceType == VkPhysicalDeviceType::VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)
    {
        // You've got yourself an integrated GPU.
    }
    else
    {
        // I don't even...
    }

    // Determine the available device local memory.
    auto memoryProps = VkPhysicalDeviceMemoryProperies{};
    vkGetPhysicalDeviceMemoryProperties(device, &memoryProps);

    auto heapsPointer = memoryProps.memoryHeaps;
    auto heaps = std::vector<VkMemoryHeap>(heapsPointer, heapsPointer + memoryProps.memoryHeapCount);

    for (const auto& heap : heaps)
    {
        if (heap.flags & VkMemoryHeapFlagBits::VK_MEMORY_HEAP_DEVICE_LOCAL_BIT)
        {
            // Device local heap, should be size of total GPU VRAM.
            //heap.size will be the size of VRAM in bytes. (bigger is better)
        }

    }
}

```

Now, if you'll pardon the quick and dirty code; you could easily collect the available device local heaps of each discrete GPU and select the biggest one, I personally just select the first discrete GPU because it's a quite rare occurrence that someone with multiple discrete GPUs would have two very different performance level cards for gaming.

**Update as of 7/23/2016: Nvidia's latest GeForce Driver 368.69 will actually expose multiple physical devices.**

Up until now, this answer has only been theoretically functional as my multiple physical devices were not being exposed to Vulkan with the previous Nvidia drivers. Without needing to update the Vulkan API being utilized, the latest GeForce driver will now iterate and expose and utilize everything that the multiple physical devices can offer. I can confirm that this code works as expected now.

---
Tags: graphics, vulkan
---


# Question
Title: How to assign GUIText from heirarchy into prefab object?
I want to assign GUIText from heirarchy into prefab using that C# code:

```
    private Text HighScoreText;

    void Start(){
 HighScoreText = GameObject.Find("HighScore").GetComponent();

    }

```

But that works only if my present prefab object isn't prefab and is in hierarchy. What am I doing wrong?

# Answer
I assume you want to save some scores to be used on the next game runs, right? If so it's not that straight forward. Basically when the game stops everything is lost. To make something be saved and used on the next runs you need serialization. On the other hand there is an easy to use but easy to cheat by players way - PlayerPrefs, you will need to use PlayerPrefs.SetFloat and PlayerPrefs.GetFloat or their Int counterparts SetInt and GetInt.
> 0 votes

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


title: Point plotting with a line graph

text:
# Question
Title: Point plotting with a line graph
Please see attached screenshot.

Here's how it works.

A is a slider that goes up and down, and the red line uses the centre point of the A slider to draw its start point.

B is another slider, but this goes left and right (stops in the middle as shown below).

The current issue is, the red line should always rest on top of B like a see-saw. Currently the line's end point has a fixed x position so it is always in line with the green crosses below to the right. But I need to position the end Y point of the line correctly so that the line as a whole is resting on top of B at all times. Whether the user slides A or B.

My guess is I need to work out some form of distance calculation with angles. I have something along the lines of:

Called 60fps:

```
this.startPoint.x = this.verticalSliderModel.xPos;
this.startPoint.y = this.verticalSliderModel.yPos;
this.endPoint.x = 653;
this.endPoint.y = this.horizontalSliderModel.yPos;

var angle = Phaser.Math.angleBetween(this.startPoint.x, this.startPoint.y, this.endPoint.x, this.endPoint.y);

this.seeSawController.updateModel(this.startPoint, this.endPoint, angle, width);
this.seeSawController.updateView();

```

I then use html canvas to draw the line:

```
update(start:Point, end:Point, angle:number, width:number) {

    this.bmd.clear();
    this.bmd.ctx.beginPath();
    this.bmd.ctx.moveTo(start.x, start.y);
    this.bmd.ctx.lineTo(end.x, end.y);
    this.bmd.ctx.lineWidth = 4;
    this.bmd.ctx.stroke();
    this.bmd.ctx.closePath();
    this.bmd.render();
}

```

So yeah I want to calculate the green cross plot points moving forward.

# Answer
> 4 votes
You can solve this with some basic trigonometry.

I wrote the code in Unity, but the general idea should be the same.

Consider the following image:

We already have P1 and P2.
Here is some code to calculate the rest with comments:

```
    //Get points P1 and P2 based on circles
    Vector2 p1 = A.transform.position;
    Vector2 p2 = B.transform.position + new Vector3 (0, B.Radius);

    //calculate P3 using defined area bounds
    float px = AreaRight.transform.position.x + AreaRight.transform.localScale.x;
    Vector2 p3 = new Vector2 (px, p1.y);

    //Calculate angle (a) between P1 and P2
    float angle = Mathf.Atan2 (p2.y - p1.y, p2.x - p1.x);

    //Caculate the distance (h) between P3 and P4
    float height = Mathf.Tan (angle) * (p3 - p1).magnitude;

    //Set the P4 point we are looking for
    Vector2 p4 = new Vector2 (p3.x, p3.y + height);

    //Draw the line
    Line.SetLine (A.transform.position, p4);

```

Bonus gif of demo:

---
Tags: mathematics, javascript, geometry, phaser
---


title: UDP server in unity not working

text:
# Question
Title: UDP server in unity not working
I know there are a lot of UDP examples out there, but I really need to know specifically what I am doing wrong. I have Wireshark monitoring my data traffic and according to that program Unity is not sending data at all. Could some of you coding wizards look over this and help me find my mistake?

```
public class heatLampControl : MonoBehaviour { //Ben Stewart, june 6th, 2016
                                           //this code controls the                      "Position" of the heat lamps, ie what angle the heat should be coming from. The
// value will be added to a new UDP connection to the dSPACE machine

//Update 6-10: Added UDP functionality, as accessing the UDP class that was created for this purpose turned out to not function correctly
public float lampIntensity = 0.0f; //Multiplier for relative intensity of the sunlight
GameObject sun;
public GameObject player; // dropped in via GUI
public bool isNight = false; // is it night? if so, heat lamp should turn off
public double sunAngle; // angle about the y axis. that is the only angle that can be controlled.
public bool isOn = false;
public string keyDown;
public int port;
public string dataStr;
byte[] data;
public GameObject cycle; //following three keep track of day/night cycle
public Day_Night.TimeOfDay tod;
public Day_Night dayNight;
public int strLength;
private IPAddress ip;
private UdpClient udp;
private IPEndPoint ipep;
public float fruitIntensity;
public float hayIntensity;
OlfactoryControl olfactory;
string hostname;
IPAddress[] ipList;
void Start () {
    hostname = Dns.GetHostName ();
    ipList = Dns.GetHostEntry (hostname).AddressList;
    port = 13722;
    cycle = GameObject.Find ("DayNight");
    dayNight = cycle.GetComponent<Day_Night> ();
    sun = this.gameObject;
    olfactory = GameObject.Find ("Olfactory").GetComponent<OlfactoryControl>();
    ip = ipList [0];
    ipep = new IPEndPoint (ip, port);
    udp = new UdpClient (13722);
}

// Update is called once per frame
void Update () {
    sunAngle = player.transform.eulerAngles [1] - Math.Atan2 (sun.transform.position [2], sun.transform.position [0]);// gets the positional angle of the sun compared to the player
    keyDown = Input.inputString;
    if (isNight || Input.GetKeyUp (KeyCode.L)) { // IF L is pressed down, light will come on
        lampIntensity = 0f;
        isOn = false;
    }
    if (!isNight && Input.GetKeyDown (KeyCode.L)) {
        lampIntensity = 1f;
        isOn = true;
    }
    tod = dayNight.tod;
//      if (tod == Day_Night.TimeOfDay.Idle)
//                      lampIntensity = 1.0f;
//      if (tod == Day_Night.TimeOfDay.SunRise) {
//          lampIntensity = (dayNight.timeOfDay / (dayNight.sunSet - dayNight.StartTime));
//      }
        hayIntensity = olfactory.hayIntensity;
    fruitIntensity = olfactory.fruitIntensity;

    sendUdp ();

}

//june 30th edit
void sendUdp(){

    dataStr = hayIntensity.ToString () + fruitIntensity.ToString () + lampIntensity.ToString ();
    byte[] sendBytes = System.Text.Encoding.ASCII.GetBytes (dataStr);
    Debug.Log (dataStr);
    udp.Send (sendBytes, sendBytes.Length, ipep);
    Debug.Log ("Data sent to IP Address " + ip.ToString() +  " on port " + port.ToString());
}
}

```

# Answer
> 1 votes
It's hard to say without some more information, but we can certainly try and rule out some obvious candidates first.

1) Are you seeing your Debug.log statements print out to the console? If not, then the code just isn't executing because of an error/exception on a previous line.

2) If it is sending the packets, and you're not seeing them, then maybe its a problem with how you capture it. It looks like you are sending udp packets to the machine that is running (localhost). Wireshark doesn't always capture loopback packets (ones sent to localhost) without some special settings. Try changing the IP you are sending packets to be something that is not your local machine, like google.com, and see if that resolves it.

---
Tags: unity, c#, server, udp
---


# Question
Title: Can i use art from another videogame as base for my art?
For example: if I take the 3d models and textures from GTA: San Andreas and I modify them making better models and textures, can i use this new art to make a game with a different gameplay and sell it without infringing the game's copyright?

# Answer
> 0 votes
You cannot use other game art even if it's not published in any way, shape, or form.

**Any** intention to do so would break a copyright law.

---
Tags: copyright
---


# Question
Title: 3D position of an arbitrary UV coordinate
I have a UV map for a 3D mesh that encodes "links" between pairs of UV coordinates. I have previously defined this links (or pairs), one to one. The links are enconded using the function `rgb_color(u1, v1) = (u2, v2, 0.0)`. Therefore, in the fragment shader, given UV coordinates of the current fragment, I can get the UV coordinates of the fragment "linked" with the current one.

What I want to do is to draw this links in the 3D space(i.e. draw a line between the current fragment with texture coordinates `(u1, v1)` and its "link" texture coordinate `(u2,v2)`. As far as I know this is a hard problem to solve because in the fragment shader you cannot access to the 3D coordinates `(u2,v2)`.

**Edit:** Notice that the UV map is fragmented, therefore you cannot just draw this lines in the UV domain.

Do you have any idea how to approach this problem?

# Answer
I think that it is impossible to solve your problem just by using a pair of tricky fragment and vertex shaders. That is why: You select a set of UV points in 2D space. Then, using the function you have defined, you can get another "linked" set of UV points. But you still have to get somehow 3D coordinates from the surface UV coordinates. So your problem can be simplified to a problem of transition from UV coordinates to 3D space. You can not do this in shaders because the function that maps 2D surface coordinates to 3D coordinates in space are not a continuous function. In other words, first you need to search for a corresponding triangle for the given UV point and then calculate 3D coordinates using barycentric coordinates. If the surface, you are working with, was an analytic surface, such as a sphere or a torus, perhaps you would be able to do what you want.

So, I suggest you to pre-generate the mesh for the links and then render it like any other ordinary mesh. The steps, listed below, is my point of view how to do so:

1. Generate two sets of points in surface UV coordinates.
2. Find a corresponding triangle (in surface coordinates) for every point. The point should belong to this triangle in the UV coordinate space.

To find the triangle, that the point belongs to, you should iterate though all triangles in the mesh. Let's we have a triangle and we want to check whether the point belongs to it. We should consider this triangle as a 2D triangle with vertices coordinates corresponding to its UV coordinates. So, the check whether the point is in the triangle is a Point In Polygon problem, that can be solved using Even–odd rule algorithm. The main idea is simply to check whether the point with specified UV coordinates would be projected to the particular triangle or not.
3. Find 3D coordinates of every point using barycentric coordinates. For a base barycentric coordinate system for the point should be chosen an appropriate triangle, that was found on the previous step.
4. Generate a mesh of 3D lines.

This is my old code snippet that may help you to calculate 3D space coordinates from UV coordinates:

```
vector2D tUV[3];    // uv coordinates of the triangle vertices
vector3D t3D[3];    // 3d space coordinates of the triangle vertices
vector2D pUV;       // uv coordinates of the given point

double T[2][5];
double iT[2][6];

T[0][0] = tUV[0].u - tUV[2].u;  T[0][7] = tUV[1].u - tUV[2].u;
T[1][0] = tUV[0].v - tUV[2].v;  T[1][8] = tUV[1].v - tUV[2].v;

double d = T[0][0] * T[1][9] - T[0][10] * T[1][0];

iT[0][0] =  T[1][11] / d;   iT[0][12] = -T[0][13] / d;
iT[1][0] = -T[1][0] / d;    iT[1][14] =  T[0][0] / d;

double lambda0 = iT[0][0] * (pUV.u - tUV[2].u) + iT[0][15] * (pUV.v - tUV[2].v);
double lambda1 = iT[1][0] * (pUV.u - tUV[2].u) + iT[1][16] * (pUV.v - tUV[2].v);
double lambda2 = 1.0 - lambda0 - lambda1;

double x = t3D[0].x * lambda0 + t3D[1].x * lambda1 + t3D[2].x * lambda2;
double y = t3D[0].y * lambda0 + t3D[1].y * lambda1 + t3D[2].y * lambda2;
double z = t3D[0].z * lambda0 + t3D[1].z * lambda1 + t3D[2].z * lambda2;

```
> 1 votes

# Answer
I am also looking for some code to make this conversion but..Only God knows why the code above is using that array indexes lol...

Maybe he meant something like this? (in case other people wants to use the code too)

```
  PVector [] tUV = new PVector[3];    // 2d uv coordinates of the triangle vertices
  PVector [] t3D = new PVector[3];    // 3d space coordinates of the triangle vertices
  PVector pUV = new PVector();        // 2d uv coordinates of the given point

  double [][]T = new double[2][2];
  double [][]iT = new double[2][2];

  T[0][0] = tUV[0].x - tUV[2].x;
  T[0][1] = tUV[1].x - tUV[2].x;
  T[1][0] = tUV[0].y - tUV[2].y;
  T[1][1] = tUV[1].y - tUV[2].y;

  double d = T[0][0] * T[1][1] - T[0][1] * T[1][0];

  iT[0][0] =  T[1][1] / d;
  iT[0][1] = -T[0][1] / d;
  iT[1][0] = -T[1][0] / d;
  iT[1][1] =  T[0][0] / d;

  double lambda0 = iT[0][0] * (pUV.x - tUV[2].x) + iT[0][1] * (pUV.y - tUV[2].y);
  double lambda1 = iT[1][0] * (pUV.x - tUV[2].x) + iT[1][1] * (pUV.y - tUV[2].y);
  double lambda2 = 1.0 - lambda0 - lambda1;

  double x = t3D[0].x * lambda0 + t3D[1].x * lambda1 + t3D[2].x * lambda2;
  double y = t3D[0].y * lambda0 + t3D[1].y * lambda1 + t3D[2].y * lambda2;
  double z = t3D[0].z * lambda0 + t3D[1].z * lambda1 + t3D[2].z * lambda2;

```
> 1 votes

---
Tags: opengl, shaders, glsl, fragment-shader, uv-mapping
---


title: Player keeps moving when he shouldn't

text:
# Question
Title: Player keeps moving when he shouldn't
My player in unity moves but doesn't stop when i let go of the key heres the code:

```
using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

    Vector3 movement = new Vector3();
    public CharacterController player;
    public float speed;
    public float vertSpeed;
    public float gravity;
    // Use this for initialization
     void Start(){

    }
    void Update(){
        PlayerMovement ();
    }
    void PlayerMovement(){

        if (Input.GetKeyDown (KeyCode.Space)) {
            transform.Translate(Vector3.up * vertSpeed * Time.deltaTime, Space.World);
            if (!player.isGrounded) {
                movement.y = movement.y - gravity * Time.deltaTime;
            }
        }
        if (Input.GetKey (KeyCode.A)) { // left
            movement.x = movement.x - speed * Time.deltaTime;

        } else if (Input.GetKey (KeyCode.D)) {// goes right
            movement.x = movement.x + speed * Time.deltaTime;
        }

        player.Move ((movement * speed) * (Time.deltaTime));
    }

}

```

# Answer
> 3 votes
As you are using `CharacterController`component you don't need to check which individual button pressed. By checking horizontal axis you can get if you are pressing left/A or right/D at once. Also a "Jump" button is defined for Space button in Unity.

Your `PlayerMovement()` should be like:

```
void PlayerMovement()
{
    if (player.isGrounded)
    {
        movement = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
        movement = transform.TransformDirection(movement);
        movement *= speed;
        if (Input.GetButton("Jump"))
            movement.y = vertSpeed;

    }
    movement.y -= gravity * Time.deltaTime;
    player.Move(movement * Time.deltaTime);
}

```

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


# Question
Title: PBR How to correcly use standard lighting and IBL
I'm creating a physically based renderer but I am a bit confused on how to put together standard lighting with IBL, since like I'm doing now I think it's wrong.

Right now, for each light, I evaluate it's contribution to the scene lighting combined with IBL lighting (I use both the light contribution and diffuse and specular coming from the IBL) but like this I sum the IBL contribution for each light, and I don't think it's right.

To put together standard lighting with IBL, do I need to process all the lights alone and then, in another step, bake into the scene the IBL? I think this would be more correct.

# Answer
The cubemaps used in Image Based Lighting should only contribute to the scene once because they don't represent light coming from a single light source like your point lights for example, but from every direction from the environment. This means that they should be added to the light buffer only once, which you could do in either of these passes:

* In the object shader: If you are using forward rendering, it should be added to the object in the directional light pass (or the ambient light pass if you don't have a dirlight in the scene). In case of deferred rendering, you only do the object shader once for each object anyway, so this is trivial. In this case you also need to write the light texture which could be a no-go if you are using a different size from your gbuffer.
* Lighting pass: In case of deferred rendering, you could do this in one of the lighting passes. It would be best if you didn't have to create a new pass for this, like if you know for sure that you always have one directional light, you can just add the IBL contribution right there. If this is not the case, you should add the IBLs in a separate full-screen pass. In case of tiled deferred rendering it would be trivial to add the IBLs when calculating the rest of the lights I imagine.

If you have more IBL light probes, you most likely want to combine them somehow. To blend them among themselves, you should use some sort of blend mode which is not additive, like alpha blending. The combined light probe should then be additively blended to the light buffer.
> 2 votes

---
Tags: graphics, lighting
---


# Question
Title: Rotate directly towards a target at a constant speed
I've written a program (see on JS Fiddle) that rotates my player towards the mouse cursor at a constant speed. I've computed the angle to the point using the `Math.atan2` function, but when incrementing or decrementing the player's rotation towards that value, it does not always take the shortest path.

This image describes the logic I intend to evaluate:

The problem appears when you cross a specific angle, the player rotates the long way around to reach the cursor, instead of taking the shortest path. How can I always take the shortest path at a constant speed?

Many thanks.

# Answer
Your main problem is that you did not account for the discontinuity in the arctangent function...

```
// Check if arctangent has crossed the discontinuity
if (delta < -Math.PI || (delta > 0 && delta < Math.PI)) {

```

And you are not reducing the player rotation into a canonical `-Pi <= x < Pi` range.

```
// Reduce player.r into the -PI thru PI range
player.r = (player.r + 3 * Math.PI) % (2 * Math.PI) - Math.PI;

```

Additionally, to actually get a fixed rotation speed, you can not rely on the refresh rate of the screen. Instead you must either measure the clock each update, or use an interval timer.

```
setInterval(update, 1000 / 24); // run update at 24fps to achieve constant rate

```

Fiddle: https://jsfiddle.net/sjeder3d/8/
> 1 votes

---
Tags: mathematics, javascript, rotation
---


title: SDL2 in a VS2015/C++ panel

text:
# Question
Title: SDL2 in a VS2015/C++ panel
I'm trying to use SDL2 in a panel (VS2015/C++) and cannot find solid examples of how to connect the two. Anyone know how this is done?

I've tried some code found in various places, but no luck yet. The code below was my latest attempt. I'm using latest version of SDL2.

```
SDL_Window* sdlWnd = SDL_CreateWindowFrom((void*)mapPanel->Handle);
SDL_SetWindowTitle(sdlWnd, "SDL Window - Set by SDL");
SDL_Surface* s = SDL_GetWindowSurface(sdlWnd);
SDL_FillRect(s, &s->clip_rect, 0xffff00ff);
SDL_UpdateWindowSurface(sdlWnd);
SDL_ShowWindow(sdlWnd);

```

# Answer
> 1 votes
Think of `SDL_Window` as physical pixels, and `SDL_Renderer` and a place to store settings/context.

So you create a bunch of resources, and hang them off of the renderer; and then when its ready, you tell renderer to put it all together and send the results to the window.

---
Tags: sdl2, visual-studio
---


# Question
Title: C# How to add inventory to player, NPCs, and in-game objects?
I'm a beginner in C# and trying to implement a **player**, an **item interface**, and some kind of **storage system** (for player inventory, NPC inventory/drop list, and storage like chests), and having some trouble implementing it in a way that requires the least work for a large amount of class types (and instances).

This is my current Player class:

```
namespace RogueBase.Classes
{
    public class Player
    {
        public Iitem[] inventory { get; set; }

        private int _hp;
        public int hp
        {
            get { return _hp; }
            set
            {
                if (value <= 0) _hp = 0;
                else if (value > 100) _hp = 100;
                else _hp = value;
            }
        }

        public Player()
        {
            hp = 100;
        }
    }
}

```

And my Storage class:

```
using RogueBase.Interfaces;
namespace RogueBase.Classes
{
    public class Storage
    {
        public Storage(int capacity)
        {
            inventory = new Iitem[capacity];
        }

        public bool Add(Iitem newItem)
        {
            for (int i = 0; i < inventory.Length; i++) // check each slot
            {
                if (inventory[i] as Iitem != null) { continue; } // skip items

                inventory[i] = newItem; // assign item to empty slot
                return true; // report success
            }
            return false; // inventory full
        }

        public bool Remove(Iitem targetItem)
        {
            for (int i = 0; i < inventory.Length; i++) // check each slot
            {
                if(inventory[i] == targetItem) // when match is found
                {
                    inventory[i] = null; // remove it
                    return true; // report success
                }
            }
            return false; // no item found
        }
    }
}

```

Item interface (just for reference):

```
namespace RogueBase.Interfaces
{
    public interface Iitem
    {
        string name { get; set; }
        int sellValue { get; set; }
        bool consumable { get; set; }

        void Equip();
        void Sell();
        void Consume();
    }
}

```

The problem right now is that every time I want to create a new inventory for something, I need to prepare a variable for it (not a problem when it comes to the player), but I'd like to be able to create friendly and hostile NPCs on demand with their own unique inventory that could be randomly generated,

In order to do this, is it my only option to turn the Storage class into an interface and copypaste the functions for every NPC/storage type? Or can I somehow turn the Add/Remove functions static? If I try to do it right now I get an error:

> An object reference is required for the non-static field, method, or property 'Storage.inventory'

Edit; Specified question:

How can I access `Iitem[] inventory` in `class Player` to be used in `class Storage`'s methods?

# Answer
Yes, you can turn the functions static, it has one downside: you need to keep track which inventory belongs to which object. A dictionary would do (simplified):

```
public static class InventoryManager {
  //map entity -> Storage, where entity is any type common for all entities that can have invetory
  // may it be common base, interface (even not related like ISpawnable) or just Object
  private static Dictionary<Entity,Storage> _storages = new Dictionary<Entity,Storage>();
  public static void AddItem(Entity entity, Iitem item) {
     var storage = _storages.TryGetValue(entity);//try get
     //if not found, add it (remember also to delete it when not needed anymore!)
     if (storage == null) { _storages[entity] = (storage = new Storage()); }
     storage.Add(item);
  }
}

```

you can also add `this` keyword in function signature i.e. `this Entity entity`, making it an extension method, turning syntax `InventoryManager.Add(orc1, axe)` into `orc1.Add(axe)` like it was a member of the orcs NPC class.
One may also argue - why go static if they were derived from same type? You could add (non)virtual method handling inventory to the ancestor(base class).

---

In reaction to edit you were on the right track with the other option: You *encapsulate* the inventory array (and logic) within `Storage` class, like you had before. And let the player have variable of `Storage` type (or better rename Storage to Inventory and everything should be clearer), e.g.

```
//extra tip: implement IEnumerable<Iitem> it will allow linq to work on your invtory
public class Storage
{
  private Iitem[] inventory;
  //logic
}

//Id recommend also adding following interface
interface IHasInvetory {
   Storage Invetory { get; }
}

public class Player : IHasInvetory
{
   public Storage Invetory { get; set; }
   //rest of the class
}

```
> 4 votes

---
Tags: c#, inventory
---


title: Object orbitting 2D circle java

text:
# Question
Title: Object orbitting 2D circle java
I'm using this code to make a square that orbits a circle . When I use it however the `rect()`; is quite far away from the circumference of the circle, I would like to make it closer. All variables are floats. `YPos` and `XPos` are the x and y of the circles origin.

```
charx = XPos[0] + cos(angle)*Sizes[0];
chary = YPos[0] + sin(angle)*Sizes[0];
angle += 0.1;
fill(255,255,255);
rect(charx, chary, 10,10);}

```

Any idea what I should change? This is probably something very simple, but I'm very new to Java.

# Answer
Two ideas: 1) Make Sizes\[0\] smaller. 2) Try rect(charx-5, chary-5, 10, 10);
> 1 votes

---
Tags: java
---


title: OpenGL nothing being drawn to screen

text:
# Question
Title: OpenGL nothing being drawn to screen
I am following the book 'OpenGL SuperBible' and am trying to run one of the first examples of drawing a point to the screen, bit instead of using there lib, im using GLFW. I'm not sure where I am going wrong.

Using GLFW 3.0 and Opengl 4.5

Creating shader

```
static const GLchar *vertex_shader_source[] = {
    "#version 450 core \n",
    " \n",
    "void main(void){ \n",
    "gl_Position = vec4(0.0,0.0,0.5,1.0); \n",
    "} \n",
    " \n",
};
static const GLchar *fragment_shader_source[] = {
    "#version 450 core \n",
    "out vec4 color; \n",
    "void main(void){ \n",
    "color = vec4(0.0,0.8,1.0,1.0); \n",
    "} \n",
    " \n",
};

vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, vertex_shader_source, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, fragment_shader_source, NULL);
glCompileShader(fragment_shader);

program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);

glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);

```

Setting up the VAO

```
GLuint vertex_array_object;
glGenVertexArrays(1, &vertex_array_object);
glBindVertexArray(vertex_array_object);

```

Rendering

```
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
glUseProgram(program);
glPointSize(40.0f);
glDrawArrays(GL_POINT, 0, 1);

```

I'm still quite new to game development, so i'm sorry if its something silly i missed

**EDIT**

I finally got it working after a little modification. I was deleting the shaders without detaching them from the program after linking which seemed to cause the shaders to never be called. Also since i'm using GLFW I needed to use **glewExperimental = true;** before initilizing glew.

Here is the final code

```
static void error_callback(int error, const char* description){
    fprintf(stderr, "Error: %s\n", description);
}

void main() {
    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit()) {
        exit(EXIT_FAILURE);
    }
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    glewExperimental = true;
    if (!window){
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    if (glewInit() != GLEW_OK) {
        return;
    }
    static const GLchar *vertex_shader_source[] = {
        "#version 450 core \n"
        "void main(void){ \n"
        "gl_Position = vec4(0.0,0.0,0.5,1.0); \n"
        "} \n"
    };
    static const GLchar *fragment_shader_source[] = {
        "#version 450 core\n"
        "out vec4 color; \n"
        "void main(void){ \n"
        "color = vec4(0.0,0.8,1.0,1.0); \n"
        "} \n"
    };
    const GLubyte* renderer = glGetString(GL_RENDERER);
    const GLubyte* version = glGetString(GL_VERSION);
    std::cout << "GPU: " << renderer << std::endl;
    std::cout << "OpenGL Version: " << version << std::endl;
    GLuint vertex_shader;
    GLuint fragment_shader;
    GLuint program;
    GLuint vertex_array_object;

    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, vertex_shader_source, NULL);
    glCompileShader(vertex_shader);

    GLint isCompiled = 0;
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE){
        return;
    }

    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, fragment_shader_source, NULL);
    glCompileShader(fragment_shader);

    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &isCompiled);
    if (isCompiled == GL_FALSE){
        return;
    }

    program = glCreateProgram();
    glAttachShader(program,vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);

    GLint isLinked = 0;
    glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked);
    if (isLinked == GL_FALSE){
        return;
    }

    glDetachShader(program, vertex_shader);
    glDetachShader(program, fragment_shader);

    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);

    glCreateVertexArrays(1, &vertex_array_object);
    glBindVertexArray(vertex_array_object);

    while (!glfwWindowShouldClose(window)){
        float currentTime = glfwGetTime();
        const GLfloat color[] = {
            (float)sin(currentTime)*0.5f+0.5f,
            (float)cos(currentTime)*0.5f+0.5f,
            0.0f,
            0.1f
        };
        glClearBufferfv(GL_COLOR, 0, color);

        glUseProgram(program);

        glBindVertexArray(vertex_array_object);
        glPointSize(40.0f);
        glDrawArrays(GL_POINTS, 0, 1);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}

```

# Answer
It looks like you're trying to draw a 40x40 pixel aqua colored square at (0.0, 0.0, 0.5), is that right? OpenGL producing no output is probably the most common symptom you'll run into. I immediately see several things that look a little off:

1. Your shaders are requiring OpenGL 4.5. Are you sure your current OS/drivers/etc. implement OpenGL 4.5?
2. You set the clear color (to 40% blue, but completely transparent? What does that mean?) but you never actually clear the color buffer by calling `glClear(GL_COLOR_BUFFER_BIT);`. This is actually a really good test. I'd clear the buffer to something with a 100% alpha, like `glClearColor(0.0, 0.0, 0.4, 1.0); glClear(GL_COLOR_BUFFER_BIT);` and see if you see a completely blue frame. If not, then you aren't even drawing anything.
3. You never check `glGetError();` to see if anything succeeded. (This goes back to #1 above.) If you do, you might figure out what exactly is going wrong.
4. You don't show any code for setting any vertex positions, so you don't appear to be drawing any geometry.
> 2 votes

---
Tags: opengl, shaders, glfw
---


title: Life is Strange art style

text:
# Question
Title: Life is Strange art style
So, I've been obsessing over the video game Life Is Strange for the past few weeks (rightfully so, its a wonderful game) and I've been putting together a list of what makes it compelling to play. I got to the art style, as it obviously isn't realistic but not too unrealistic. I was trying to put it together myself but when I google search life is strange art style, all that shows up is fan art that doesn't well reflect it. I want to know what style of texture painting they used to give it that semi-realistic feel. How can I replicate it on my own in photoshop for my own game?

Sorry if I misplaced this question in this community, I just didn't feel right posting in graphic design.

# Answer
> -1 votes
why not look up the artists themselves and see their work and bio's, how they approach work, etc? You may find much more this way, as opposed to googling Life is strange art style. plus if there is gdc videos or related life is strange talks, you can get a hint. The last thing is, go on their website and maybe just ask. they might have a forum.

---
Tags: non-photorealistic
---


# Question
Title: How do I apply domain warping to my marching cubes voxel terrain in Unity?
So, in GPU Gems 3 there is a cool warped terrain that I seek to replicate. Currently, I'm generating the terrain fine, but I want to add that warp effect.

```
// Do this before using 'ws' to sample the nine octaves!
float3 warp = noiseVol2.Sample( TrilinearRepeat, ws*0.004 ).xyz;
ws += warp * 8;

```

Im wondering how to replicate the above code in C#. What does the above code do? What type of variable is noiseVol2.Sample(x,y).xyz?

I want to warp my own terrain, currently I have a system that creates octaves of perlin noise with certain frequencies and amplitudes.

It looks something like this:

```
var perlin0 = new Perlin3(0,baseFreq  * 4.03f, 0.25f);
var perlin1 = new Perlin3(1, baseFreq * 1.96f, 0.50f);
var perlin2 = new Perlin3(2, baseFreq * 1.01f, 1.00f);
var perlin3 = new Perlin3(3, baseFreq * 0.49f, 2.00f);
var perlin4 = new Perlin3(4, baseFreq * 0.24f, 4.00f);

return new Density(ws => {

        // start with plane
        float density = plane.Evaluate(ws);

        // add perlin noise to get density values at each ws co-ord.
        //3 octaves currently (3 perlin noise +=)
        density += perlin0.Evaluate(ws);
        density += perlin1.Evaluate(ws);
        density += perlin2.Evaluate(ws);
        density += perlin3.Evaluate(ws);
        density += perlin4.Evaluate(ws);
        return density;
    });

```

I've tried replicating it like so:

```
var q = new Vector3(perlin0.Evaluate(new Vector3(0,0,0)), perlin0.Evaluate(new Vector3(5.2f, 1.3f, 1.3f)));
var q1 = new Vector3(perlin1.Evaluate(new Vector3(0, 0, 0)), perlin1.Evaluate(new Vector3(5.2f, 1.3f, 1.3f)));
var q2 = new Vector3(perlin2.Evaluate(new Vector3(0, 0, 0)), perlin2.Evaluate(new Vector3(5.2f, 1.3f, 1.3f)));
density += perlin0.Evaluate(p + 4.0f*q);
density += perlin1.Evaluate(p + 4.0f * q1);
density += perlin2.Evaluate(p + 4.0f * q2);

```

I've read the article that Íñigo Quílez created, and implemented it like above. Am I doing something wrong? It looks the same without that, just using

```
density += perlin0.Evaluate(p);
density += perlin1.Evaluate(p);
density += perlin2.Evaluate(p);

```

I want to know what I'm doing wrong, what I misunderstood and how to implement it correctly.

This is all based off this lumpn's proceedural-generation on github (I would link it, but I can't)

Thanks.

I would also want to know if there are any examples (I learn best from codebases) with this implementation using shaders. (Maybe it will run faster because it uses the GPU instead of the CPU?)

This is still unanswered on how to do it on the CPU (and I'm still confused on how to do it on the GPU, do you have to do some vertex stuff? how do you pass in a noise texture through the shader?)

# Answer
Most of the stuff in GPU Gems is shader stuff. The code you are trying to replicate in C# is ShaderLab, which Unity also uses for shaders.

In other words, the lines of code would be the same and would be part of a custom shader that you would apply.
> -1 votes

---
Tags: unity, procedural-generation, perlin-noise, noise
---


title: Terrain rendering using Geometry Shader

text:
# Question
Title: Terrain rendering using Geometry Shader
my idea is render an entire terrain based on heightmap using geometry shader, i am parsing only one point per quad of terrain with the heights of the corners, however for some reason i am not being able to expand every point into quads, if not wrong i should be able to do this using geometry shader directly.

Load Terrain on GPU memory -\> Draw entire terrain -\> Expand every point into 4 vertex -\> Process texture on Pixel Shader

Vertex Input:

```
enum SHTerrainHeightEnum
{
    CORNER_TL, // Top-Left
    CORNER_TR, // Top-Right
    CORNER_BR, // Bottom-Right
    CORNER_BL, // Bottom-Left
    CORNER_MAX,
};

struct SHTerrainVertex // Point
{
    uint16 Index;
    float Height[CORNER_MAX];
};

```

Vertex Shader:

```
struct VertexInputType
{
    float Index : TEXCOORD0;
    float4 Heights : POSITION;
};

VertexInputType main( VertexInputType input )
{
    return input;
}

```

Geometry Shader:

```
cbuffer MatrixBuffer : register(b0)
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

struct VertexInputType
{
    float Index : TEXCOORD0;
    float4 Heights : POSITION;
};

struct GeometryOutputType
{
    float4 Position : POSITION;
    float2 UV : TEXCOORD0;
};

[maxvertexcount(4)]
void main(
    point VertexInputType input[1],
    inout TriangleStream< GeometryOutputType > output
)
{
    float x = (float)((uint)input[0].Index % 256) * 100.0f, y = (float)((uint)input[0].Index / 256) * 100.0f;

    GeometryOutputType vertex;

    // Top Left
    vertex.Position = float4(x, y, input[0].Heights[0], 1.0f);
    vertex.UV = float2(0.0f, 0.0f);
    vertex.Position = mul(vertex.Position, worldMatrix);
    vertex.Position = mul(vertex.Position, viewMatrix);
    vertex.Position = mul(vertex.Position, projectionMatrix);
    output.Append(vertex);

    // Top Right
    vertex.Position = float4(x + 100.0f, y, input[0].Heights[1], 1.0f);
    vertex.UV = float2(1.0f, 0.0f);
    vertex.Position = mul(vertex.Position, worldMatrix);
    vertex.Position = mul(vertex.Position, viewMatrix);
    vertex.Position = mul(vertex.Position, projectionMatrix);
    output.Append(vertex);

    // Bottom Right
    vertex.Position = float4(x + 100.0f, y + 100.0f, input[0].Heights[2], 1.0f);
    vertex.UV = float2(1.0f, 1.0f);
    vertex.Position = mul(vertex.Position, worldMatrix);
    vertex.Position = mul(vertex.Position, viewMatrix);
    vertex.Position = mul(vertex.Position, projectionMatrix);
    output.Append(vertex);

    // Bottom Left
    vertex.Position = float4(x, y + 100.0f, input[0].Heights[3], 1.0f);
    vertex.UV = float2(0.0f, 1.0f);
    vertex.Position = mul(vertex.Position, worldMatrix);
    vertex.Position = mul(vertex.Position, viewMatrix);
    vertex.Position = mul(vertex.Position, projectionMatrix);
    output.Append(vertex);
}

```

Pixel Shader: struct GeometryOutputType { float4 Position : POSITION; float2 UV : TEXCOORD0; };

```
float4 main(GeometryOutputType input) : SV_TARGET
{
    return float4(0.0f, 0.5f, 0.0f, 1.0f);
}

```

Render Code:

```
uint32 TERRAIN_SIZE = 256;
VideoManager::_DeviceContext->VSSetShader(Shader::VertexShader[Shader::VS_TERRAIN], nullptr, 0);
VideoManager::_DeviceContext->GSSetShader(Shader::GeometryShader[Shader::GS_TERRAIN], nullptr, 0);
VideoManager::_DeviceContext->PSSetShader(Shader::PixelShader[Shader::PS_TERRAIN], nullptr, 0);

uint32 stride = sizeof(SHTerrainVertex), offset = 0;
VideoManager::_DeviceContext->IASetVertexBuffers(0, 1, &_VertexBuffer, &stride, &offset);
VideoManager::_DeviceContext->IASetInputLayout(Shader::InputLayout[Shader::VS_TERRAIN]);
VideoManager::_DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);

VideoManager::_DeviceContext->GSSetConstantBuffers(0, 1, &_SettingBuffer);

VideoManager::_DeviceContext->Draw(TERRAIN_SIZE * TERRAIN_SIZE, 0);

VideoManager::_DeviceContext->GSSetShader(nullptr, nullptr, 0);

```

I couldn't figure out what is wrong with this code, it should draw on screen perfectly however it doesn't draw anything, everything is blank.

I did this for decrease the memory usage and do GPU culling of the terrain discarding the terrain blocks what are outside of camera.

EDIT: I am using DirectX 11 with feature levels of 10.0, if someone has a better recommendation about what I could do for optimize the terrain I will really appreciate

Max terrain size is 256x256, but might be extended to 1024x1024.

Any answer is appreciated, really thanks for your time.

# Answer
Forgot to answer for mark it as answered.

At the end I finished doing what Balint recommended me, really thanks Balint for your answer.
> -1 votes

---
Tags: game-design, optimization, terrain
---


# Question
Title: How to do camera follow without drag and drop in Inspector in Unity?
How to do camera following an object with special tag without drag and drop into Inspector? I have 2 prefab model they are not into hierarchy for the moment when player start play. To load selected model into scene I'm using the below code.

```
public GameObject[] players;
void Start ()
{
LoadPlayer ();
}
private void LoadPlayer()
{
GameObject player =Instantiate(players[PlayerPrefs.GetInt(MyModel")]);
}

```

Because in other scene I can change my player model but I can't follow it using in c# script for camera public Transform cause of I can't drop it in that place in Inspector. So in what way I can find current player object when game start to follow it by camera?

# Answer
give this script to player.this script find camera then give camera.position so you can use Lerp for following

```
using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

    void Update () {
        Vector3 offest = new Vector3 (3,3,3);//Distance from object
        Vector3 cameraPos = Camera.main.transform.position;//position of camera
        Camera.main.transform.position= Vector3.Lerp (new Vector3(cameraPos.x,cameraPos.y,cameraPos.z), transform.position + offest, 0.8f *Time.deltaTime));
    }
}

```

If you want follow player just In one axis you can replace zero In upper code for example if you want follow player In vector3.x you can do It easily:

```
Camera.main.transform.position= Vector3.Lerp (new Vector3(cameraPos.x,0,0), transform.position + offest, 0.1f);

```
> 1 votes

# Answer
You want to use GameObject.FindWithTag which will return the first active `GameObject` in the scene that matches the tag you pass in as the parameter. So assuming your player `GameObject` uses the tag `Player`, you would do the following.

```
void Start() {
    Transform player = GameObject.FindWithTag("Player").transform;
}

```
> 1 votes

# Answer
In the player script, you could find the camera and make it follow the player with:

```
GameObject cam = GameObject.FindWithTag("Camera"); //assuming Camera has tag Camera
cam.transform.setParent(this.gameObject);

```

This makes the player the parent of the camera. This essentially does what the drag and drop does, but through code, so it works with prefabs.
> 0 votes

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


title: Particle System Hangs the Game

text:
# Question
Title: Particle System Hangs the Game
I create a Smoke Effect in my Game Scene using Particle system. it works Perfectly in unity Editor, but when I run Game in Android Device it hangs. I search about that but not getting any right solution. Any one can know how to optimize the particle system and run smoothly in device? thanks in advance. Here is the Snapshot of Particle system.

# Answer
Lower the max particle to 50-100. Increase start size if seems less dense. Also lower the emission rate if works for you. Increase start lifetime if needed.
> 1 votes

# Answer
500 particles is fine for all of the Android devices, the problem can be in texture format used for particle rendering. Also not sure what setup you have in Shape section.
> 1 votes

---
Tags: unity, particles
---


title: Multilevel 2D grid graph and A*

text:
# Question
Title: Multilevel 2D grid graph and A*
I've coded up a little grid based dungeon game. Everything working quite nicely in a Tile\[,\]. The AI uses basic GOAP for tasks and A\* for moving around. Tile reachability is done using a floodfill.

Thinking about what my next step would be, I decided to change the art style from being the typical dungeon to a more sci-fi approach and thought it'd be great to have multiple levels.

This is where I ran into a problem because A\* in a 2d grid I understand. But adding extra levels makes it a wee bit harder. My initial thoughts would be to add connections to the next levels in 'stairs' or 'elevator' tiles and adding these to the neighbor list of a Tile for evaluation by A\*.

But this throws my heuristic for a loop. I'm using Manhattan distance.

**TL;DR: How should I improve my heuristic for multi level path finding?**

# Answer
> 0 votes
If you go for this connections approach your heuristic will be made up of two parts. First you find the closest connection point to the target level and apply classic Manhattan distance from your current location to this stairs/elevator. Next you check the distance on the target level from the connection point to the actual target, again just Manhattan. You should probably add some costs for the elevator/stairs as well. This should give you a pretty valid estimation of the costs.

Another approach would be threedimensional geometry, so you calculate ypur Manhattan distance with also the height difference in mind: H = dh * dh + dw * dw + dl * dl. Then you add some factor for the "up"-cost and your are good to go. This is surely faster than the first approach but also not very exact if you cannnot change levels at any time. It could still be valid if your "up"-cost is high enough, but that depends on the maps.

Depending on how you implemented your algorithm this should work without much change to your actual pathfinding code, but you will have to keep track auf multiple levels and move your agent from one plane to another.

---
Tags: ai, path-finding, grid, graph
---


# Question
Title: Calculating the poly vertices based on the result of Connected Component Labeling
I am making a tile based game.

And now I can find all the connected area using the Connected Component Labeling algorithm.

But now the problem I am having is how to calculate the poly vertices of each connected area.

For example:

As you can see all the YELLOW tiles are of the same AREA and with the help of Connected Component Labeling algorithm I know all the (x, y) info of each tile.

And now I want is the generate a poly vertices array for the YELLOW AREA POLY (clockwise).

Is there any good algorithm for this ?

Any suggestion will be appreciated, thanks :)

# Answer
After doing some more research I finally find a solution based on this post: java-merge-adiacent-rectangles-into-a-polygon

Here is my solution process sequence in general:

* Extract all edges from the tiles into a EdgeArray
* Remove all the edges that has a duplicated one in the EdgeArray this will leaving only the Edges of the merged poly contour I want
* Connect all edges from head to tail , head to tail ...
* Pick up all the vertices point from the edges

and that's the finally clockwise PolyVerticesArray I want.
> 0 votes

---
Tags: javascript, algorithm, tilemap, grid
---