title: Poor CUDA performance, raytracing

text:
# Question
Title: Poor CUDA performance, raytracing
I use CUDA 7.5 to learn the basics of raytracing. So far I've done nothing but constant color no-lighting spheres-only raytracing. But my delta time is already 14 - 16 ms for 800x600 resolution - 1 ray for each pixel.

Some pc specs, if needed: GPU - nvidia titan black, CPU - intel core i7..., enough RAM.

Here is the kernel:

```
__global__ void runKernel(Camera* cam, SphereData* objs, uint* size, uchar* out_img)
{

vec3 pos = cam->getPos();
rs::Rectangle rec = cam->genNearPlaneRectangle();
vec3 start = rec.center - rec.right - rec.up;
float pixelsizex = 1.0F / cam->getWidth();
float pixelsizey = 1.0F / cam->getHeight();
uint width = cam->getWidth();

uint id = threadIdx.x + blockIdx.x * blockDim.x;
uint i = id % width;
uint j = id / width;

vec3 pixelW = start + rec.right * 2 * (pixelsizex / 2 + pixelsizex*i) + rec.up * 2 * (pixelsizey / 2 + pixelsizey*j);
vec3 dir = (pixelW - pos).normalize();

Ray ray = Ray(pos, dir);

vec3 resColor = Tracer::rayTraceSpheres(ray, objs, *size);

out_img[4 * width * j + 4 * i + 0] = 255 * resColor.x();
out_img[4 * width * j + 4 * i + 1] = 255 * resColor.y();
out_img[4 * width * j + 4 * i + 2] = 255 * resColor.z();
out_img[4 * width * j + 4 * i + 3] = 255;

}

```

I have a really basic standart setup for OpenGL, I use it to render a fullscreen texture of raytracing results.

Main loop's update and render functions:

```
void Graphics::update()
{
cameraUpdate();

//println(camera.genLookingRay().dir.toString());

uint objSize = objs.size();
cudaMemcpy(cudaData.d_cam, &camera, sizeof(Camera), cudaMemcpyHostToDevice);
cudaMemcpy(cudaData.d_objs, objs.getArray(), sizeof(SphereData)*objs.size(), cudaMemcpyHostToDevice);
cudaMemcpy(cudaData.d_size, &objSize, sizeof(uint), cudaMemcpyHostToDevice);

uint threadsPerBlock = 128;
uint blocks = ((uint)(width*height) + threadsPerBlock - 1)/threadsPerBlock;

runKernel <<< blocks, threadsPerBlock >>>(cudaData.d_cam, cudaData.d_objs, cudaData.d_size, cudaData.d_out_img);

// Check for any errors launching the kernel
cudaError cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
    fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
}

cudaStatus = cudaDeviceSynchronize();

cudaMemcpy(image, cudaData.d_out_img, sizeof(uchar)*4*width*height, cudaMemcpyDeviceToHost);

RenderFullScreen::setupTexture(width, height, image, 0);
RenderFullScreen::build();

}

void Graphics::render()
{
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

Shader::setCurrent(Shader::SHADER_HUD);
Shader::getCurrent().enable();
Shader::getCurrent().setUniformMat4f("P", camera.getMatOrthographic());
RenderFullScreen::render();
Shader::getCurrent().disable();

glfwSwapBuffers(window);
}

```

Function "rayTraceSpheres(...)":

```
__CUDA__ vec3 Tracer::rayTraceSpheres(Ray& ray, SphereData* objs, uint size)
{
    vec3 color(0,0,0);
    float tmin = INFINITY;

    for(size_t i = 0; i < size; i++)
    {
        Sphere obj = Sphere(objs[i]);

        float ct = tmin;
        vec3 cc(0,0,0);
        bool res = obj.hit(ray, ct, cc);

        if(ct < tmin) {
            color = cc;
            tmin = ct;
        }
    }

    return color;
}

__CUDA__ bool Sphere::hit(Ray& ray, float& tmin, vec3& color)
{
    float t;
    vec3 temp = ray.start - center;
    float a = ray.dir * ray.dir;
    float b = temp * 2 * ray.dir;
    float c = temp * temp - radius * radius;
    float disc = b * b - 4 * a * c;

    if(disc < 0){
        return false;
    }
    else
    {
        float e = sqrt(disc);
        float denom = 2 * a;
        t = (-b - e)/denom;
        if(t > 0){
            tmin = t;
            color = this->color;
            return true;
        }
        t = (-b + e)/denom;
        if(t > 0)
        {
            tmin = t;
            color = this->color;
            return true;
        }
    }
    return false;
}

```

What could be the issue ?

# Answer
I would guess that the amount of branching you're doing is causing the performance loss. When there's warp divergence, divergent threads need to be thrown out and processed again so be careful about using conditionals and loops in CUDA. Try indexing into a list of function pointers and unraveling loops to avoid branching.
> 2 votes

# Answer
If You are working on Windows, CUDA tend to lag a bit due to WDDM feature. With my own CUDA raytracing implementation on Ubuntu 14.04 I get about 55 FPS on GTX 560 Ti, while on Windows 7 with GTX 970 on board I get only about 16 FPS, with the exact same code in both cases (i.e. a single ray per pixel solution). See this for more info about the issue.
> 1 votes

---
Tags: raytracing, cuda
---


# Question
Title: Parsing .OBJ to fit the gldrawelements() call. c++/opengl
I'm struggling trying to get this to work like it should. Ive been able to make an obj loader that fits the `glDrawArrays()` call, with uv and facenormals, but when trying to modify it to fit `glDrawElements()` Im at a loss.

This is the code I have this far, the function takes the addresses of the vectors to be filled:

```
void objload3(string filename, vector<glm::vec3>&vertices, vector<glm::vec2>&texcords, vector<glm::vec3>&normals)
{
    size_t vertsize = 0; size_t texsize = 0; size_t normalsize = 0; size_t facesize = 0;  //ref size containers

    string line; string token;
    std::ifstream file(filename);

    if (file.is_open())
    {
        while (getline(file, line)) //count size
        {
            if (line.compare(0, 2, "v ") == 0)++vertsize;
            else if (line.compare(0, 2, "vt") == 0)++texsize;
            else if (line.compare(0, 2, "vn") == 0)++normalsize;
            else if (line.compare(0, 2, "f ") == 0)++facesize;
        }file.close();
    }

    //set size
    vector <glm::vec3>verticeref(vertsize);
    vector <glm::vec2>texkoordref(texsize);
    vector <glm::vec3>normalref(normalsize);

    vector<string>points(facesize * 3);

    //index filling counters
    size_t vcount = 0; size_t vtcount = 0; size_t vncount = 0; size_t fcount = 0; size_t refcount = 0;

     //fill reference vectors
    file.open(filename);
    if (file.is_open())
    {
        while (getline(file, line))
        {
            if (line.compare(0, 2, "v ") == 0) {
                istringstream s(line.substr(2));
                glm::vec3 v; s >> v.x; s >> v.y; s >> v.z;
                verticeref[vcount++] = v;
            }

            else if (line.compare(0, 2, "vt") == 0) {
                istringstream s(line.substr(2));
                glm::vec2 v; s >> v.x; s >> v.y;
                texkoordref[vtcount++] = v;
            }

            else if (line.compare(0, 2, "vn") == 0) {
                istringstream s(line.substr(2));
                glm::vec3 v; s >> v.x; s >> v.y; s >> v.z;
                normalref[vncount++] = v;
            }

            else if (line.compare(0, 2, "f ") == 0) {
                line.erase(0, 2);
                istringstream is(line);
                while (getline(is, token, ' '))points[fcount++] = token;
            }
        }file.close();
    }

    vector<int>indexref(3*points.size()); //faces allocation

//clean up faces information, convert to int
for (unsigned int a = 0; a <points.size(); ++a) {
    stringstream is(points[a]);
    while (getline(is, token, '/')) { indexref[refcount++] = stoi(token); }
    is.clear();
}

```

at this point, I would do this to fit it with the `glDrawArrays()` call:

```
vertices.resize(points.size());
texcords.resize(points.size());
normals.resize(points.size());

refcount = 0; //keep track of fill

for (size_t fillcount = 0; fillcount < points.size(); ++fillcount)
{
    vertices[fillcount] = verticeref[indexref[refcount++] - 1];
    texcords[fillcount] = texkoordref[indexref[refcount++] - 1];
    normals[fillcount] = normalref[indexref[refcount++] - 1];
}

```

But this fill doesnt take account of all the duplicate vertices, nor does it create an index. Im having problems understanding the logic behind the gldrawarrays call, and how to easily make an index and list of vertices/uv/normals to fill the vbos with.

Seems like something the 3Dmodel tool should do, but it doesnt? I cant juse use the list of faces already in obj export?

Some clarification would be much appreciated.

# Answer
The answer turns out to be rather easy, altho lengthy, Instead of cleaning up faces (now called points) and preparing the list for gldrawarrays, I instead create a new list of unique faces/points as a base reference: Ill just post the entire function:

```
void objload4(string filename, vector<glm::vec3>&vertices, vector<glm::vec2>&texcords, vector<glm::vec3>&normals, vector<unsigned int>&xover)
{

size_t vertsize = 0; size_t texsize = 0; size_t normalsize = 0; size_t facesize = 0;  //ref size containers

string line; string token;
std::ifstream file(filename);

if (file.is_open())
{
    while (getline(file, line)) //count size
    {
        if (line.compare(0, 2, "v ") == 0)++vertsize;
        else if (line.compare(0, 2, "vt") == 0)++texsize;
        else if (line.compare(0, 2, "vn") == 0)++normalsize;
        else if (line.compare(0, 2, "f ") == 0)++facesize;
    }file.close();
}

//set size
vector <glm::vec3>verticeref(vertsize);
vector <glm::vec2>texkoordref(texsize);
vector <glm::vec3>normalref(normalsize);

vector<string>points(facesize * 3);

size_t vcount = 0; size_t vtcount = 0; size_t vncount = 0; size_t fcount = 0; size_t refcount = 0; //index filling count

//fill reference vectors
file.open(filename);
if (file.is_open())
{
    while (getline(file, line))
    {
        if (line.compare(0, 2, "v ") == 0) {
            istringstream s(line.substr(2));
            glm::vec3 v; s >> v.x; s >> v.y; s >> v.z;
            verticeref[vcount++] = v;
        }

        else if (line.compare(0, 2, "vt") == 0) {
            istringstream s(line.substr(2));
            glm::vec2 v; s >> v.x; s >> v.y;
            texkoordref[vtcount++] = v;
        }

        else if (line.compare(0, 2, "vn") == 0) {
            istringstream s(line.substr(2));
            glm::vec3 v; s >> v.x; s >> v.y; s >> v.z;
            normalref[vncount++] = v;
        }

        else if (line.compare(0, 2, "f ") == 0) {
            line.erase(0, 2);
            istringstream is(line);
            while (getline(is, token, ' '))points[fcount++] = token;
        }
    }file.close();
}

//make ref sheet for faces
vector<string>pointsreference;
pointsreference = points;
std::sort(pointsreference.begin(), pointsreference.end());
vector<string>::iterator it = std::unique(pointsreference.begin(), pointsreference.end());
pointsreference.erase(it, pointsreference.end());

xover.resize(points.size());

for (unsigned int a = 0; a < points.size();++a) //fill crossover index
    {
        for (unsigned int b = 0; b < pointsreference.size(); ++b)
        {
            if (pointsreference[b] == points[a])xover[a] =b;//make list of references for points
        }
    }

vector<int>indexref(pointsreference.size()*3); //faces allocation

//clean up faces information, convert to int
for (unsigned int a = 0; a <pointsreference.size(); ++a) {
    stringstream is(pointsreference[a]);
    while (getline(is, token, '/')) { indexref[refcount++] = stoi(token); }
    is.clear();
}

vertices.resize(indexref.size()/3); //final vertices now has right size
texcords.resize(indexref.size() / 3);
normals.resize(indexref.size() / 3); //in fact they all do

refcount = 0; //keep track of fill

for (size_t fillcount = 0; fillcount < indexref.size()/3; ++fillcount)
{
    vertices[fillcount] = verticeref[indexref[refcount++] - 1];
    texcords[fillcount] = texkoordref[indexref[refcount++] - 1];
    normals[fillcount] = normalref[indexref[refcount++] - 1];
}

//all vectors are now aligned with vertices and are unique, xover should define list of indices that are now aligned (for vbo use and gldrawelements)
}

```

call the function like this;

```
objload4(filename, vertices, texcords, normals, xover);//fill existing vectors

```

The breakthrough was realizing I needed a reference with unique values, make a xover index for faces, then apply the xover to the aligned indexes. (aligned with unique, if that makes sense).

Either way this approach is cheap, fast and it works
> 1 votes

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


# Question
Title: In Unity, how do I handle very short mouse drags as click events?
I am trying to recreate a UI menu that has functionality similar to the iPhone's home screen:

* If a user drags anywhere on the menu (including on a button), it should drag the whole page left/right depending on the user's drag.
* If a user clicks and holds motionlessly on a single button, it "dislodges" the button so that it can be dragged around.

I have all of my functionality working, including the dislodge. The one exception being that I'm running into a situation where I'm not sure how to transfer the drag message consumed by a button onto the backing scroll container if the user has not clicked long enough on a single button to "dislodge" it.

That is, I place my finger onto a button and drag (with the intention of dragging the entire page) but I'm not sure how to redirect the same drag message onto the ScrollRect of my backing container. Instead, my button consumes the OnDrag message and the page is not scrolled. The only method of scrolling the page is simply dragging on an empty part of the container where there is no button.

I'm using UI elements from Unity's 4.6 UI:

* I am using a ScrollRect to represent the backing container with all of my buttons
* I'm using a GridLayout to resize and pad my buttons
* I'm using a regular UI.Button class on each of my buttons
* I'm using the following EventSystem interfaces to catch and handle input for my buttons: IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler

Is there something already built into Unity that can allow me to transfer/redirect the drag message from one GameObject to another while the drag is still in process? Or do I need to rebuild parts of the UI from scratch to support this?

# Answer
What you can do from the OnDrag implementation of the button is this.

```
public void OnDrag(PointerEventData eventData)
    {
        if(scroll)// scroll is the GameObject with the ScrollRect component you will have to ckeck for the different drags here.
        {
            scroll.SendMessage("OnDrag", eventData);//This passes the drag message that started from the button onto the ScrollRect but it results in some jittery motion maybe you will have to modify eventData.
        }
    }

```

After a quick test the jittery motion is only when the movement type is elastic but giving it a higher elasticity fixed the problem.
> 1 votes

# Answer
This is something I did in UnityScript, you can adapt it accordingly.

This uses the mouse to drag.

You need to add an EventTrigger component to your button. Then add a PointerDown, PointerUp and a Drag event. Drag your GameObject where the script lies onto each event and then find the relevant function for each:

StopDragging function to PointerUp AttemptingDrag to PointerDown Dragging to Drag

```
#pragma strict

var MouseCoord : Vector2;

var ObjectToDrag : GameObject;

var NextClickTime = 0.0;
var NextClickInterval = 1;

var Drag : boolean;
var DragBackground : boolean;

var TransformChanged : boolean;

function Start () {

}

function Update () {

  if (Drag && (Time.time > NextClickTime) && (!ObjectToDrag.transform.hasChanged))
  // If we want to move the background and the button has not been dragged!
  {
    Drag = false;
    DragBackground = true;  // We now shift focus to the background.
  }

  if (DragBackground) // If we want to move the background
  {

    ObjectToDrag = GameObject.Find("ShoppingBackground");
                              // Find the background.

    ObjectToDrag.transform.localPosition.y  = MouseCoord.y;

    // The background will move with the mouse.
    ObjectToDrag.transform.position.x = MouseCoord.x;
  }

  //If you want to see the mouse coordinates in the inspector.
  MouseCoord.x = Input.mousePosition.x;
  MouseCoord.y = Input.mousePosition.y;
}

function Dragging()
{
  print ("Hit Button");

  if (Drag)
  {
    ObjectToDrag.transform.hasChanged = true;

    // We tell the computer that the object is in fact being dragged.
    TransformChanged = ObjectToDrag.transform.hasChanged;
    // We show this fact in the inspector.

    // The button will move with the mouse.
    ObjectToDrag.transform.position.y = MouseCoord.y;
    ObjectToDrag.transform.position.x = MouseCoord.x;

  }

}

function StopDragging()
{
  Drag = false;
  DragBackground = false;
}

function AttemptingDrag()
{
  NextClickTime = Time.time + NextClickInterval;
  // If we stay still interval is now set.
  Drag = true;

  if (Drag) // If we are merely dragging the button
  {
    // Find the button to grab.
    ObjectToDrag  = GameObject.Find("RemoteControlSpiderButton");

    // We tell the computer that the Button has not changed position.
    ObjectToDrag.transform.hasChanged = false;
    // We show this fact in the inspector.
    TransformChanged = ObjectToDrag.transform.hasChanged;
  }
}

```
> 0 votes

---
Tags: unity, iphone, scrolling, gui
---


title: Ray tracing - glossy reflection

text:
# Question
Title: Ray tracing - glossy reflection
Here I am again with my ray tracer for ipad. Now I'm trying to add glossy reflection to an object. How do i implement it? I read some documentation online like these:

http://www.cs.cmu.edu/afs/cs/academic/class/15462-s09/www/lec/13/lec13.pdf http://www.cs.cornell.edu/courses/cs4620/2012fa/lectures/37raytracing.pdf

If I understood correctly instead of trace a single ray as for standard reflection I have to trace n ray in a random direction. **How do I get this random direction for each ray?** **How do i generate these samples?**

# Answer
> 2 votes
Generating random directions efficiently is a major issue, especially in GPU implementations of anything like ray tracing. In my research about the matter I've been using an implementation described here. The solution refers to single values but can be easily applied to vectors as well. In my applications I generate random vectors using two methods:

* by repeating calls to PRNG function several times,
* using a function that produces a normally distributed vectors according to given slope value.

In both cases the base functions I use are as follows:

```
    inline __device__ unsigned _TausStep(unsigned &z, const int S1, const int S2, const int S3, const unsigned M)
    {
        unsigned b = (((z << S1) ^ z) >> S2);
        return z = (((z & M) << S3) ^ b);
    }

    inline __device__ unsigned _LCGStep(unsigned &z, const unsigned A, const unsigned C)
    {
        return z = (A * z + C);
    }

    /* Hybrid Tausworthe PRNG by NVIDIA.
       https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch37.html
     */
    inline __device__ float hybtausf(uint4 &z)
    {
       return 2.3283064365387e-10 * (
            _TausStep(z.x, 13, 19, 12, 4294967294UL) ^
            _TausStep(z.y, 2, 25, 4, 4294967288UL) ^
            _TausStep(z.z, 3, 11, 17, 4294967280UL) ^
            _LCGStep(z.w, 1664525, 1013904223UL)
        );
    }

```

The `hybtausf` function is what I use as a PRNG function. It is used both in the multiple calls random vectors generation, as in the following function, that implements the second method:

```
    // Pseudo-random, normally distributed ray direction generator.
    __device__ float3 prrg(float3 dir, float n, float4 &seed)
    {
        uint4 z = make_uint4(seed.x, seed.y, seed.z, seed.w);
        float u0 = hybtausf(z);
        float u1 = hybtausf(z);
        float3 w = normalize(dir);
        float3 t = w;

        w = fabs(w);

        seed = make_float4(z);

        if (w.x < w.y) {
            if (w.x < w.z) t.x = 1.0f;
            else t.z = 1.0f;
        } else if (w.y < w.z) t.y = 1.0f;
        else t.z = 1.0f;

        w = normalize(dir);
        float3 u = normalize(cross(t, w));
        float3 v = cross(w, u);

        float theta = acos(pow(1.0f - u0, 1.0f / (1.0f + n)));
        float phi = 2.0f * PI * u1;
        float3 a = make_float3(cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta));
        float3 R[3] = { make_float3(u.x, v.x, w.x), make_float3(u.y, v.y, w.y), make_float3(u.z, v.z, w.z) };

        return mult(a, R);
    }

```

The `n` parameter controls the mentioned "slope" of the distribution function, while `dir` is a "reference direction" around which a new direction will be generated. This method allows to generate the following overall outcome images of my implementation of path tracing (notice the reflection on the sphere):

The image is a bit grainy but that is because I haven't yet applied proper importance sampling in the particular case.

I hope that helps.

---
Tags: raytracing, reflection-rendering
---


title: Refraction and transparency?

text:
# Question
Title: Refraction and transparency?
I need to do some refraction in a sphere. Do I need to make the object transparent first? Or just use refraction(refract) in HLSL DirectX?

# Answer
> 0 votes
No, you are not supposed to make the object use transparent blending, instead, you should blend its color with the refracted scene color in its shader when rendering the object.

---
Tags: directx11
---


# Question
Title: Couldn't all games avoid post-start loading?
Just as giant open world games load massive maps dynamically, couldn't we load separate maps, menus, and virtually any interface or 3D setting via that same dynamic loading method? Without changing the environment, it seem like interfaces and various locations within the game could all be loaded dynamically the same way massive open world maps are loaded as you walk through them.

Why isn't this done? I see so many modern games where you have to wait a minute or more while the match / map / level is loading. I know there's a latency involved with connecting peers, but that doesn't take more than a few moments in my experience. What issues exists with this concept to stop it from being used to eliminate loading time involved with loading map / level / interface data?

# Answer
The answer is yes, this could be done, in most cases, at least to some extent.

The reasons it isn't done are many:

* It requires time and money to do it right.
* The amount of bugs that pass testing will be higher
* Load times are accepted by the users.
* There can be other reasons for load times, such as balancing server load.
* Generic solutions that can be bought off the shelf are more compatible with "load all at once".
> 34 votes

# Answer
If your menus have a ton of assets, those assets take time to load. You also have no idea what order people will navigate your menu. They could click options -\> back -\> credits, or credits -\> back -\> start game in rapid succession. So there's no reasonable streaming strategy.

In an open world game, you know the player won't move faster than some certain speed, so you know you don't need to load the detailed versions of faraway locations until they are approaching them.
> 10 votes

# Answer
A big factor in the feasibility of such a solution is the predictability of what needs loading. If the player loads entirely new levels with no way of anticipating what they will choose, a completely seamless solution is just not possible. For example, when the player may select any level in the game to play from, or if they have freedom to teleport to completely different areas in open world games.

Some *Halo* games start loading the selected level in the background while setting up multiplayer games. This reduces waiting time when the players are ready to start, and is probably the closest one can get to such a solution when the player can freely choose different levels with completely different assets.

Of course, you said "without changing the environment", but I just wanted to bring up the *Halo* example, as it's something I'd like to see more of.

Within a continuous campaign, or whenever the developer has a lot of control over the player's location, such a solution is certainly viable, just as you say. Naughty Dog likes to do away with loading times, with *Jak and Daxter* famously having no loading times on the PS2, and *Uncharted* games having a single loading time at the beginning.

However, to many, **loading time just isn't a problem that needs solving**. Or it's a problem that's very low on developers' priorities, when there's always more that could be done between *now* and *release date*.
> 5 votes

# Answer
Time.

You need time to save time. Or you need money to make up for the lack of time. In any case, "No loading time!" is a feature that only those who have the luxury to afford it can offer. It takes very careful planning, and you need to understand very well what you're doing and not all game developers have the resources to put on it.
> 3 votes

# Answer
Ultimately, it's limited resources.

Open-world games and especially MMOs are heavily crafted toward predictability - you always know what data you need to load well in advance. You can see this in the architecture of the worlds - anytime there's a lot of resources that need to be loaded, you have some way of preventing the user from seeing the stuff that isn't loaded yet. The most common way is gates and entrances that block your view into the next area for the crucial few seconds needed for the loading. Most MMOs also use less detailed models and textures, which shortens load times considerably.

Some things are still unpredictable, even with careful design. For example, there may be custom banners worn by players, that are only shown once the relevant data has been sent to your computer over the network. Of course, most games try to limit this to make it cheaper (e.g. Diablo III's banners are simple compositions, easy to send as few bytes of data). But ultimately, sometimes you just have to wait for data to come by. And you need to show *something* while the loading is in progress - in many games, this can cause a break in immersion as you see a grey, low-detail model shown while waiting for the data to be loaded.

And with all this, loading like this is a solved problem(TM), but that doesn't make it easy. It costs a lot of resources and time, both in optimizing the resources and their utilization to ensure a smooth playing experience, and in the code itself - asynchronous code is hard. It can also mean a lessened game experience even if everything goes right - it means that you have to ensure you don't cross the bandwidth capabilities of your lowest common denominator, so you need to lower the quality of models and textures, or make them less varied, and the geometry of your worlds is severely limited. If you don't, the game will be quite unplayable - while I remember people who played games that took 10 minutes (or even longer!) to load a map, simply because their computer wasn't quite up to the task, the game itself run fine after that. If it had seamless loading instead, the game would just freeze or show ugly textures and models all the time while waiting for the data to be loaded. Deferred loading isn't a win-win, it's a trade-off as most things in engineering :)
> 2 votes

# Answer
One reason dynamic loading isn't always the ideal solution that other answers haven't really considered I think is also pop-in and other graphical artifacts.

The prediction of what to load and what not to load often fails, and it can be a detracting experience when it does. One of the worst examples of this was in Rage by id Software. At least in the early versions, the megatexture systems made it so that even something like spinning around too quickly made enourmous amounts of texture and even geometry artifacts appear before slowly fading away.

These issues just aren't a problem is everything is preloaded.

Something to consider isn't necesarily what to load, but what to unload. When you've only got so much budget for space, when you load new things, what are the old ones to remove? How certain are you that those assets aren't going to be in use within the next few seconds? These are difficult problems to solve.

If every gameplay state is small enough to fit inside a common system budget, then every advantage is apparent, instead of loading, you just go straight into a level and things fade in as you play. But, as the main answers suggest, the loading time for a small game wouldn't be too extensive to worry about anyway.

I think it's worth thinking about the reasoning why dynamic loading systems were created originally, being that you know that several of your gameplay states may be too large for a common system and a game of that size just isn't possible to preload entirely.
> 2 votes

# Answer
One common reason is that it isn't always equally easy to determine if a resource is going to be needed in the near future.

Since you used terrain paging as an example, I will continue with that.

It's perfectly reasonable if you're in a given map grid to load all adjoining map grids in the background. You know the user can, at best, enter one of those. When they do, you can unload the ones no longer adjoining and load the ones that now are. This you have noted.

Now imagine fast travel. There is absolutely no way to predict where the user may choose to go. They have (usually) almost the entire map to choose from. Pre-loading all possible fast travel locations would take far too much memory (you might as well load the whole map into memory in the first place) and far too much time (assuming you did not have the whole map pre-loaded). When would this happen? When they open the fast travel dialog? The problem would only become several times worse!

This is why even most games with "no-load" terrain paging still have load screens on fast travel. It's also why, if you move fast enough, you can sometimes trigger loading screens in even games with no-load maps (I recall having done this in TES Oblivion).

Now imagine this applied to game resources in general, where relationships are often not obvious. You will end up having to either load all possible options, or start guessing what the user is going to do. Guessing is costly (both in development and CPU) and a complex mess to program. Specific examples:

* Save files: you would need to load *every* save file before the user reaches the save screen, or guess which file they might load (latest 5, etc.).
* UI: Many strategy games change their UI depending on your faction. You would need to load every possible UI design before the user started their game.
* Game world: in procedurally generated games, like Minecraft or RTS games like Civilization, the world doesn't exist until viewed, to varying extents. Pre-loading this is *impossible* since they did not exist to begin with; pre-calculating them could *at best* be done similarly to pre-loading, and is not applicable in the RTS case.

There might be ways around some of these issues, but that *costs real life money* to figure out. Most gamers accept reasonable loading screens and, if anything, tend to be willing to spend more on hardware to mitigate them. It's seen as a *hardware* issue, not a *game* issue, unless unusually excessive or otherwise disruptive (like loading in the middle of levels).

And keep in mind, background loading is not free. There is usually minimal impact from the modern use of background-loading terrain and some model files, but if you're suddenly guessing about many different resources, especially if you don't have reliable metrics and have to unload many resources and load superfluous ones, you can grind the system into dust.

The idea of background loading is to use the dead cycles for a better use, but there are only so many dead cycles to use. The same goes for memory - pre-loading can substantially increase the memory usage of a game. With a loading screen, you get to dump the existing resources. No such luxury with background loading, meaning it could double the memory requirement of the game on that count alone.
> 2 votes

# Answer
This is a common issue stemming from the fact that games are soft-realtime products, where a late delivery of content is not as useful as an on-time delivery (contrast with hard-realtime, like the cars in computers, where a late delivery can be no better than no delivery at all). You have to decide what to load and where.

Sometimes, the late deliveries are particularly bad. For example, if you are permitted to run around in a world before all of the walls are loaded, you can get behind a wall that you could never have gotten behind if the game loaded the walls before letting you move. It is not always easy to tell when you can get away with a "lazy" loading of content, and when you have to guarantee that the content is fully loaded.

Dynamic loading is also far more complicated. You constantly have to consider what to do if the resource has not yet loaded. This is a drain on development resources. It's far easier to develop when you can rely on the resources to exist.

The latencies are also not always acceptable. I've heard of cases in Starcraft where you would "warm up" your game by loading a map that has a side effect of caching every dynamically loaded model/image. You would then exit, and play the game normally. For the elite gamers, this minimized stuttering of the GUI which actually affected their gameplay. Trying to prove out which latencies will be acceptable to users and which will not is tricky.
> 1 votes

---
Tags: loading
---


# Question
Title: Stop rotating when select the game object by mouse input
I am new to Unity and I am confused about how to solve this problem. Initially, I want to make a platform rotate to its center vector up like this.

```
transform.Rotate (Vector3.up, speed * Time.deltaTime);

```

Then, I want to stop it from rotating when the mouse select it, like:

```
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast (ray, out hit)){
  //find a way to stop rotate
}

```

I cannot figure out how to stop it from rotating. Can anyone help me, please?

# Answer
Well, you can use OnMouseDown message to do so.

What you have to do is to make sure that your platform have any collider attached. Now implement `OnMouseDown` with the help of a flag. Like,

```
bool _shouldRotate = true;

void Update()
{
    if (_shouldRotate)
        transform.Rotate (Vector3.up, speed * Time.deltaTime);
}

void OnMouseDown()
{
    if (_shouldRotate)
        _shouldRotate = false;
}

```
> 1 votes

# Answer
Firstly add a tag to the platform object eg. "platform", then in the script where you are rotating the object make sure it checks if certain Boolean eg. **ROT** is true, then in the raycast from mouse script check the tag of the object like this: `if(hit.collider.tag == "platform")`

If it is then set the Boolean **ROT** to false which will prevent the line rotating the platform from running.
> 0 votes

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


# Question
Title: Component messaging system - using integers vs message objects
I'm currently working on a component based system for my game, and I've decided to use a messaging system to communicate between components. I've read some on the subject and it seems that most people are using message objects that extend on a base message object like so;

```
MySpecificMessage extends Message

```

or possibly they just have a single `Message` object which takes in a string variable that determines what it does, like so;

```
new Message("positionX:10"); //Plus other variables you might need

```

But I've also seen some implementations of this using statically defined integers as messages like so;

```
public static final int MySpecificMessage = 1; //Different numbers for different messages

```

Basically I'd like to know what the pros and cons are between them, and possibly when you'd use one over the other. Also, if you have any other type of messaging system please do share.

# Answer
> 1 votes
The syntax of your code snippets is Java, but this answer is from the perspective of C++ as that's what most game engines are written in.

## Message Objects

### Pros

Usability. Message objects are flexible and easy to debug. Since message objects names are known at runtime, you can easily print them, assert on them, etc. without having to write any reflection or other systems. In languages with built in reflection (C#, Java), this is less of a benefit.

### Cons

Speed. Doing a string-compare for every message * every recipient sent is significantly slower than the alternatives.

## Numbered Message Types

### Pros

Speed! Numbered message types (plus sensible message handling with switch statements) means that messages can be quickly discarded.

### Cons

Usability. If you define all your message-numbers in one file, that file is going to be referenced everywhere and modified constantly (by every member of the team) leading to frequent conflicts in merging. Additionally, at debugging-time, it may not be immediately obvious what each message is when you see them pass by.

## Delegate Binding

I'm not really sure how you'd implement this in Java, but my preferred means of doing events is by attaching a delegate to a given message name (or type). The front-end code would look something like this:

In SomeClass.h

```
class SomeClass : Component
{
  void Initialize();
  void onSomeEvent(const SomeEvent &args);
}

class SomeEvent
{
public:
  GameObject sourceObject;
  int amount;
}

```

And in SomeClass.cpp

```
void SomeClass::Initialize()
{
  this.Owner.ConnectEvent(SomeEvent, onSomeEvent);
}
void SomeClass::onSomeEvent(const SomeEvent &args)
{
  // resolve the event here
}

```

### Pros

Usability AND speed. Events can be created for free, without editing any extra files, events can be handled each in their own function rather without the need for a HandleEvent() function on every class, and (if it's set up correctly), it is every bit as fast as using integers for events.

### Cons

Complicated to write in the first place. The back-end implementation is a bit tricky. ConnectEvent, in the above example, is actually a macro that expands to a template to construct the delegate. Furthermore, the event-listening system in the middle needs to be able to handle objects being after registering for events without segfaulting, and other hairy considerations.

---
Tags: component-based, messaging
---


# Question
Title: Most effective approach when creating % chance of something
When dealing with % chance in a game what are the most effective ways to achieve this? When I use random.random()\[python\] or Math.random()\[javascript\] and use an if/elif/else conditional it seems like the things with a very low chance of happening, happened far more often than they should have.

For example, a python game I worked on used something like this:

```
qaul_eq = random.random()
if qual_eq <= .5:
   quality = common
elif qual_eq <= .75:
   quality = uncommon
elif qual_eq <=.9:
   quality = rare
elif qual_eq <=.97:
   quality = epic
else:
   quality = legendary

```

Javascript DEMO

There is a 2% chance that quality will be legendary yet when printed 20 times every time it is run at least 1 item in almost every test run is legendary. In my python game it isn't uncommon for 2 or 3 of the items to be legendary. I'd chalk it up to good luck if not for the large amount of test runs I have conducted.

# Answer
> There is a 2% chance that quality will be legendary yet when printed 20 times every time it is run at least 1 item in almost every test run is legendary.

Your algorithm generates a "legendary" rarity whenever a random number in the range 0..1 rolls above 0.97. That's a 3% chance or a chance of one in 33. It's not a 2% chance because `random()` generates double-precision floating-point numbers. `0.970000000023` is just as likely as `0.9999998735`.

As DMGregory calculated in a comment, you will have at least one legendary in 20 samples 45.6% of the time.

If you want an event to happen every `n`th times on average, do `if (random() < 1.0 / n)`. So to get something to happen once in 50, do `random() < 0.02`. Or `random() > 0.98` when you prefer that form. Checking randomly-generated floating-point numbers for equality is quite pointless because of their high presision (by the way: this also applies to floating-point numbers in most other situations).

However, keep in mind that random numbers have no memory (ok, techncally they do, because pseudorandom number generators are actually deterministic, but they do their best to hide that fact). Everytime you roll you have the same chance of success (further reading Gambler's Fallacy). This leads to winning-streaks and losing-streaks which last far longer than you would expect intuitively and often have a tendency to *feel* much longer than the player finds plausible (this effect is known as the Clustering Illusion).

Although both are psychological phenomenons where the game is working as intended and the player's perception of the game is skewed, we as game designers do well when we work around these and instead try to make the randomness in our games *feel* right and not *be* right. We have an interesting question with various techniques to mitigate this streak-effect and have rare events happen with pauses between them.
> 1 votes

---
Tags: game-mechanics, random
---


# Question
Title: Convert a modified Transform.forward to world space
I am trying to make an electricity system, where it is given the start and end points, and it works out a random sequence of points in the rough direction of the end point. These points are set as vertices on a line renderer, and it should end up joining up as a bolt of electricity. My problem is that it needs to move 'forward' from start to end. The easy solution is that the electricity comes from a game object, which is set to `LookAt` the end point. Then, every time it sets a 'nextPoint', it adds to the transform.forward.

```
nextPoint = new Vector3 ((startingPoint.forward.x + divergence.x),
        (startingPoint.forward.y + divergence.y), distance);

```

`divergence` is a `Vector3` containing a random increase on the x and y axis, and 1 on the z axis.

This works, in a way. The problem is that it then assumes these are world-space coordinates. So the line will go from starting point, to (eg. 0.3, 0.75, 1), and then back to the end point. I can't find a *localToWorld* conversion for a vector though, so I am not sure how to get the transform.forward + whatever, converted from local to world space.

# Answer
What is happening is that your `nextPoint` vector is not actually describing a point in world space; it is describing a direction and distance away from your starting point. So in order to get the world space position of where this vector is pointing to, take the world space position of your starting point, then add your offset vector to it:

```
nextPoint = startingPoint.position + new Vector3((startingPoint.forward.x +
        divergence.x), (startingPoint.forward.y + divergence.y), distance);

```

Side note: Instead of making a game object and setting its rotation with `LookAt`, then using the forward vector, you can also very easily calculate the direction vector yourself. Your underlying question is "Starting from `startingPoint`, in which direction do I have to go to reach `endPoint`?" Given two Vector3s, `startingPoint` and `endPoint`, the direction from start to end is simply:

```
Vector3 direction = (endPoint - startPoint).normalized;

```

This will give you a vector that is pointing in the correct direction, normalized to have a length of 1; exactly how `Transform.forward` works.

If you would like to know how far the two points are apart (for example so you can evenly space a certain number of points between then), you can get the length of the direction vector like so:

```
float distance = (endPoint - startPoint).magnitude;

```
> 1 votes

---
Tags: unity, vector
---


# Question
Title: Is keeping all my game art in a static class wasting memory?
When I make games, I generally create a static class called Art that has static fields to track all content in the game. For example

```
public static class Art
{
    public static SpriteFont defaultFont;

    public static Texture2D playerSprite;

    public static void LoadContent(ContentManager content)
    {
        defaultFont = content.Load<SpriteFont>("Fonts/DefaultFont");
        playerSprite = content.Load<PlayerSprite>("Sprites/PlayerSprite");
    }
}

```

My question is do these objects in my art class take up memory for the duration of the games lifetime? The point of this class is to only have to load my art once in the game and have easy access to the assets anywhere in my project, but at what cost?

# Answer
When `LoadContent` works as advertised, then it seems to load all resources from disk into memory.

The result will be a longer load-time at the beginning of the game, but far shorter load-times during playing. Whether or not this is a good tradeoff depends on how the players play your game. When it's a game you play for hours in one session, players would certainly prefer shorter ingame loading times. When it's a game you just play for a few minutes, players whould rather prefer a fast startup.

Having everything in memory at once *could* cause you to run out of RAM. Whether or not this will happen depends on how large your assets are (note that filesize does not necessarily correspond with memory requirement after loading) and how much RAM your target platform usually has.

An alternative would be "lazy loading". Instead of loading all assets at startup, you load resources when they are first requested. You would usually do that by calling a function to obtain an asset. This could look something like this:

```
public static class Art
{
    private static HashMap<String, Sprite> spriteCache = new HashMap<String, Sprite>();

    public static Sprite getSprite(filename) {
        // look in sprite cache if sprite was already loaded before
        Sprite sprite = spriteCache[filename];
        if (sprite == null) {
              // sprite wasn't found. load it now.
              sprite = content.Load(filename);
              spriteCache[filename] = sprite;
        }
        return sprite;
    }
}

```

Warning: This implementation is not thread-safe. It will load the same resource multiple times in parallel when requested by multiple threads at once

The upside is that you won't have any loading screens at all, because nothing gets preloaded. The downside is that the game will start to lag whenever a lot of unloaded stuff appears in the game for the first time. When your game needs almost all assets on startup, then you will end up with the same loading time as before.

You will also end up with the same memory usage as before when the player plays for a long time and sees every art asset you have. To prevent this "memory leak" effect your Art class could keep track of the time each asset was requested last and automatically unload those which were not requested for a while. When you go down that route, make sure that *every* use of an asset goes through your Art class and no other class keeps own references to assets. Otherwise the Art class could *think* an asset is no longer used even though something uses it all the time but does so through a reference it owns itself.
> 2 votes

---
Tags: memory
---


title: Reference to a particular Prefab clone

text:
# Question
Title: Reference to a particular Prefab clone
I am developing a simple 2D game. In game, I've created a prefab for charcaters. and I am changing sprite of prefab runtime. This all execute fine. Now I want to apply click event on a particular prefab clone and want to increase scale of prefab. I am attaching a c# script what I have did till now.

```
[System.Serializable]
public class Shopping
{
    public string CharacterName;
    public Sprite CharacterSprite;
}

public GameObject CharacterPrefab;
public Transform CharacterSpacer;

public List<Shopping> ShoppingList;

private CharacterScript NewCharacterScript;

/*********************************************Awake()******************************************/
void Awake()
{
    MakeSingleton ();
}

/******************************Create object of the script**********************************/
void MakeSingleton()
{
    instance = this;
    DontDestroyOnLoad (gameObject);
}

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

void LoadCharacters()
{
    foreach (var characters in ShoppingList) {
        GameObject NewCharacter = Instantiate (CharacterPrefab) as GameObject;

        NewCharacterScript = NewCharacter.GetComponent<CharacterScript> ();
        NewCharacterScript.CharacterName = characters.CharacterName;
        NewCharacterScript.Charcater.GetComponent<Image> ().sprite = characters.CharacterSprite;

        NewCharacterScript.GetComponent<Button> ().onClick.AddListener (() => CharacterClicked (NewCharacterScript.CharacterName, NewCharacterScript.Charcater));

        NewCharacter.transform.SetParent (CharacterSpacer, false);
    }
}

void CharacterClicked(string CharacterName, GameObject Char)
{
    StartCoroutine (IncreaseScale (Char));
}

IEnumerator IncreaseScale(GameObject TempCharacter)
{
    int i = 5;
    while (i > 0) {
        yield return new WaitForSeconds (0.1f);

        Vector3 TempVector = TempCharacter.GetComponent<RectTransform> ().localScale;
        TempVector.x = TempVector.x + 0.2f;
        TempVector.y = TempVector.y + 0.2f;
        TempCharacter.GetComponent<RectTransform> ().localScale = TempVector;

        i--;
    }
}

```

This code triggers click event and also it increases scale but of last clone, not of clicked prefab clone. What I am missing, I can't understand. What should I correct in this. and Yeah! I am also attaching code of a script that I've added on prefab.

```
public class CharacterScript : MonoBehaviour {

public string CharacterName;
public GameObject Charcater;
}

```

# Answer
The problem is solved using OnMouseDown() method. Attach this script on the object oon which you want to trigger click event. Don't forget to add collider on that object.

```
public class MouseDownEffect : MonoBehaviour {

[SerializeField]
private GameObject TempCharacter;

void OnMouseDown()
{
    StartCoroutine (IncreaseScale ());
}

IEnumerator IncreaseScale()
{
    int i = 5;
    while (i > 0) {
        yield return new WaitForSeconds (0.1f);

        Vector3 TempVector = TempCharacter.GetComponent<RectTransform> ().localScale;
        TempVector.x = TempVector.x + 0.2f;
        TempVector.y = TempVector.y + 0.2f;
        TempCharacter.GetComponent<RectTransform> ().localScale = TempVector;

        i--;
    }
}

```

}
> -1 votes

---
Tags: unity
---


# Question
Title: How to apply Collider to Particle and what components are needed for particles?
**i want to apply collider to particle system** because if i applied the collider to particle ,if any other game object touched to that particle its gives some action or do some operation.so only i need.

# Answer
> 1 votes
In the particle system component properties you can find a tab that is called collision, then you just tick it and set it to world space, and in order to be detectable you could add a tag to the particle system and make other objects check for the collision with the objects with that tag.

# Answer
> 1 votes
You need to activate the Collision under particle system component itself and set the Collision to be 'World' for particle system component and also check the 'Send Collision Message' check box under Collision. Refer this url

http://answers.unity3d.com/questions/715622/world-particle-system-collider-what-am-i-missing.html

---
Tags: unity, particles, monodevelop
---


# Question
Title: Can't work with universal tween engine while having added it to gradle
I'm actually developing a game with libgdx and I'd like to create a splash screen. To do this, I must use the Universal Tween Engine. To add the Universal Tween Engine, I followed the instructions of the libgdx doc at this link: https://github.com/libgdx/libgdx/wiki/Universal-Tween-Engine

I created a new directory called "libs" in my project directory (not with Eclipse) and put on it the universal tween engine files I got by downloading the universal tween engine. At this time, I had this:

After that, I made the edits in the dependencies sections of "build.gradle" (by adding this: compile fileTree(dir: '../libs', include: '\*.jar') )

Then I tried to refresh the gradle dependencies (by right clicking on my core and android projects and pressing "refresh".)

After restarting eclipse, I tried to work with the universal tween engine by trying to import some of the tween engine (I typed on the top of my main class "import aurelienribon.tweenengine.TweenAccessor;").

The problem is that I got a problem message saying "the import aurelienribon cannot be resolved", even after trying to fix the project setup, I got a message saying that this problem is unresolvable.

What shall I do?

Thanks for your answers.

# Answer
> 2 votes
So the solution I found:

1. Re-build the project with GDX setup
2. Import project
3. added the following to the build.gradle in the project root under the "android" dependencies and the "core" dependencies section.
4. clean project
5. Select all gradle projects, right click on them, gradle-\>refresh dependencies

That sorted it for me...

```
compile fileTree(dir: '../libs', include: '*.jar')

```

Implemented like this:

```
buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }

    dependencies {
        classpath 'de.richsource.gradle.plugins:gwt-gradle-plugin:0.6'
        classpath 'com.android.tools.build:gradle:1.0.0'
        classpath 'org.robovm:robovm-gradle-plugin:1.0.0-beta-03'
    }
}

allprojects {
    apply plugin: "eclipse"
    apply plugin: "idea"

    version = '1.0'

    ext {
        appName = 'Tiddalick'
        gdxVersion = '1.5.3'
        roboVMVersion = '1.0.0-beta-03'
        box2DLightsVersion = '1.3'
        ashleyVersion = '1.3.1'
        aiVersion = '1.5.0'
    }

    repositories {
        mavenCentral()

        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }

        maven {
            url "https://oss.sonatype.org/content/repositories/releases/"
        }
    }
}

project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
    }
}

project(":android") {
    apply plugin: "android"

    configurations {
        natives
    }

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"

        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"

        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"

        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"

        compile fileTree(dir: '../libs', include: '*.jar')
    }
}

project(":ios") {
    apply plugin: "java"
    apply plugin: "robovm"

    configurations {
        natives
    }

    dependencies {
        compile project(":core")
        compile "org.robovm:robovm-rt:${roboVMVersion}"
        compile "org.robovm:robovm-cocoatouch:${roboVMVersion}"
        compile "com.badlogicgames.gdx:gdx-backend-robovm:$gdxVersion"

        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-ios"
    }
}

project(":html") {
    apply plugin: "gwt"
    apply plugin: "war"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d-gwt:$gdxVersion:sources"
    }
}

project(":core") {
    apply plugin: "java"

    dependencies {
        compile "com.badlogicgames.gdx:gdx:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"

        compile fileTree(dir: '../libs', include: '*.jar')
    }
}

tasks.eclipse.doLast {
    delete ".project"
}

```

# Answer
> -1 votes
## It is very easy to resolve.

Step-1: select whole project \>right click\> gradle \>**Refresh Dependency**
Step-2: right click on error \> **Fix Project Setup**

you are done!

---
Tags: java, libgdx, gradle
---


# Question
Title: Convert Minimap render texture to 3d space position
I am using **Render Texture** to make a Mini Map it is working fine. Now I want world space position from render texture click point.

**Is there any way available that I get the world space position from the render texture's specific click point?**

If I click somewhere in render texture then, how can I get that point in 3D world space?

For example, I click a car object on render texture How can I highlight or get it in 3D world space.?

Update: Actual Scenario is:

1. One Main Camera Rendering the Scene.
2. NGUI Camera Rendering the GUI.
3. That GUI contains the Render Texture(minimap) which rendering the scene on texture using GUI Camera.

Now how can I get 3D position from 2D render texture!

# Answer
> 1 votes
I am not aware of an easy way of doing this. The way I'd do this is the following:

* Determine XY position of click on texture (x = 0..1, y = 0..1) How to do this depends on where you use it, but will likely require raycasting.
* Go to the camera that sends the image to the texture.

**Assuming the camera uses perspective projection:**

* Calculate the 3D position on the camera's far plane that is at position x and y (xy was derived earlier from the texture)
* Do a raycast from the camera's position to this calculated position on the far plane.
* The first position it hits (in 3D) is the 3D position of what was clicked on. If nothing is hit, then it's the position on the far plane.

**Assuming the camera uses orthogonal projection:**

* Determine XYZ position of point on the near plane that is at the XY position, determined from the template
* Determine XYZ position of point on the far plane that is at the XY position, determined from the template
* Do a raycast from the position on the near plane to the one on the far plane.
* The first position it hits (in 3D) is the 3D position of what was clicked on. If nothing is hit, then it's the position on the far plane.

Now determining all of this requires some knowledge of vector math. I'm however not aware of any simpler way of doing it, at least if you want to use the Rendered Texture. It may be easier to do if you simply overlay the camera's output on the main viewport (by setting Viewport Rect parameters on the minimap camera)

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


# Question
Title: Calculating vertex normals to be able to have both sharp edges and smooth gradients
I'm computing area-weighted vertex normals, but lighting looks bad on meshes containing sharp edges and corners (e.g. cubes look 'blobby' as the light leaks onto the dark sides).

Is there a way of calculating/using vertex normals to preserve sharp edges and still have smooth regions? Ideally, without the need to create extra geometry (e.g. splitting faces adjacent to a sharp edge and creating new vertices).

Most sources talk about having different 'smoothing groups' which influence geometry generation.

Could someone explain what are "per-corner" normals? From Libigl tutorial: "Storing normals per-corner is an efficient and convenient way of supporting both smooth and sharp (e.g. creases and corners) rendering."

# Answer
The only way I can think of preserving sharp edges using an algorithm is to have some kind of threshold of maximum angle between normals. But this is kind of auto generating smoothing groups anyway. I also cant see this being effective unless your geometry is a mixture of very smooth + very angular.

Essentially when you render a tri you would have 3 verts & 3 vert normals. So if two tri's are joined on one edge, and you want that edge to be a hard edge ( no smoothing ) then you will have 4 verts but 6 normals. If you see what I mean? So I guess its not that you're duplicating geometry. You share verts but have new normals.

So if you think about a cube corner. Although the vert is in one place, there are three faces atatched to it, each facing a different direction. You can share the vert but you'll need the 3 normals.

So a smoothing group is a bunch of tri's where each vert has its own single normal.

You could have geometry in another smoothing group which shared the same verts.
> 1 votes

# Answer
One way it to make seams everywhere you want a sharp corner. In fact you are going to need to do that anyway in the game if you want to use a a GPU for rendering.

With seams I mean storing the vertexes on the edges you want sharp twice (one for the polygons on each side of the edge).
> 1 votes

---
Tags: 3d-meshes, normals
---


# Question
Title: Object automatic create new with old every time when load / save game.?
My problem with this DontDestroyOnLoad(cube.gameObject); When I load my player position its create new object with default and saved position respectively. I have a screen shot for better understand.

First scene without save

Second scene with save game.

Here is my code.

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine.SceneManagement;
using System.Collections.Generic;

public class Player : MonoBehaviour {

public static float speed;
//public static Player control;
public float moveSpeed = 10f;
public float turnSpeed = 50f;
public Transform cube;
public float x, y, z,x1 ,y1, z1;
public int s;

//public static List<Game> savedGames = new List<Game>();
public static Player Instance;
// Use this for initialization

// Update is called once per frame

void OnTriggerEnter(Collider other) {

    if(other.tag == "Player1"){
        DontDestroyOnLoad(cube.gameObject);
        //DontDestroyOnLoad (other.gameObject);
    }
}

void Awake ()
{

    if (Instance == null) {
        DontDestroyOnLoad (this.gameObject);

    } else {
        DestroyObject(gameObject);
    }
}

public void Start () {
    speed = 50f;
}

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

    if(Input.GetKey(KeyCode.W))
        transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);

    if(Input.GetKey(KeyCode.S))
        transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);

    if(Input.GetKey(KeyCode.A))
        transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);

    if(Input.GetKey(KeyCode.D))
        transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);

    }

public  void Save(){

    //Player.savedGames.Add ();
    BinaryFormatter bf = new BinaryFormatter ();
    FileStream fs = File.Create ("D:/playerinfo3.txt");

    playerData pd = new playerData ();
    PlayerPrefs.SetInt ("currentscenesave",SceneManager.GetActiveScene().buildIndex);

    PlayerPrefs.SetFloat ("cubeposx",cube.position.x);
    PlayerPrefs.SetFloat ("cubeposy",cube.position.y);
    PlayerPrefs.SetFloat ("cubeposz",cube.position.z);
    PlayerPrefs.SetFloat ("cuberotx",cube.eulerAngles.x);
    PlayerPrefs.SetFloat ("cuberoty",cube.eulerAngles.y);
    PlayerPrefs.SetFloat ("cuberotz",cube.eulerAngles.z);

    pd.x = PlayerPrefs.GetFloat ("cubeposx");
    pd.y = PlayerPrefs.GetFloat ("cubeposy");
    pd.z = PlayerPrefs.GetFloat ("cubeposz");
    pd.x1 = PlayerPrefs.GetFloat ("cuberotx");
    pd.y1 = PlayerPrefs.GetFloat ("cuberoty");
    pd.z1 = PlayerPrefs.GetFloat ("cuberotz");
    pd.s = PlayerPrefs.GetInt ("currentscenesave");

    SceneManager.LoadScene (pd.s);
    bf.Serialize (fs,pd);
    fs.Close ();

}

  public void Load(){
    //transform.position = new Vector3 (PlayerPrefs.GetFloat ("cubeposx"), PlayerPrefs.GetFloat ("cubeposy"), PlayerPrefs.GetFloat ("cubeposz"));
    if(File.Exists("D:/playerinfo3.txt"))
    {

        BinaryFormatter bf = new BinaryFormatter ();
        FileStream fs = File.Open ("D:/playerinfo3.txt",FileMode.Open);
        playerData pd = (playerData)bf.Deserialize (fs);
        pd.x  = PlayerPrefs.GetFloat ("cubeposx");
        pd.y = PlayerPrefs.GetFloat ("cubeposy");
        pd.z = PlayerPrefs.GetFloat ("cubeposz");
        pd.x1 = PlayerPrefs.GetFloat ("cuberotx");
        pd.y1 = PlayerPrefs.GetFloat ("cuberoty");
        pd.z1 = PlayerPrefs.GetFloat ("cuberotz");
        fs.Close ();
        SceneManager.LoadScene (PlayerPrefs.GetInt ("currentscenesave"));
        cube.position = new Vector3 (pd.x,pd.y,pd.z);
        cube.rotation = Quaternion.Euler (pd.x1,pd.y1,pd.z1);

        Debug.Log ("currentscenesave"+ " "+ pd.s);
        Debug.Log ("currentscenesave"+ " "+ pd.x);
        Debug.Log ("currentscenesave"+ " "+ pd.y);
        Debug.Log ("currentscenesave"+ " "+ pd.z);
    }

  }

  [Serializable]
  class playerData{

    public float x, y, z;
    public float x1, y1, z1;
    public int s;

 }

}

```

# Answer
> 0 votes
You can solve this by using the ability of the SceneManager to load scenes additively.

Create one base-scene with everything which is supposed to be present in every level (like the player-character, for example). Nothing in this scene requires `DontDestroyOnLoad`.

Create every level as a separate scene. Those scenes should not contain anything from the base-scene.

When you switch to another level (savegame, level select, game progression or otherwise), first unload the previous level (if loaded) with `UnloadScene(currentLevel)`. Then load the new level with `SceneManager.LoadScene(newLevel, LoadSceneMode.Additive)`.

`LoadSceneMode.Additive` loads the scene without destroying anything in the previous scene. When you then unload a scene which was previously loaded this way, anything which originates from a different scene stays intact. This allows you to switch out your levels without losing anything from the base-scene.

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


# Question
Title: Is object space the same as local space?
I was in directx 11 and was wondering is local space the same as object space and if not, what is object space?

# Answer
> 2 votes
"Object space" is generally used to refer to the coordinate space that a model or collection of geometry is defined within. Another way to think of this would be the space that the object was created in, where the origin is some useful point within or relative to the object, such as its center, or the place where the model would "touch the ground" when positioned in the world, et cetera.

"Local space" is sometimes synonymous with object space, if you're talking geometry. However, in some specialized contexts it could also be used to refer to any other coordinate system if there is an important distinction to be made between "this" system (the local one) and "that" system (the other one). However this will generally be made apparent explicitly or from the context.

Assuming "local space" refers to "object space" is probably a generally safe assumption. "Model space" is another term you might here.

---
Tags: directx11, terminology
---


# Question
Title: Is it a bad idea to "map" the mouse position on the screen so that collision detection works regardless of resolution?
Consider a game who's default resolution is 800x600. Objects with collision masks are placed in a game world of size 800x600. The collision masks can detect when the mouse collides with them.

Now consider we scale the game up to 1024x768 (assume we scale the graphics by simply rendering everything to a layer and then scaling the entire layer up at once). We have two options for making the collisions with the mouse work properly in this new resolution:

A.) Scale up the world to 1024x768 and scale every object's collision mask accordingly.

B.) "Map" the mouse position onto the original world (800x600).

By "map" I mean simply scale the mouse position onto the original 800x600 world. So for example, if the mouse position on the *screen* is (1024, 768), then the mouse position in the *world* is (800, 600).

Now obviously, option B requires *way* less computation and is probably less prone to geometric errors, but it also feels kind of "hackish" to me, like there are unforeseen consequences of going with this method that will be hell to fix later on.

Which method should I go with: A, B, or something else?

# Answer
Typically (even for 2d games) there is a separate coordinate system for the game that is independent of the resolution, this is typically referred to as the world space. This allows you to scale to an arbitrary resolution.

The easiest way to achieve this is use a 2D Camera, which is essentially a matrix that defines the transition from world space (your arbitrary units) to screen space (the pixels on the screen). This makes dealing with the math trivial.

Take a look at the below section in XNA 2d Camera Scrolling - why use matrix transform?

## It makes it really easy to convert between coordinate system definitions

To go from screen to world space simply use Vector2.Transform. This is commonly used to get the location of the mouse in the world for object picking.

```
Vector2.Transform(mouseLocation, Matrix.Invert(Camera.TransformMatrix));

```

To go from world to screen space simply do the opposite.

```
Vector2.Transform(mouseLocation, Camera.TransformMatrix);

```

There is no drawbacks to using a matrix other than it takes a little learning.
> 38 votes

# Answer
Another option would be: On each input mouse movement event, move the in-game mouse cursor by the number of game pixels corresponding to the number of pixels in the mouse event. This comes naturally for 3D games that lock the real mouse pointer to the center and rotate the aim direction by an amount corresponding to the input mouse movement, but you could do it the same way by moving a sprite representing the in-game mouse cursor.

You obviously have to ignore any input mouse movement events caused by warping it to the center, and if your game has any input lag at all the cursor unresponsivity will be the most jarring and noticeable aspect.

Partially, what solution you use depends on how important the mouse position is to gameplay. If this is an RTS and the player is simply clicking to select units, you can probably simply go with whichever of your A or B is easier. If it's a top-down shooter and the mouse directly controls the character's movements, then you will probably want a more in-depth solution that limits the amount of variability in how the character can move based on not only resolution but also things like mouse movement speed. If the mouse controls targeting direction instead, then you'll want a different solution, etc.
> 2 votes

# Answer
ClassicThunder's answer is correct, but I'd like to provide an example of an alternative/simpler means of achieving the desired effect. This is a simpler solution for rapid prototyping, cases where you don'thave access to a fully featured library, or for cases where you don't have access to a GPU (e.g. in embedded systems).

To perform said mapping, you can use the following function (assume it to be defined in the static class `Helper`):

```
static float Map(float value, float fromLow, float fromHigh, float toLow, float toHigh)
{
    return ((value - fromLow) / (fromHigh - fromLow) * (toHigh - toLow)) + toLow;
}

```

(You didn't specify a language, but I see you have some knowledge of C#, so my example is in C#.)

You can then use this function like so:

```
float mouseXInWorld = Helper.Map(Mouse.X, 0, Screen.Width - 1, camera.Bounds.X, camera.Bounds.X + camera.Bounds.Width - 1);
float mouseYInWorld = Helper.Map(Mouse.Y, 0, Screen.Height - 1, camera.Bounds.Y, camera.Bounds.Y + camera.Bounds.Height - 1);

```

Where `camera.Bounds` is a rectangle representing the area of the world the camera can see (i.e. the area being projected onto the screen).

If you have a `Vector` or `Point` class, you could simplify this process further by creating a 2D equivalent of the map function, like so:

```
static Vector Map(Vector value, Rectangle fromArea, Rectangle toArea)
{
    Vector result = new Vector();
    result.X = Map(value.X, fromArea.X, fromArea.X + fromArea.Width - 1, toArea.X, toArea.X + toArea.Width - 1);
    result.Y = Map(value.Y, fromArea.Y, fromArea.Y + fromArea.Height - 1, toArea.Y, toArea.Y + toArea.Height - 1);
    return result;
}

```

Which would make your mapping code a simple one liner:

```
Vector mousePosInWorld = Map(Mouse.Pos, Screen.Bounds, camera.Bounds);

```
> 0 votes

# Answer
Option (C): change the screen resolution back to 800x600.

Even if you don't do this, consider it as a thought experiment. In that case, it's the responsibility of the display to resize the graphics to fit its physical size, and then the responsibility of the operating system to give you pointer events at an 800x600 resolution.

I think it all depends on whether your graphics are bitmap or vector. If they're bitmap, and you're rendering to an 800x600 buffer, then yes it's much easier to remap the mouse into screen space and ignore the real screen resolution. However the big downside of this is that the upscaling can look ugly, especially if you're doing blocky "8-bit" style graphics.
> -1 votes

---
Tags: collision-detection, resolution
---


title: Opentk Textured Full Screen Quad

text:
# Question
Title: Opentk Textured Full Screen Quad
I want to display a texture on a full screen quad. What I get is a completely green quad and after a week of debugging I cannot understand why.

I am currently using OpenTK 1.1.2225 and Magick.NET-Q16-HDRI-AnyCPU.

My class extends GameWindow. I report here the methods I use.

```
class SelectiveEnvironmentMapping : GameWindow
{
    int textureID, shaderProgram, quadVAO;
    float exposure = 1.0f;

    float[] quadVertices = {
        // Positions        // Texture Coords
        -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
        -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
        1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
        1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
    };

    public SelectiveEnvironmentMapping() : base(800,600,new GraphicsMode(),"My Title",GameWindowFlags.Default)
    { }

    protected int LoadShaderProgram(string VSSource, string FSSource)
    {
        int program = GL.CreateProgram();
        int vshader = GL.CreateShader(ShaderType.VertexShader);
        int fshader = GL.CreateShader(ShaderType.FragmentShader);
        GL.ShaderSource(program, VSSource);
        GL.ShaderSource(program, FSSource);
        GL.CompileShader(vshader);
        GL.CompileShader(fshader);
        int success;
        GL.GetShader(vshader, ShaderParameter.CompileStatus, out success);
        if(success != 1)
        {
            Console.WriteLine("vshader not compiled");
            Console.WriteLine(GL.GetShaderInfoLog(vshader));
        }
        GL.GetShader(fshader, ShaderParameter.CompileStatus, out success);
        if (success != 1)
        {
            Console.WriteLine("fshader not compiled");
            Console.WriteLine(GL.GetShaderInfoLog(fshader));
        }
        Console.WriteLine(GL.GetShaderInfoLog(vshader));
        Console.WriteLine(GL.GetShaderInfoLog(fshader));
        GL.AttachShader(program, vshader);
        GL.AttachShader(program, fshader);
        GL.LinkProgram(program);
        return program;
    }

    protected override void OnLoad(System.EventArgs e)
    {
        try
        {
            Console.WriteLine(ClientSize.Width + " " + ClientSize.Height);
            Console.WriteLine(GL.GetString(StringName.Version));
            Console.WriteLine(GL.GetString(StringName.ShadingLanguageVersion));
            GL.Viewport(0, 0, ClientSize.Width, ClientSize.Height);
            VSync = VSyncMode.On;
            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Less);

            // Setup quad VAO
            quadVAO = GL.GenVertexArray();
            int quadVBO = GL.GenBuffer();
            GL.BindVertexArray(quadVAO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, quadVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, quadVertices.Length * sizeof(float), quadVertices, BufferUsageHint.StaticDraw);
            GL.EnableVertexAttribArray(0);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 5 * sizeof(float), 0);
            GL.EnableVertexAttribArray(1);
            GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 5 * sizeof(float), 3 * sizeof(float));

            MagickImage img = new MagickImage(@"../../Cubemaps/GravelPlaza_REF.jpg");

            float[] data = img.GetPixels().ToArray();

            textureID = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, textureID);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, width, height, 0, PixelFormat.Rgb, PixelType.UnsignedByte, data);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, Convert.ToInt32(TextureWrapMode.Repeat));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, Convert.ToInt32(TextureWrapMode.Repeat));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, Convert.ToInt32(TextureMinFilter.Linear));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, Convert.ToInt32(TextureMagFilter.Linear));

            GL.BindTexture(TextureTarget.Texture2D, 0);

            string vsource = File.ReadAllText(@"../../Shaders/MyVShader.glsl");
            string fsource = File.ReadAllText(@"../../Shaders/MyFShader.glsl");
            shaderProgram = LoadShaderProgram(vsource, fsource);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

    protected override void OnRenderFrame(FrameEventArgs e)
    {
        GL.ClearColor(Color.Purple);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.UseProgram(shaderProgram);
        GL.ActiveTexture(TextureUnit.Texture0);
        GL.BindTexture(TextureTarget.Texture2D,textureID);

        GL.BindVertexArray(quadVAO);
        GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
        GL.BindVertexArray(0);
        SwapBuffers();

    }

    public static void Main()
    {
        try
        {
            using (SelectiveEnvironmentMapping p = new SelectiveEnvironmentMapping())
            {
                p.Run(60);
            }
      }
}

```

My Vertex Shader:

```
#version 400
layout(location = 0) in vec3 position;
layout(location = 1) in vec2 texCoords;

out vec2 TexCoords;

void main()
{
    gl_Position = vec4(position.x, position.y, 0.0f, 1.0f);
    TexCoords = texCoords;
}

```

And my Fragment Shader:

```
#version 400
out vec4 color;
in vec2 TexCoords;

uniform sampler2D text;

void main()
{
    color = vec4(texture(text,TexCoords),1.0);
}

```

EDIT: there was a typo in the LoadShaderProgram function (on this post, not on my code).

EDIT2: Found out that my shaders don't compile and no infolog is showed, i tried this

`int success;
 GL.GetShader(vshader, ShaderParameter.CompileStatus, out success);
 if(success != 1)
 {
 Console.WriteLine("vshader not compiled");
 Console.WriteLine(GL.GetShaderInfoLog(vshader));
 }`

and the output was "vshader not compiled" and that's it. No apparent reasons.

# Answer
> 1 votes
In glsl, the `texture` function returns a vec4, thus you provide too much arguments to the vec4.

It should be

```
color = texture(sampler, texCoord);

```

To avoid issues like this, always print out what glGetError returns.

Second problem:

Guess what GL.ShaderSource takes in as arguments. A **shader**, and you provided a shader **program** to it.

# Answer
> 0 votes
Line 5 and 6 of LoadShaderProgram() contain a copy/paste error.

```
    GL.ShaderSource(program, VSSource);
    GL.ShaderSource(program, FSSource);

```

Should be instead:

```
    GL.ShaderSource(vshader, VSSource);
    GL.ShaderSource(fashader, FSSource);

```

---
Tags: opengl, textures, opentk
---


title: ScreenSize vs. WorldSize

text:
# Question
Title: ScreenSize vs. WorldSize
While programming a game with LibGDX, I came across a problem. My OrthographicCamera wasn't centering in the right place. I was trying to center the camera by using the line of code:

```
gameCam.position.set(gamePort.getScreenWidth() / 2, gamePort.getScreenHeight() / 2, 0);

```

But that centered the camera at (0, 0) so that you could see all four quadrants of the coordinate table.

Here is the image:

NOTE: I am using a `FitViewport` that was initialized like `gamePort = new FitViewport(MarioBros.V_WIDTH, MarioBros.V_HEIGHT, gameCam);`

Also: `public static final int V_WIDTH = 400;
 public static final int V_HEIGHT = 208;` (in the MarioBros class)

But after some fiddling with the code, I changed the line of code to this:

`gameCam.position.set(gamePort.getWorldWidth() / 2, gamePort.getWorldHeight() / 2, 0);` I changed it from `ScreenSize` to `WorldSize` and got this result:

I'm still unsure of what using `WorldSize` changed.

What's the difference between the two?. Also, why did one work while the other didn't?

# Answer
The difference between `ScreenSize` and `WorldSize` is part of the brilliance of graphics systems like OpenGL.

`ScreenSize` is the actual size of the window in pixels. When the user grabs the window handles and resizes the window, then `ScreenSize` will change.

`WorldSize` is the size of your game level or "World". It is completely arbitrary. In a 2D game, 1 unit in your game world will generally mean 1 pixel on your game map, but depending on how you setup your world, you could use whatever units you wanted to.

Libgdx very helpfully makes it so you really don't have to worry about the `ScreenSize` when writing your game. After all, depending on the computer they are using, your users will have vastly different screen sizes. When you create a `FitViewport`, you are saying "No matter what the user's `ScreenSize` is, I want the screen camera to be V\_HEIGHT world units tall and V\_WIDTH world units wide. If you are using an `OrthographicCamera`, this means that your camera will always show V\_HEIGHT x V\_WIDTH world units of your world. `FitViewport` then automagically fits your camera into the user's window.

`FitViewport's` `getWorldWidth()` and `getWorldHeight()` are perhaps named a little inappropriately. They are getting the width and height of the viewport in world units. Not the entire width and height of your world. Essentially, these functions are just returning V\_WIDTH and V\_HEIGHT that you gave it in the constructor.

Note that the World can be much bigger than the V\_HEIGHT and V\_WIDTH dimensions because not all of the World will be visible at once. So if you make your level bigger and you want to start the camera off at the bottom left corner of the level, then you will want to position it at V\_HEIGHT/2 and V\_WIDTH/2 (assuming of course that your map is drawn at the origin).

One last thing. Even though you can mostly forget about the screen size, if the user resizes the window, then you have to notify your viewport. You do this by overriding the `resize(int width, int height)` method of your `ApplicationListener` class and calling

```
gamePort.update(width,height);

```
> 3 votes

---
Tags: libgdx, camera, maps, viewport
---


title: LibGDX How do I create a Shop?

text:
# Question
Title: LibGDX How do I create a Shop?
My game is fully working but now I want to make a shop so that the player can buy boosts or other useful stuff for the money the player has collected.

What is the best way of doing this kind of shops:

\*The collected coins you have saved goes up/down in value when you buy something

\*The item activates if bought.

Is this possible in libGDX and how can I start?

# Answer
You can store the values in a database,It is simple if you use database like sqlite but that wont work with libgdx -android.

Instead you can use gdx-sqlite

gdx-sqlite is a cross-platform Libgdx extension for SQLite database handling. The extension abstracts databse handling to provide a unified method to handle database transacitons across multiple platforms while also adding SQLite support for desktop version of Libgdx application.
> 1 votes

---
Tags: android, libgdx
---


# Question
Title: How can I tune material values with the slider in the Unity inspector more finely?
I'm adjusting a material's texture tiling and offset values in the editor but its increments are too large and it's jumping over the value I need. Is there a way to slow it down or adjust the amount it increments by (without using a custom script)?

# Answer
If the slider is skipping over the value you need, why can't you just enter it in the value box?? It looks like you can also hold ALT down, which will give you some more granularity when using the slider
> 2 votes

---
Tags: unity
---


# Question
Title: How do I render a volumetrically lit spotlight?
To be clear, I really do mean volumetric lighting; not only calculating which area is lit, but also realistically lighting the volume of "air" that the light hits on the way.

Like this:

I've tried are 2 approaches: a *pre-rendered 2D image* and a *3D cone*. The 2D image always looks flat, no matter how it is rotated in world space. The cone on the other hand is next to impossible to control when it comes to fade distance, doesn't look soft (smooth) and is expensive to compute.

Is there a better way?

# Answer
> 3 votes
(Someone else can write a more in-depth answer since these steps require a bit of non-trivial math, but since there's no answer and this question is probably important for some I'll post). There are few ways depending on your scene and how modern you want to go.

You can either render a fullscreen quad naively or render a 2D billboarded rectangle covering the cone's area. In your pixel shader you'd pass in the cone position, direction (both in world space), and color. For every rasterized pixel you'd create a world space ray by creating a camera space ray and transforming by the camera matrix into world space. Then use that ray to intersect with cone based on the uniform cone data you passed in. Extract the front and back face intersection points and calculate the difference. This is your depth. If you only have a backface point then your camera is inside so use the ray's starting position and calculate the difference.

(Note this works even if you're looking into the cone at the light source. In the end it'll appear almost opaque depending on your weights since the depth values are large).

You then need to use https://en.wikipedia.org/wiki/Transmittance#Beer.E2.80.93Lambert\_law. A common mistake is to try to use alpha blending equations with the depth value in someway. If you try using alpha transparency blending you'll notice it produces very unrealistic results. This is very noticeable if you have overlapping cones since there's no formula using alpha blending to treat two mediums as one. Using Lambert's law solves this allowing for multiple overlapping beams to be rendered as you would expect. Just to be very clear you cannot get a realistic result using alpha blending or additive blending techniques. This might be acceptable though for some though. I'm going to use the word depth from here on out, but realize that with lambert the light is going through a medium. If you support multiple different mediums you'll need to pass that in and use it as a weight to the depth. I'm assuming air here everywhere thus some constant absorption weight.

Note that what you'll end up with a kind of murky cone shape that looks like a transparent cone and not a beam. A cone light's intensity will be concentrated at the center of the beam and fall off radially. To take this into consideration there's a few methods. The first is you can sample the distance to the center of the beam starting from the front intersection point and stepping a few times to the back intersection point. At each step you calculate the minimum distance to the light ray and then take the average of all samples. The second approach is to solve the integral for the average distance directly. (I'm not sure the latter has a closed form, but it might). Both approaches give you the average distance to the center of the beam of light.

You'll also need a second average distance which is the average distance to the light position. You can sample along the ray from the front to the back intersection point or solve the integral like before. (This one should have a closed form solution). Lights fall off distance squared so you can optionally use this to weight the intensity if you want the beam to fall off over distance along the light ray. (You can use a weight like secondDistance / maxDistance or square it if you want, but linear falloff sometimes looks better). In any case we need this average for the beam falloff away from the ray direction. (Since it's a cone).

The first distance value can be used with the second to weight the intensity which indicates how close the intersecting ray is to the center of the light's beam along the ray. For the second distance calculate the maximum radius of the cone at that distance. Using this a linear weight can be created that looks like: 1 - (secondDistance / radius). You can use this or a distance squared variant and combine it with the firstDistance weight by multiplying. (You can combine these in many ways to produce different cone properties. You can even run the firstDistance through a max function to make the core of the beam evenly lit like in the image).

Using these two weights you'll end up with a realistic volumetric cone of light probably identical to the image above.

I haven't explained how to handle overlapping or intersecting cones though. I did explain not to use additive blending though. The issue with a forward approach of rendering the cones is you lack the depth information of the previously rendered cone. You can use multiple render targets and render the depth additively such that the next cone, rendered front to back can sample for the the depth information and calculate the opacity weight left from the lambert calculations. (Again this assumes every cone passed through is going through a medium of constant absorption. If that's not the case then you can store a weighted depth value based on absorption and use that instead).

Handling intersecting cones is not simple, but with modern hardware it's very doable. There's an ordered independent transparency (OIT) algorithm that uses append buffers (a-buffers) where instead of rendering front to back all the fragment data is stored in a linked list data structure in the GPU. AMD wrote the initial basics I believe. Instead of storing just the color you'd render each cone and store the color, front face depth z value, and back face depth z value, and optionally the medium's absorption if you're using it. (In reality you'd be storing a linked list of elements with the structure { z:float, color:float3, absorption:float, front:bool } where the front and back faces are separate). Then after rendering all the cones into the OIT linked list in a second pass sort the linked lists then perform the Lambert law blending. (For overlapping z ranges take the average of the colors and add the absorption weights).

I should point out that this works for any volumetric object, not just cones. If you don't want to mathematically compute the front and back faces with the linked list approach you can just render the front and back face meshes and in the pixel shader perform the linked list insertions with the corresponding z values.

I hope I didn't make a mistake in this explanation. I used a technique nearly identical to this in a project a long time ago for a voxel test with volumetrically rendered voxels. I have a simple blending function here: http://ideone.com/PVXdB if the wikipedia article was confusing. In that one volume is a function of depth and absorption.

---
Tags: lighting, graphic-effects, volumetric-light
---


# Question
Title: Why am I getting a down arrow in my Unity scene when using Oculus Rift and how do I get rid of it?
In Unity, I have set up a scene to try out in Oculus Rift. When I hit play in Unity, everything works fine until about 5 seconds later when I get an arrow (Assets\>OVR\>Textures\>out.png) that appears in the center of my screen and won't go away. What does this arrow mean and how can I get rid of it? It is obstructing my view of the level that I am trying to view.

# Answer
dshanker from Unity forums answered this question as follows:

*This is a pretty recent feature in the Oculus Unity integration. It's basically a guide that starts to appear when you approach the bounds of the positional tracking camera. This symbol is basically telling you, "please move your head down, you're near the upper limit of the positional tracker"*
> 1 votes

# Answer
If you are looking at your monitor while developing for vr and you vr headset is off to the side then after a few second, this will appear on screen. I guess the trick is to hold the headset by your chin (assuming you don't want to put it on at the moment) to get a quick look at you environment. dshanker is correct.
> 0 votes

---
Tags: unity, oculus
---


# Question
Title: 10 weapon types, 2 proficiencies, rock-paper-scissors relationship?
I want to make a game where there's a total of 10 general weapon types. I want any given character to be able to be proficient with 2 of the weapon types. Looking at the fact that 10 is an even number, a perfect rock-paper-scissors relationship wouldn't be possible. "C(10,2)=45" however is an odd number, which should be workable into a rock-paper-scissors system.

Since the final number of total weapon pairings is an odd number, I reckon there should be an intuitive and systemically organized way to get a rock-paper-scissors relationship to exist where each weapon pairing is at an advantage against 22 of the other pairings while being at a disadvantage against the remaining 22 pairings. Assuming the 10 weapon types that a character can be proficient with 2 of are labeled A through to J, how should I organize it?

P.S.: A smaller example that runs into the same situation would be "C(6,2)=15"; weapons labeled A through F; if that's more convenient for explanation purposes. Please let me know if this question belongs under different tags or even over on the Mathematics section of SE instead of here; I wasn't sure where to put this question.

# Answer
> 3 votes
The simplest way to do it would be to lay out your weapon combinations in whatever order you see fit in a circular list. Each combination could have a bonus against the 22 combinations after it in the list, and a weakness against the 22 before it.

The player might appreciate a more straight-forward or easier-to-recognise logic to that order -- some sort of pattern.

With your 6 weapon example, you could have:

```
1. AB AC AF
2. BC BD BF
3. CD CE CF
4. DE DA DF
5. EA EB EF

```

Here you have a whole lot of rock-paper-scissors. Every combination of weapons has a "primary" and a "secondary" weapon according to a rock-paper-scissors between the first 5 weapon types, with the 6th weapon type (F) always being secondary (since, as you pointed out, we need an odd number for rock-paper-scissors).

We now have 5 super groups, and can have a simple 5-way rock-paper-scissors between them (group 1 beats groups 2 and 3, 2 beats 3 and 4, and so on).

If two characters are using the same primary weapon, we have a 3-way rock-paper-scissors. The way I've laid it out here, you could have AB beat AC, AC beat AF, and AF beat AB.

Expanding this to 10 weapons, you can divide the 45 combinations into 9 primary weapon groups of 5 combinations, with the 10th weapon always secondary:

```
1. AB AC AD AE AJ
2. BC BD BE BF BJ
3. CD CE CF CG CJ
4. DE DF DG DH DJ
5. EF EG EH EI EJ
6. FG FH FI FA FJ
7. GH GI GA GB GJ
8. HI HA HB HC HJ
9. IA IB IC ID IJ

```

While this kind of pattern may not be super easy to memorise, a well-designed UX could do a lot to make it clear which weapon is a character's primary weapon, which primary weapons beat which other primary weapons, and which secondary weapons beat which other secondary weapons (conveniently in the same order as primary weapons, except for the always-secondary weapon J).

I hope that makes sense!

*With 11 weapon types*, with 55 combinations, which, as you've pointed out, is divisible by the number of weapons, you don't need a special "secondary only" weapon:

```
01. AB AC AD AE AF
02. BC BD BE BF BG
03. CD CE CF CG CH
04. DE DF DG DH DI
05. EF EG EH EI EJ
06. FG FH FI FJ FK
07. GH GI GJ GK GA
08. HI HJ HK HA HB
09. IJ IK IA IB IC
10. JK JA JB JC JD
11. KA KB KC KD KE

```

# Answer
> 2 votes
While Jibb Smart already gave a good answer within the constraints of the question, I would like to step a bit outside the box and question: "Do you actually need perfect balance"? A perfectly *im*balanced system can work too and often makes for far more interesting games.

For example, you can have one weapon combination which is slightly better than 43 others, but has a glaring weakness which can be easily exploited by the otherwise slightly underpowered combination 45. Everyone will play the first combination, until someone with 45 shows up and wipes the floor with them. Then players will look for a counter to 45 and try all kinds of different combinations.

Players will have far more fun with figuring out which combinations stand out of the crowd power-wise and then figure out which other combination can counter them than when you present them a perfectly balanced system where the counter for everything is obvious and in the end their weapon choice doesn't really matter because the ratio of players which are stronger or weaker than them will be 50/50 split in any case.

However, such a system is not easy to create. You really need to know and understand your game mechanics well to not accidentally create a combination which either has no viable counter or doesn't counter anything else.

Extra Credits made a really great video about this concept: "Perfect Imbalance - Why Unbalanced Design Creates Balanced Play"

---
Tags: mathematics, game-design, rock-paper-scissors
---