# Question
Title: How to deal with a many to many relationship between objects
In my game, I keep a list of all clients currently connected to the server and a list of all actors in the game. Each actor is "relevant" ( currently replicating ) to 0 or many clients, and each client has has 0 or many actors that are relevant to it.

In some situations, I want to do something like this:

```
NetworkSystem.AddMulticastRPC( rpcCall, actor.AllRelevantClients );

```

This would send an RPC to all clients who have this actor as relevant.

Sometimes I need to do things like this:

```
foreach( var actor in client.RelevantActors )
{
    ...
}

```

Looping through all relevant actors.

Storing a collection on both the client and actor objects would be a duplication of data. Storing a collection on only one of these leads to some complex searches.

Is there an approach to dealing with data like this that avoids both of those problems?

# Answer
**Plese don't consider it as an anwser yet, for good or bad, I just need some place to tell about half of the problem (duplication)**

I think you need to choose one of them to be the central point, either actor or client (I don't know how to use RPC to tell you how the API would work).

Suppose you choose that an Actors have many clients

```
foreach(var client in actor.AllRelevantClients)
{
    actor.doRPC(client);//work out with true RPC inside a function
}

```

and

```
forech(var client in actor.AllRelevantClients)
{
    actor.foo(client);//or client.foo(actor);
}

```

Invert the types to invert which class is the central point.

What is being referenced could only points to the central point when added

```
class Actor
{
    List<Client> _clients = new List<Client>;
    public void Add(Client client)
    {
        _clients.add(client);
        _clients.actor = this;
    }
}

```
> -2 votes

---
Tags: c#, data-structure
---


title: C++ Saving and Loading From Text File

text:
# Question
Title: C++ Saving and Loading From Text File
In my C++ program I am trying to develop a simple saving and loading function for my game. I can easily get the save function on it, but the loading part of it really stumps me.

What I need is to load the numbers on the file (line by line) and insert them into different variables for my player. I'm just not able to figure that out. I've even looked all around the inter webs.

Here is the code for the player save and load functions:

```
void Player::Save()
{
    std::ofstream savePlayerFile;
    savePlayerFile.open("Save/playerSave.dat", std::ofstream::trunc);

    savePlayerFile << x << "\n" << y << "\n" << prevX << "\n" << prevY << "\n" << health << "\n" <<
    health  << "\n" <<  mana  << "\n" <<  gold  << "\n" <<  level  << "\n" <<  maxHealth << "\n" <<
    maxMana << "\n" << strength << "\n" << defense;

    savePlayerFile.close();
}

void Player::Load()
{
    std::ifstream loadPlayerFile;
    loadPlayerFile.open("Save/playerSave.dat", std::ofstream::in);

    /*std::string line;
    while(std::getline(loadPlayerFile, line))
    {
        std::istringstream iss(line);
        */
    loadPlayerFile >> ( x && "\n" && y && "\n" && prevX && "\n" && prevY && "\n" && health && "\n" &&
    health && "\n" && mana && "\n" && gold && "\n" && level && "\n" && maxHealth && "\n" &&
    maxMana && "\n" && strength && "\n" && defense);
}

```

# Answer
I highly recommend serialization as well, whether you use boost or your own magic.

But, if you want to keep it simple for maybe prototyping sake, you could use streams like you are. You could even make this really easy on yourself and do space delimited. Since you know the format your saving, you simply have to parse it back the same way into whatever vars you want.

For example:

```
save() {
    stream << health << mana;
}

load() {
    stream >> health >> mana;
}

```

Obviously lots of code left out, but you get the idea. You would need to know the types as well, casting or converting as needed. Here is a cpluplus reference to what I'm talking about. http://www.cplusplus.com/reference/sstream/istringstream/istringstream/
> 0 votes

# Answer
It may work to write it on your own like that but that isn't a very flexible approach. If you add variables to the save file, you have to update them twice. This isn't preferable. Also, if you want to change formats, you need to restructure the entire thing.

Personally, I would use the Boost.Serialization library.

It is a very flexible library with more features to boot. It easily lets you use binary formats and xml formats, along with a simple text format not u like the one you suggest.

You could also use it with other parts of your game, instead of writing your own save files.
> 0 votes

---
Tags: c++, loading
---


# Question
Title: Java how to rotate an image towards a certain point?
Hello I have a game where a spaceship flies towards a different point every time I press a button. I am able to rotate the image but I don't know how to rotate the image to face the direction it is going. How can I make the image face towards the target area. Heres my code:

```
public class ship {

    public boolean arrived,sel1,sel2;
    public int amountOfPop = 0;

    public int fc = -1,sc = -1,rot =5;
    private Image img;

    private Vector2 position;
    private Vector2 start;
    private Vector2 target;
    private Vector2 direction;

    private float speed ;

    private float distance;
    public boolean remove;

    public ship(Vector2 position, Vector2 target, float speed,int aop) {
        this.position = position;

        this.start = new Vector2(position.x, position.y);
        this.target = target;

        distance = Vector2.distance(start, target);
        direction = Vector2.direction(target.x - start.x, target.y - start.y);

        this.speed =speed;
        this.amountOfPop = aop;

    }

    public void tick(){

        start.x = position.x;
        start.y = position.y;

        if(play.ds.s1.p.get(play.ds.s1.secondclicked).moon == false){
        target = new Vector2((int)  play.ds.s1.p.get( play.ds.s1.secondclicked).x + 25, (int)  play.ds.s1.p.get( play.ds.s1.secondclicked).y + 25);
        }else{
            target = new Vector2((int)  play.ds.s1.p.get( play.ds.s1.secondclicked).x + 10, (int)  play.ds.s1.p.get( play.ds.s1.secondclicked).y + 10);

        }
        distance = Vector2.distance(start, target);
        direction = Vector2.direction(target.x - start.x, target.y - start.y);

        position.x += direction.x * speed;
        position.y += direction.y * speed;

        if (Vector2.distance(start, position) >= distance) {
                remove = true;
        }

        if(rot >= 360){
            rot = 0;
        }else{
            rot+=5;
        }

    }

    public void render(Graphics g){

        Graphics2D g2 = (Graphics2D) g;

        g.setColor(new Color(255,127,42));
        g.drawLine((int)start.x+7, (int)start.y+7, (int)target.x, (int)target.y);

        AffineTransform at = AffineTransform.getTranslateInstance((int)position.x,(int)position.y );
        at.rotate(Math.toRadians(),7,7);

        ImageIcon i121 = new ImageIcon("res/misc/circle4739.png");
        img = i121.getImage();
        g2.drawImage(img,at, null);

    }
}

```

# Answer
Here's a quick mock up demonstration of vector mathematics in action:

https://dl.dropboxusercontent.com/u/38185080/Flash/Examples/Vector%20Mathematics.swf

Click to move.

Following on from my answer to your previous question here, and applying what @Frank and @David have explained, you can retrieve the angle of rotation by calculating the inverse tangent value of the direction:

```
float angle = Math.atan2(direction.y, direction.x);

```

This value is in Radians, which is represented as a decimal from `-PI` to `PI`. You can convert this into Degrees by using `Math.toDegrees(angle);`. The calculation for converting Radians to Degrees:

```
degrees = radians * 180 / PI;

```
> 0 votes

# Answer
The following answer gives the angle from horizontal. (https://stackoverflow.com/questions/7586063/how-to-calculate-the-angle-between-a-line-and-the-horizontal-axis)

(This will boil down to essentially using the same info David van Brink provided in his comment.)

You might want one that works from the current angle of the ship. Unless the rotation is instantaneous, then you only care about the target heading.

The details of mbecker's comment in the thread above give you a change in angle.

> In my code I'm fix this with:

```
double arc = Math.atan2(mouse.y - obj.getPy(), mouse.x - obj.getPx());
degrees = Math.toDegrees(arc);
if (degrees < 0)
  degrees += 360;
else if (degrees > 360)
  degrees -= 360;

```
> 1 votes

---
Tags: java
---


# Question
Title: How to handle mesh update in its vertex buffer
suppose i have a mesh, it can undergo any kind of changes - bend, stretch, even been torn. How should i update vertex buffer in DirectX for this mesh. For now i recreate it every time, and i don't see any chances for another approach because i don't know what part of vertices array can change between steps.

Is there any known approaches for this problem?

# Answer
> 1 votes
When creating your vertex buffer, specify `D3D11_USAGE_DYNAMIC` and `D3D11_CPU_ACCESS_WRITE` in the buffer description (in Usage and CPUAccessFlags members). This will create you a dynamic vertex buffer, which you can update by `ID3D11DeviceContext::Map` -ping it, copying data to it and `ID3D11DeviceContext::Unmap` -ping at the end. Something like this:

```
ID3d11DeviceContext* context;
ID3D11Buffer* buffer; //your vertex buffer
Your_Data_Type* data; //your vertex array
int dataSize; //size of data to copy
//...

D3D11_MAPPED_SUBRESOURCE mappedResource;
void* dataPtr;
context->Map(buffer,0,D3D11_MAP_WRITE_DISCARD,0,&mappedResource);
dataPtr = (void*)mappedResource.pData;
memcpy(dataPtr,data,dataSize));
context->Unmap(buffer,0);

```

Another option is to create a normal vertex buffer with `D3D11_USAGE_DEFAULT` flag and no cpu access flags and update the buffer by calling `ID3D11DeviceContext::UpdateSubResource`, but it will be slower.
Like this:

```
context->UpdateSubresource( buffer, 0, nullptr, data, 0, 0 );

```

# Answer
> 0 votes
It's called GPU skinning (or a variation of it)

Add several uniforms that represent the changes.

Then add attributes to the vertices that represent how much they are affected by each change.

For example bulging would be going towards the normal vector:

```
outPos = MVP*(pos_in + bulgeFactor * normal * bulgeUniform)

```

---
Tags: directx, directx11, 3d-meshes, vertex-buffer
---


# Question
Title: Transformation problems with hardware instancing in DirectX 11
I'm getting some wonky geometry in my application when trying to use instancing. I'm not sure if I'm doing the mapping of my per instance data wrong. This is how my mapping looks like:

```
XMMATRIX scale          = XMMatrixScaling( 1.0f, 1.0f, 1.0f );
XMMATRIX rotation       = XMMatrixRotationY( mRotation * 10.0f );
XMMATRIX translation    = XMMatrixTranslation( 0.0f, 0.0f, 0.0f );

XMMATRIX finalTransform = scale * rotation * translation;

XMFLOAT4X4 world;

XMStoreFloat4x4( &world, XMMatrixTranspose( finalTransform ) );
mBox->PerInstanceData( world );

D3D11_MAPPED_SUBRESOURCE mappedResource;
hr = mDeviceContext->Map( mPerInstanceBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );

if( SUCCEEDED( hr ) )
{
    memcpy( mappedResource.pData, &mBox->PerInstanceData(), sizeof(PerInstanceData) );
    mDeviceContext->Unmap( mPerInstanceBuffer, 0 );
}

```

I've constructed my input layout like this:

```
D3D11_INPUT_ELEMENT_DESC inputDescInstanced[] = {
            { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "WORLD",    0, DXGI_FORMAT_R32G32B32_FLOAT, 1,  0, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
            { "WORLD",    1, DXGI_FORMAT_R32G32B32_FLOAT, 1, 16, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
            { "WORLD",    2, DXGI_FORMAT_R32G32B32_FLOAT, 1, 32, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
            { "WORLD",    3, DXGI_FORMAT_R32G32B32_FLOAT, 1, 48, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
            { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 64, D3D11_INPUT_PER_INSTANCE_DATA, 1 }
        };

```

And this is how a part of my shader looks like:

```
struct VertexIn
{
    float3              position    : POSITION;
    float3              normal      : NORMAL;

    // Instanced data
    row_major float4x4  world       : WORLD;
    float4              color       : COLOR;
    uint                instanceID  : SV_InstanceID;
};

PixelIn VS( VertexIn input )
{
    PixelIn output = (PixelIn)0;

    output.position = mul( float4( input.position, 1.0f ), input.world );
    output.position = mul( output.position, view );
    output.position = mul( output.position, proj );

    output.normal   = normalize( mul( input.normal, (float3x3)input.world ) );
    output.color    = input.color;

    return output;
}

```

The final output of the cube looks like this:

Any suggestions? Thank you!

# Answer
> 3 votes
DXGI\_FORMAT\_R32G32B32\_FLOAT is not 16 bytes, that's the first problem after a quick look. Either declare it 12 in your layout or specify D3D11\_APPEND\_ALIGNED\_ELEMENT instead. Or Make it DXGI\_FORMAT\_R32G32B32A32\_FLOAT instead depending on your matrix.

---
Tags: c++, shaders, directx11, transformation, instancing
---


# Question
Title: How can I store point voxel terrain in octrees
I am writing a voxel engine in LWJGL3 - binding for OpenGL 4 for JVM. Recently I implemented an octree storage of cubic voxels. In my implementation each leaf node of an octree has one voxel, voxels can't overlap each over. But now I changed my mind and my goal is to create a dynamic point voxel engine. How can I store point voxels in an octree ? My reference is EverQuest Next Landmark.

# Answer
> 1 votes
What you would do is have a limited depth for your octree and allow multiple voxels per leaf. I used a depth of around 6-8 for spatial partitioning for collision detection but for voxels you'll probably need more; it's up to you. You'll also need a limit to stored voxels before splitting, say 10 for the sake of example. As your populate your octree when you hit 10 voxels in a leaf you'll split it and move the voxels into their new leaves. Once a leaf is at your maximum depth you should no longer split it and just let your voxels fill the leaves.

---
Tags: voxels, octree, storage
---


title: Collision with player following mouse

text:
# Question
Title: Collision with player following mouse
I'm making a RPG with libGDX. I've loaded a TiledMap and now I'm implementing the player movement. The view is top-down.

In my game I want two ways of input: one is using the ARROW keys to move the player. This implementation works pretty well, including collisions. The second one is a movement based in the mouse. When I click, then the player starts to follow the mouse pointer

```
 private void autoMove(float speed)
{
    //Start or stop moving
    if (Gdx.input.justTouched())
    {
        autoMoving = !autoMoving;
    }

    //Start follow the mouse
    if (autoMoving)
    {
        //Get direction
        Vector3 point = this.getStage().getViewport().getCamera().unproject(new Vector3(Gdx.input.getX(),Gdx.input.getY(),0));
        dir = new Vector2(point.x - pos.x, point.y- pos.y);

        //Normalize
        dir.nor();

        //Set correct animation
        if (Math.abs(dir.x) <= 0.5)
        {
            if (dir.y >= 0)
            {
                lookingDirection = UP;
            }
            else
            {
                lookingDirection = DOWN;
            }

        }
        else
        {
            if (dir.x >= 0)
            {
                lookingDirection = RIGHT;
            }
            else
            {
                lookingDirection = LEFT;
            }
        }

        //Scale to speed and move
        dir.scl(speed);
        pos.add(dir);
    }

```

As you can see, I use global variable `dir`to store the direction of the player. Now I want to handle the collisions with this input. However, I'm not able to do this. I've tried, for example, using `pos.add(dir.scl(-1.0f))` but doing this the player gets blocked in every direction. After that, I tried to make the same but blocking only x or y movement based on the `lookingDirecion` variable. However, player can be looking at right and move a bit upwards, to it's possible to "hack" the system and introduce the player inside the block. I tried with more complex if structures but they didn't worked at all.

The collision code looks like this, if it's useful.

```
public void checkBounds(float speed)
{
    for (int i=0; i < map.getWidthInTiles(); i++)
    {
        for (int j=0; j < map.getHeightInTiles(); j++)
        {
            //bound is player's rectangle. colBounds are map's impenetrable objects.
            if (bound.overlaps(map.colBounds[i][j]))
            {
                if (!autoMoving) //Control with ARROW keys
                {
                    if (lookingDirection == UP)
                    {
                        pos.y -= speed;
                    }
                    else if (lookingDirection == DOWN)
                    {
                        pos.y += speed;
                    }
                    else if (lookingDirection == RIGHT)
                    {
                        pos.x -= speed;
                    }
                    else if (lookingDirection == LEFT)
                    {
                        pos.x += speed;
                    }
                }
                else
                {
                    //MOUSE COLLISION DETECTION
                }
            }
        }
    }

```

**The question is: how can I implement the collision detection for this kind of movement?**

Thank you!

# Answer
Collision detection shouldn't depend on input. You should aim to make your movement and collision systems as generic as possible.

Not only that but I'm seeing an issue with the logic that happens during your frame. You seem to be doing something along the lines of:

```
//Detect input

//Detect collision

//Move according to facing direction

//Draw

```

Correct me if I've made a mistake with that.

Usually the order of operations for a frame involving collision detection is:

```
//Detect input

//Move player (usually adding velocity to position)

//Detect collisions and return overlap between player and wall

//Move player back so it's no longer colliding

//Draw

```

Of course this isn't even as generic as it can get but it's relative to your problem.

During the `DetectInput` stage you should determine your velocity. If the player has clicked why not set a velocity that doesn't change unless the player clicks again or right clicks to stop. Otherwise just move the player if a key or keys are down in a certain direction. Then you can apply that velocity to position, detect collision and react.

If this is more involved than you want it to be I'd suggest using something like Box2D to handle the collision logic for you so you can just worry about getting your player walking around the way you want.
> 1 votes

---
Tags: collision-detection, libgdx, rpg
---


# Question
Title: Porting SDL OpenGL Game to Android and IOS
I am currently learning OpenGL (3.0+) with C++. I am using SDL for input handling, window creation, etc., GLEW to use OpenGL and call OpenGL Functions, and GLM for OpenGL Math stuff.

If I fully finish a Windows game, how can I port my game with the setup above to Android, IOS, and maybe even other platforms (but my main focus is Android and IOS). I do not want to use any Game Engines.

What I am looking for is a program that could just make my game run on android and IOS. If there is a way to optimize my game using the tools listed above a little bit and change some code to make my game run on android and IOS, I am okay with that (if that is the case, please provide resources).

I have heard of OpenGL Es, not quite sure what that is, but I do not want to use it if it is a completely different library and if I have to rewrite the entirety of my game rendering engine. I also want my app to run without the user having to download any libraries such as SDL, so please make sure that my app can just run as an .apk file or whatever format that I can just tap on and it will open.

I also want my app to run on most smartphones (Android and IOS), so please be sure that what you are suggesting is not only available to a limited amount of smartphones. Another thing that I want is optimal performance. No emulators or simulators from .exe to .apk that run very slowly. It should run as fast as other apps and run at probably the same speed as my windows version. Also point out any mistakes that I may have made (for example, maybe I am just crazy thinking that smartphones use OpenGL).

# Answer
> 5 votes
If you're using SDL 2 you should just be able to port to mobile quite easily. SDL 2 has support out of the box for mobile. It won't be a 2-click port but it will be very possible to do.

Check out the download page: http://www.libsdl.org/download-2.0.php#source

There are versions of SDL 2 for iOS and Android that you can build from source. SDL is very well supported so it should require minimal effort. You'll probably need an actual Mac to do anything for iOS.

OpenGL and OpenGL ES are very similar. OpenGL ES is really just OpenGL for Embedded Systems (hence the ES). You will not have to rewrite everything from scratch. Your shaders may need some optimizations or tweaks to work perfectly on mobile however. The exact tweaks that you will need to make will depend on your application, your shaders and your target platforms.

Here are some READMEs that you should read:

https://hg.libsdl.org/SDL/file/d6a8fa507a45/README-android.txt

https://hg.libsdl.org/SDL/file/d6a8fa507a45/README-ios.txt

Don't be afraid to search around on your own. SDL is very widely documented and discussed.

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


title: 2D Lock x Axis on character

text:
# Question
Title: 2D Lock x Axis on character
I am creating an endless runner with a flying character.

I want to lock any movement in the x axis so that the character object can only move up and down but still move forward through the scene. I have looked into freezing axes and joints, but this stops the forward movement.

Is it possible to edit the below to lock the x axis for character movement only, or is there a setting where i can apply this?

```
using UnityEngine;
using System.Collections;

public class moveupdown : MonoBehaviour {
    public Vector2 velocity;
    public float uservelocity;
    public Rigidbody2D rb2D;

    void Start() {
        rb2D = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate() {

        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {
            Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;

            rb2D.MovePosition (rb2D.position + touchDeltaPosition * Time.fixedDeltaTime / uservelocity);

        }
    }
}

```

# Answer
> 1 votes
Don't take deltaPosition.x value:

```
Vector2 touchDeltaPosition = new Vector2(0, Input.GetTouch(0).deltaPosition.y);

```

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


# Question
Title: Unity3D Get object size in order to be used in Vector3 coordinates
I have a `plane` in Unity in 3D project, and I want to get its boundaries so I can use them in random function for getting `Vector3` coordinates. Currently I am trying like this

GameObject ground;

```
void Start () {
        ground = GameObject.Find("Ground");
        moveAreaX = ground.GetComponent<Renderer>().bounds.size.x;
        moveAreaZ = ground.GetComponent<Renderer>().bounds.size.z;
        Debug.Log ("X Area: " + moveAreaX + ", Z Area: " + moveAreaZ);
        GetRandomTargetCoords();
    }

void GetRandomTargetCoords() {
        targetCoordsX = Random.Range(0f, moveAreaX);
        targetCoordsZ = Random.Range(0f, moveAreaZ);
        targetCoords = new Vector3(targetCoordsX, 1.1f, targetCoordsZ);

    }

```

And in the console I am getting this:

```
X Area: 108.5801, Z Area: 108.5801

```

The problem is the units provided by this `bounds.size` are not equal to the game object's Transform position's units, and so the game object gets out of the Plane's boundaries.

How can I make it have the same units for measurements?

# Answer
If i understand correctly, you want to put a random target on the plane. However, your plane bounds.size are the "sides" of the plane, and do not start at the center. What you want to do is something like this:

```
float scale = 0.1f;
float moveAreaX = gameObject.GetComponent<Renderer>().bounds.size.x / 2;
float moveAreaZ = gameObject.GetComponent<Renderer>().bounds.size.z / 2;
Vector3 center = gameObject.GetComponent<Renderer>().bounds.center;
targetCoordsX = center.x + Random.Range(-moveAreaX*scale, moveAreaX*scale);
targetCoordsZ = center.z + Random.Range(-moveAreaZ*scale, moveAreaZ*scale);

```

You take the center of the plane, and add it the size of the corresponding side divided by 2 since you start at the center. That way you randomize positive and negative "half side". The scale is because the scale of the game is not the same for transform.scale and bounds (but i think that actually depends on your game).
> 3 votes

---
Tags: unity, 3d, vector, coordinates, planet
---


# Question
Title: How do I duplicate the functionality of ugui's onClick (button component) in inspector (Unity)?
I'm trying to create the same functionality that occurs when you are working with a button in uGui in Unity. I know that I have to create a custom inspector, but i'm not sure where to go from there.

Essentially the functionality allows you to drag and drop a script to it's on click portion in the inspector, and then it gives you a list of functions for that script to select. This may sound a little confusing, so here are a few pictures demonstrating the functionality i'm trying to replicate.

As you can see above the functionality allows you to drag in a script, select a function to link, and do this for as many or as little scripts as you want by pressing the + or - buttons on the bottom right.

Thanks for any help in advance!

# Answer
You need to use UnityEvents to make use of such functionality. Derive a class from UnityEvent and then then declare a public member:

```
[System.Serializable]
public class MyEvent : UnityEvent<int> {}

public MyEvent onClick;

```

This will show up as the custom inspector widget you want. To send the event you do something like this:

```
onClick.Invoke(1);

```

Take look at this tutorial I made on a Rating Bar widget that uses Unity Events
> 2 votes

---
Tags: unity, gui
---


# Question
Title: Making a master server in Photon Unity Network?
I am trying to make a game that requires a dedicated server running 24/7 and I would like to use Photon Networking but can Photon Network handle/do a dedicated server setup?

The reason I ask is because every tutorial I watch/read is talking about client hosting and not server to client.

Another question I have is that if PUN can handle dedicated servers will I have to make separate applications, one for the server and one for the client? To me that seems to make the most sense.

The third question is that if I do have to make a server and client application how do I connect to my server application with my client application?

Does PUN provide a URL which I can connect to or is there something else that I have to do?

If you guys have any tutorials you could point me to working with PUN and dedicated servers that would be awesome and if you guys have any information you are willing to bestow upon me that would be greatly appreciated!

# Answer
> 1 votes
Yes photon can handle it. Btw a master server(what you meant with running photon in a dedicaded server) is whole differen thing. Master Server is a dedicated server which you run on your own machine and you are all able to edit the photon way you want.

From what i understand you are trying to make a server(actually a photon room) which stays 24/7 online, no need for editing the photon itself. You can do it by disabling players to create a server and just make them join to your rooms. Create another application which you can create a server, it will be your masterclient. What you created isnt a server actually, its just a masterclient of a room. Buy a server to run your masterclient to make it run 24/7.

You can check out official photon docs to find out how to create a room and how to make players join it.

PS: All the rooms and lobbies are still running at Photon Cloud with this way.

---
Tags: unity, networking, unity-networking, photon
---


title: XNA Texture mapping on model

text:
# Question
Title: XNA Texture mapping on model
I have a cube as my model and want to map a texture on every side of the cube. I have been searching for a while and most answers suggest using 3D max or using VertexPositionTextures.

I am not allowed to use any moddeling program, I have to use XNA, so that is not an option. For VertexPositionTextures you have to provide a Vector3 and a vector2 containing the position and the some area of your texture. But then, why would I use a model if I provide the position myself? Do I get this wrong maybe?

I tried to add the texture to my effect with `effect.texure = ...` but I can't specify what to map. It just puts the texture on my model.

So how can I map a texture to my model and specify what and where to map?

# Answer
So you're not using a modelling program- thus you'll have to provide the cube/texture information yourself from code.

Let's start out simple with one textured triangle. VertexPositionTextures contains Vertex (location of points in space) and texture (where does that point match to a point on an image). Keep in mind that the location for the texture is on a scale of 0 (top,left) to 1 (bottom,right): Thus for one triangle:

```
  1
 / \
0---2

Vertices[0].Position = new Vector3(-5, 0, 0);
Vertices[1].Position = new Vector3(0, 10, 0);
Vertices[2].Position = new Vector3(5, 0, 0);

Vertices[0].TextureCoordinate = new Vector2(0, 1);
Vertices[1].TextureCoordinate = new Vector2(0.5f, 0);
Vertices[2].TextureCoordinate = new Vector2(1, 1);

```

This holds the information of the location of the points in space, and the location of the texture. The point (2) is located at 0,10,0 in 3D space, and the location of the the point on the texture is like this halfway along the X axis (x=0.5) and top of y-axis (y=0):

```
+--2--+
|     |
|     |
+-----+

```

For a 3D cube you basically you have a list of Vector3 points for each corner. To create your cube you'll need to create 12 triangles like that (3 points per triangle, 2 triangles per side, 6 sides for a cube) = VertexPositionTexture\[36\], and map each corner to the corners of your texture.

Another approach is to use indexed vertices; this means you need to define 8 VertextPositionTextures only for each 3D coordinate, and have a separate array int\[36\] to hold the triangle information. This makes it easier to work with, but in your case may be a headache to get the texture coordinates right; as each point would also share the texture position. For more insight in that method read this: http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series1/Indices.php

Sidenote: you *can* load models in XNA so I'm not sure how to interpret "I have to use XNA, so that is not an option"
> 3 votes

---
Tags: xna, textures, uv-mapping
---


title: libgdx Vector.cpy question

text:
# Question
Title: libgdx Vector.cpy question
Why do people use this:

```
public void set(Vector2 v) {
    this.vector2 = v.cpy();
}

```

insted of just using:

```
public void set(Vector2 v) {
    this.vector2 = v;
}

```

What I don't know that I should know?

# Answer
> 3 votes
If you would follow the second strategy, changes made to the Vector that got passed as parameter "v" will also be made to "vector2", since they are the same object.

You should have a look at this question: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

In Java every object is an reference, so you need to copy, for example your Vector2 Object, if you don't want to introduce crazy ass bugs.

A better alternative is to just set x and y to the x and y values of the vector you want to copy from.

---
Tags: java, libgdx, vector
---


# Question
Title: Best collision algorithm for Axis Aligned Bouding Boxes
I have a number of quads (suppose like 20-40) and i want to quickly check the collisions between any of them. I would like to know if there's a quick algorithm to do that 60 times per second without performance decrease

# Answer
> 3 votes
You may want to consider looking to spacial partitioning, such as a Quadtree.

In a nutshell, you would be dividing your world into sub-sections, and only check collisions between objects that are inside of the same sub-sections, greatly improving the complexity.

# Answer
> 0 votes
In the worst case (for 40 AABBs) you'll need to do 780 tests. There's not going to be any problems with a simple 4 comparison test:

```
a_min.x <= b_max.x
b_min.x <= a_max.x
a_min.y <= b_max.y
b_min.y <= a_max.y

```

If all of these are true, you have an intersection.

At this point partition structures (like AABB trees) are not necessary at all. You might only want to start thinking about them when test count goes over 10 000, which is when you need to test about \>140 AABBs.

Best to avoid using the broadphase for as long as you can because it will introduce a lot of complexity and hard choices and measurements. Not one of them is going to give a good speed improvement without serious workload and staying within special constraints with your AABBs.

# Answer
> 0 votes
A nice but lesser well known algorithm for this situation is called dimensional reduction.

If you keep your list of rectangles sorted on one axis (say, x axis by sorting on the minimum x value of the rectangles), then collision detection just becomes a 1 dimensional overlap test on the y axis, for whatever overlaps there were on the x axis.

Works better when most objects are stationary, but the same is true of all spatial subdivision algorithms (;

---
Tags: collision-detection, algorithm, performance, aabb
---


# Question
Title: How to make a horizontal scrolling menu in Unity 3d 4.5
I want to make a horizontal scrolling menu that will hold the levels of a game but I have a little idea about how to make it so it would be very great if anyone help me with it.

# Answer
Just use NGUI. It's the best for UI before 4.6 (I havn't tried 4.6 UI yet so, I cannot tell which one is better). If you have some budget, I recommend buy NGUI 3.7.x version. It's a lot lot more convenient than 2.7 version and less buggy. If you do not have a budget, you can use 2.7 version. After that, use Scroll View in NGUI to build the scrolling menu. More info on this youtube link.
> 0 votes

# Answer
Well if you are new to Unity and know a bit now about the usual functions it shouldn't be difficult for you.

You could simply make a bunch of UI buttons, that each one of them will have the sprite as a picture of the level you want to load. Only one will be inside the canvas, while the others can be fully out of it, or barely showing up. On a left/right button press, you could translate all the buttons right/left suiting your needs.

You know you should just start working on it instead of thinking about it.
> 0 votes

# Answer
I used this tutorial to create an GUI with a scrollable panel (vertical in my case but is trivial to change alignment).
Using unity 4.6 start using canvas, add panel and play with its components. Everything is well explained in the tutorial.
> -1 votes

---
Tags: unity, gui, ui-design, menu
---


# Question
Title: How do I seperate my game and game engine into seprate projects?
I am trying to separate my game from the game engine, both written in Java. Currently, they are in two separate packages, but I would like to separate them into different projects.

A main method in "Project B" starts a game loop in "Project A". This loop needs to call back to methods in "Project B". What is the best method to achieve this, without "Project A" being aware of the specific implementation of "Project B"?

---

"Project A" (Engine - Library):

```
public class Engine {

    public static void start() {
        init();
        // Call Game.getInstance().init() from Project B.

        while (true) {
            input();
            // Call Game.getInstance().input() from Project B.

            update();
            // Call Game.getInstance().update() from Project B.

            render();
            // Call Game.getInstance().render() from Project B.
        }

        cleanUp();
    }

}

```

"Project B" (Game - Executable)

```
public class Main {

    public static void main(String[] args) {
        Engine.start();
    }

}

public class Game {

    private static Game instance = new Game();

    private Game() {}

    public static Game getInstance()
        return instance;

    public void init()
        // Do Stuff

    public void input()
        // Do Stuff

    public void update()
        // Do Stuff

    public void render()
        // Do Stuff

}

```

# Answer
> 2 votes
You can write your engine in super classes. Have a game, an entity, etc.

Then to make a new game, extend the game class which has your game loop. To add an entity, extend the entity class.

So the game class would have a generic game loop. Your game would extend that game class and override the parts you need. The game class can be coded to handle the entity class. So you extend the entity class and add them to your extended game class

# Answer
> 1 votes
One way to do this is by having the game be a dll and the engine being the executable.

There are side benefits to this as well. If your main menu / matchmaker etc screens are in the engine and only actual game sessions use the game dll, you end up completely tearing down the resources used by the game between matches.

This can help with memory fragmentation and can also solve the class of bugs where state isn't properly reset between matches. These bugs can be pretty nasty and hard to track down.

---
Tags: java, architecture
---


# Question
Title: Design pattern for animation sequence in LibGDX
What design pattern to use for sequence of animation that involve different actor in libGDX. For example I am making a game to choose a wolf from a group of sheeps. The first animation played when the game begin is the wolf enter the field that is filled with two sheeps.Then the wolf disguise as a sheep and goes to the center of the screen. Then the game will shuffle the sheeps. After it finished it will ask the player where is the wolf. The game wait for player input. After that the game will show animation to show the player whether their answer is right or wrong.

I am currently using State design pattern. There are four states wolfEnterState,DisguiseState,ShuffleState,UserInputState, and answerAnimationState. I feel that my code is messy. I use addAction with action sequence and action completion(new Runnable()) a lot. I feel that the action sequence is getting long. Is there a better solution for this kind of problem

# Answer
> 1 votes
One option is to give the Wolf class a disguise function. This could look something like this.

```
class Wolf {
    void disguise(Animation p_target) {
        this.animation = p_target;
    }

    void animate() {
        play(this.animation);
    }

    void reveal() {
        play(this.animation.reveal);
    }
}

```

Another option is to create a child DisguisedWolf class.

```
class Wolf {
    void animate() {
        play(this.wolf_animation);
    }

    void reveal() {
        play(this.wolf_reveal);
    }
}

class DisguisedWolf extends Wolf {
    void animate() {
        play(this.sheep_animation);
    }
}

```

I believe it would be beneficial to present the same interface no matter what the state is. This makes it easier to iterate over a collection and call the animate function.

```
sheep.move(center);
sheep.shuffle();

wolves.move(center);
wolves.disguise(as_sheep);
wolves.shuffled();

creatures.shuffle();

promptPlayer();
// Now you can blindly call reveal
creatures[player.clicked_creature].reveal();

```

Or try this..

```
creatures = wolves + sheep;
creatures.move(center);
creatures.disguise();
creatures.shuffle();
promptPlayer();
// Now you can blindly call reveal
creatures[player.clicked_creature].reveal();

```

# Answer
> 0 votes
I think of having one class for wolves and sheep that has a `boolean isWolf;` and when it is clicked it calls `animate()` that is something like this:

```
public void animate(){
    if (isWolf) {
        //play wolf animation
    } else{
        //play sheep animation
    }
}

```

---
Tags: java, libgdx
---


# Question
Title: Unity: Slow deployment to Android devices?
From the time I hit "Build & Run", I wait 2 minutes (each) for Unity 5 to push to two different 'Droids. Fresh project, one script to generate a simple mesh, and no other assets. I am deploying via a USB 2.0 port.

IIRC from using Unity 4 in 2012, the same was true then, including for iOS deployments.

Is this to be expected? My dev machine is an i7 with 16GB RAM and everything else is fast.

# Answer
It's common to need to wait a while when you want to actually test your game on the device, since it doesn't only include sending the data over USB cable. They probably count the time it takes to instal the game in the "pushing" process.
That's why you can use the Editor and Unity Remote (it's on the play store) for instant testing.

Btw an empty Unity game also has a considerable size. If you're concerned about the time it takes for Unity to send the game to the device you should build the game and move it to the phone by yourself to compare the time.
> 1 votes

---
Tags: unity, android, deployment
---


title: Displaying Images Correctly

text:
# Question
Title: Displaying Images Correctly
So, I've been working on several smaller game project in past few months, and I've got the hang of game dev in java. Now I'm trying to optimize game performance. Is it ok to simply use `g.drawImage();`to display sprites and other images?

Note that I'm trying not to use any external libraries.

# Answer
Yes, it's perfectly acceptable to use g.drawImage(); to render your bitmaps.

Most of the optimization you'll be doing is cutting down on the number of times you call that method, rather than using some other method entirely. For example, you might only clear the parts of the background that have changed ("dirty rectangles") and draw the changed parts over top of it, or you might construct your scene by rendering tiles/layers to a secondary bitmap/buffer and then just draw that bitmap to the screen rather than reconstruct the scene. (FWIW, when I worked on professional projects for pre-smartphone era devices a lot of these didn't work so good so it was pointless to get fancy).
> 0 votes

---
Tags: java
---


title: DX11 Mixing 2D and 3D

text:
# Question
Title: DX11 Mixing 2D and 3D
So I am somewhat new to working with DirectX rendering, and I have done some 2d and 3d work. I am planning on working on a new application where I will be rendering a bunch of 3d scenery, and then overlaying some 2d 'sprites'

My plan is to draw the 3d stuff, then change to an orthographic projection for the 2d stuff and so on. I was wondering if this was a normal thing to do, or if I am somehow going to be shooting myself in the foot later because of performance problems, etc.

Sorry if the question is vague, I don't quite know enough to be more technical / elaborate.

# Answer
Totally normal thing to do.

You can also render your 3D to one render target and your 2D to a different render target and then draw those over each other in a later pass. That lets you do all sorts of fun tricks, like rendering the 3D in a lower and faster resolution while keeping your 2D in a higher and crisper resolution. This sort of thing is also important to parallelizing your rendering pipeline (more important with D3D12/Vulkan).

There *can* be performance problems with rendering as you suggest, but that's all rather dependent on a bunch of implementation details.
> 5 votes

---
Tags: 2d, 3d, directx, directx11
---


# Question
Title: Path finding in 2D grid for objects that can rotate and bigger than one tile (Tetris)
I'm trying to check if there is a path between two locations in a Tetris board. On this question it tells how to account for different shapes: Path finding in grid for objects that occupy more than one tile

But having a shape that can rotate needs a different technique. How should I approach this?

# Answer
Use a standard A-star algorithm, modified to *consider* all possible orientations as you remove each node from the *Openset*. There are two possible implementation choices here:

1. Test for suitability of each \<neighbour,orientation\> tuple **before** pushing it to the priority queue; or
2. Test for suitability of each \<neighbour,orientation\> tuple **after** popping it from the priority queue.

You would need to test both to see if one gives significantly better performance than the other for your particular circumstances.

If there is a cost to rotating remember to account for this as you queue \<neighbour,orientation\> tuples. As this merely increases the cost of entering a state, your heuristic function does not need to account for it - any existing heuristic will retain its admissibility and consistency under this transformation of the algorithm.

In order to only rotate objects when necessary you may wish to consider a *tie-breaker* to your cost function - essentially a small cost to rotating even when there is none in reality. One way to do this is to multiply (or bit-shift) your costs by a small integer, then add one for each rotation step in any direction. I have used this in my Hexgrid path-finding implementations to select between equal cost paths to obtain the one that is most **visually appealing**.
> 3 votes

# Answer
I'm curious to hear if there's a more elegant solution, but I feel like brute force may be the best.

Basically try to go down all the paths recursively, under each possible rotation orientation - assuming you only have a few rotation angles.

Something like, if you reach a spot you can't continue to path through, but there is a gap, try rotating to fit through. If you can't and the stack unwinds so to speak, unwind until you are at a place where the piece can be rotated. Rotate the piece and continue to recurse out.

Continue until you get to the destination or until you've tried all available paths at all rotation angles.

If your map is static (doesn't move, or doesn't move often), you could probably do some of this brute force as a preprocessing step so that you'd already have knowledge of how a piece had to be rotated to go down a specific path (or which rotations are valid maybe as a bit mask). That would make it more efficient at runtime.
> 0 votes

---
Tags: path-finding, grid
---


# Question
Title: How do I separate physics from framerate?
Skyrim (Creation Engine / Gamebryo) is a prime example of a game that has its physics tied to the framerate for which it has been heavily criticized, because if you disable vsync / have a \> 60 HZ monitor the physics will glitch, characters will fly into the air, and the screen will flicker while you are put into a swimming position. This problem can be solved by using a framerate limiting mod. But I want my game to run at any framerate, any refresh rate, just fine. How can I do that? Sorry if this isn't a game development question necessarily, it's more of a game engine question.

I looked and saw similar questions asked but they were very old and new tech / new programming techniques might have allowed better ways to do it since 2008.

# Answer
To do this, firstly you need to define a physics update time period (say, evry 16ms) and then you need to handle the case of when your game runs too fast, and when it runs too slow.

When the game runs too quickly (faster than your physics update period) you need to interpolate between the last physics frame data and the next physics frame data based on what percentage of time you are at between physics updates.

When the game runs too slowly, a common solution is to run it multiple times if needed, and if the game starts to fall too far behind, you can drop update calls.

The other important things here are that you always call your physics update code with a specific time step (again, like 16ms) and that you keep a variable that accumulates how much time has passed in the game, using that as a measurement to know how many physics simulations you need to do that frame (game loop) to catch up to real time.

Passing the constant frame update time to your physics system is what makes it not depend on actual frame time (fps)
> 5 votes

# Answer
For a really good and in-depth article on this subject, just read Fix Your Timestep. There's also a ton of existing questions about this subject, although addressing different angles.

But in really simple terms, this is how you get a fixed physics (or anything, really) frame rate despite the rendering frame rate being unpredictable:

```
loop
    check how long it's been since the last frame
    while we are overdue for a physics frame
        do one frame of physics
    render

```

Or diagrammatically:

```
ideal physics frames:     p1      p2      p3      p4

render (actual) frames: r1   r2            r3 r4 r5

what's actually run:    r1   p1            p2 r4 r5
                             r2            p3
                                           r3

```

At r2, we run physics for one frame (p1), at r3 we run two (p2, p3), at r4 and r5 we don't run any physics.

One key insight is that *we don't have to run physics at an exact point in time*. We just need to make sure the physics is up to date before we render everything. Some people get trapped into thinking they'll need some super-complex time-synchronised multi-threaded monstrosity to handle this, because of this misconception.

Usually this is implemented by taking the difference between the actual time and the expected time for the next physics update, accumulating that difference, and running physics frames as long as that difference is larger than the ideal physics frame time. So for example if ideally physics runs every 50ms, and it's been 120ms since the last frame, you run 2 physics frames (50 goes into 120 twice), and keep around the remainder 20ms. I think it's clearer if I just reproduce the code sample from the linked article:

```
double t = 0.0;
const double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

while (!quit)
{
    double newTime = hires_time_in_seconds();
    double frameTime = newTime - currentTime;
    currentTime = newTime;

    accumulator += frameTime;

    while (accumulator >= dt)
    {
        integrate(state, t, dt);
        accumulator -= dt;
        t += dt;
    }

    render(state);
}

```
> 5 votes

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


# Question
Title: Math behind XNA's spriteBatch.draw() color parameter?
I'm trying to make a shader that changes the color of a sprite the way the XNA spriteBatch.draw() color parameter changes color. I don't know exactly what it is called (the closest word I can think of is 'tinting' but that's not right I don't think) and it's kind of hard to explain the way it looks.

Say you set the parameter to 'Red' -- white pixels in the original texture would become completely red, while black pixels would remain black. Grey pixels would look dark red, blue pixels might look purple, green pixels might look brownish.

If you set the parameter to 'Black' the texture would become completely black.

Does anyone know the math behind this, or what this technique is called? It's probably very simple and I'm just not seeing it.

Thanks!

# Answer
> 4 votes
It's probably multiplying the colours. That's pretty typical for a parameter like this.

Each colour channel is interpreted as a value from 0 to 1, then multiplied with the corresponding colour channel of the tint colour. So:

```
_______________ times red (1, 0, 0)  =
white (1, 1, 1)                      = red (1, 0, 0)
grey (0.5, 0.5, 0.5)                 = dark red (0.5, 0, 0)
black (0, 0, 0)                      = black (0, 0, 0)

```

Under this scheme, pure blue (0, 0, 1) tinted with pure red (1, 0, 0) will turn black. But if you use intermediate blue & red colours (ones with some non-zero values in the other two channels) you may get a dark purple.

Here's an example of using "multiply" blending to tint colours, via this tutorial

---
Tags: xna, shaders, color
---


# Question
Title: Checking actor type in projectile ProcessTouch
I'm trying to teleport a pawn when it's struck by a projectile (or damaged by any weapon in my game) .

Right now, I'm trying to just call `Pawn.SetLocation` in the projectile's ProcessTouch. That's a problem because `ProcessTouch` will hit any actor, not just a pawn. Additionally, any attempts to check the `ProcessTouch`'s "Actor Other" throw errors.

I've tried a bunch of solutions (including making an event `TakeDamage` in the `Pawn` controller class) but to no avail.

```
simulated function ProcessTouch(Actor Other, Vector HitLocation, Vector HitNormal)
{
    if (Other != Instigator)
    {
        //This is where the Other.TakeDamage goes if we are using a traditional gun.
        if (Other == Pawn);
        {
             Other.SetLocation(0,0,0);
        }
    }
    Destroy;
}

```

This code complains that `Pawn` is a bad expression. How else should I check actor type here?

# Answer
I think you miss to cast your pawn as :

```
if( myDesiredClass(Other) != none)

```

Check it and give me feedback if you face any new problem.
> 1 votes

# Answer
In my opinion you could either do it by checking the class

Other.class == class'Pawn'

or by casting and checking it whether it's None or not

Pawn(Other) != None
> 0 votes

---
Tags: udk
---


title: Unity 4.6.6 iOS Build Issue

text:
# Question
Title: Unity 4.6.6 iOS Build Issue
I am using unity 4.6.6 to create a Xcode build. When I create a build I am getting following error

Cannot initialize return object of type 'Singleton\_1\_t6738 \*' with an rvalue of type 'Singleton\_1\_t6737 \*'

# Answer
> -1 votes
https://msdn.microsoft.com/en-us/library/ff650316.aspx

http://www.dotnetperls.com/singleton

Hope these links help.

Have you consulted the Unity website?

---
Tags: unity, ios, xcode
---


# Question
Title: handle mousedrag() for two different game objects individually in 2D environment
I am developing a pong game for android mobiles having 2 slider and want to assign movement of individual slider corresponding to its current position

I tried some code for the movement of these sliders using OnMouseDrag();

```
void OnMouseDrag()
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector2(transform.position.x, mousePos.y);

    }

```

I got the movement for the sliders but problem is that, I can only slide one slider at a time But I need to move both the sliders at the same time using both hands because this game is getting developed for android mobiles environment.

please Help....

# Answer
> 1 votes
The best way to handle this, is to divide your screen in 2 and check to see if someone is holding down a finger in that area. An easy way to do this, is to add two large Box Colliders on each side of your game scene, which will serve as a hit detection for Touches.

Check if the Collider is pressed, and then simulate the corresponding paddle with that touch.

This is just some untested sample code you can play around with, can be greatly improved on:

```
public BoxCollider2D Paddle1Collider;
public BoxCollider2D Paddle2Collider;

void Update()
{

    foreach (Touch touch in Input.touches) {

        RaycastHit2D[] hits;
        Vector2 pos = Camera.main.ScreenToWorldPoint (touch.position);
        hits = Physics2D.RaycastAll (pos, new Vector2 (0, 0), 0.01f);

        for (int i = 0; i < hits.Length; i++) {
            if (hits [i].collider == Paddle1Collider) {
                Paddle1.Move(pos);
            }
            else if (hits [i].collider == Paddle2Collider) {
                Paddle2.Move(pos);
            }
        }

    }
}

```

---
Tags: unity, 2d, monodevelop
---


# Question
Title: How do I render a PNG image with OpenGL?
I have an image (100×200 px) painted with Paint.NET and saved as a `.png` with 32-bit color depth. How can I render it using OpenGL 1.1 (with the LWJGL binding) or higher inside the display?

I tried creating a `ByteBuffer`, then loading the pixel color values inside that buffer, but I'm missing the OpenGL settings that need to be enabled. Some help?

# Answer
> 1 votes
First, this question is about asking for a tutorial, and as far as i know googling "opengl tutorial" is enough to get you started. Second, i don't recommend you to use such an old version of opengl, even if you want to support an extremely large range of computers, the 'modern opengl' (a.k.a. Opengl 3.0+) is widely supperted as well. And imho learning opengl 1 is useless for any intermediate complexity project, because it lacks of many essential features (see framebuffer objects).

That said, if you give up with gl1, non power of two textures will be fully supperted on every machine.

Here I want to give you a fair starting point to solve your actual problem (this is not for lwjgl, though, and I assume gl3+ with shaders):

In opengl you don't render textures, you render geometry, so you have to draw a quad with the proportions of your textures. To do this, feed a buffer with the data of this specific geometry and draw it. Now it's time of shaders, you will need a vertex and a fragment shader, where you actually sample a texture object created before to output your quad filled with your texture.

Now, you are aware that with only what i wrote, you can't do anything, because all the details that you need to write a working program are missing, so http://bfy.tw/qKL

---
Tags: opengl, textures, lwjgl, png
---


# Question
Title: Google Play Game Services (Unity Plugin) Turn Based Multiplayer List of Open Matches
I took a closer look at Google Play games services Turn based multiplayer, and I cannot find out if I am somehow able to just get a list of all open matches, so that I can implement my own GUI. It seems really weird to me that they would not let you do such a simple task. Is this just a problem with the Unity implementation or is it a general problem? Using the Google UI would make a clunky feel which I would like to avoid.

# Answer
I finally found a solution.

First of all i added a issue in the github issue tracker. They told me they already had a issue like that. From that on i was able to find a solution for now (before they implement this stuff).

The fix i found there:

https://github.com/playgameservices/play-games-plugin-for-unity/issues/414

I will use the following code:

```
public void GetAllTBMatches(Action<TurnBasedMatch, TurnBasedMatch.MatchTurnStatus> callback)
{
    mTurnBasedManager.GetAllTurnbasedMatches(allMatches =>
                                             {

            foreach (var match in allMatches.MatchesMyTurn())
            {
                var converted = match.AsTurnBasedMatch(mNativeClient.GetUserId());
                callback(converted, TurnBasedMatch.MatchTurnStatus.MyTurn);
            }
            foreach (var match in allMatches.MatchesTheirTurn())
            {
                var converted = match.AsTurnBasedMatch(mNativeClient.GetUserId());
                callback(converted, TurnBasedMatch.MatchTurnStatus.TheirTurn);
            }
            foreach (var match in allMatches.MatchesCompleted())
            {
                var converted = match.AsTurnBasedMatch(mNativeClient.GetUserId());
                callback(converted, TurnBasedMatch.MatchTurnStatus.Complete);
            }

    });
}

public void GetAllTBInvitations(Action<Invitation> callback)
{
    mTurnBasedManager.GetAllTurnbasedMatches(allMatches =>
                                             {
        foreach (var invitation in allMatches.Invitations())
        {
            var converted = invitation.AsInvitation();
            callback(converted);
        }
    });
}

```

together with:

```
internal class TurnBasedMatchesResponse : BaseReferenceHolder {
internal TurnBasedMatchesResponse(IntPtr selfPointer) : base(selfPointer) {
}

protected override void CallDispose(HandleRef selfPointer) {
    C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_Dispose(SelfPtr());
}

internal CommonErrorStatus.MultiplayerStatus Status() {
    return C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetStatus(SelfPtr());
}

internal IEnumerable<MultiplayerInvitation> Invitations()
{
    return PInvokeUtilities.ToEnumerable(
        C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_Length(SelfPtr()),
        index => new MultiplayerInvitation(C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_GetElement(SelfPtr(), index)));
}

internal IEnumerable<NativeTurnBasedMatch> MatchesMyTurn()
{
    return PInvokeUtilities.ToEnumerable(
        C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_Length(SelfPtr()),
        index => new NativeTurnBasedMatch(C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_GetElement(SelfPtr(), index)));
}

internal IEnumerable<NativeTurnBasedMatch> MatchesTheirTurn()
{
    return PInvokeUtilities.ToEnumerable(
        C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_Length(SelfPtr()),
        index => new NativeTurnBasedMatch(C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_GetElement(SelfPtr(), index)));
}

internal IEnumerable<NativeTurnBasedMatch> MatchesCompleted()
{
    return PInvokeUtilities.ToEnumerable(
        C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_Length(SelfPtr()),
        index => new NativeTurnBasedMatch(C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_GetElement(SelfPtr(), index)));
}

internal static TurnBasedMatchesResponse FromPointer(IntPtr pointer)
{
    if (PInvokeUtilities.IsNull(pointer)) {
        return null;
    }

    return new TurnBasedMatchesResponse(pointer);
}

```

}

The answer is just copied from the link copied above, i still have to test this in the end product.

I hope this helps someone having the same problems.

Nikolas
> 0 votes

---
Tags: unity, google-play-services, plugin
---


title: A cube on rotating cylinder not moving

text:
# Question
Title: A cube on rotating cylinder not moving
i have an cylinder with self-rotating script,

```
using UnityEngine;
using System.Collections;

public class rotate : MonoBehaviour {

    // Update is called once per frame
    void Update () {
        transform.Rotate (new Vector3 (0, 0, 30) * (float)5);
    }
}

```

i placed a cube (not at center) with rigidbody on the cylinder, but it is not moving, anyone know how to make it moves according to the cylinder except using make parent?

# Answer
i assume you did these :

1) added rigidbody to both objects.

2) unchecked gravity for cylinder and freeze its vertical position(y is the default) and freeze rotation except vertical.

---

i would use a fixed joint or spring joint and connect both body together. just place the cube where you want it to be then add fixed joint.

spring joint makes it more dynamic for example if you want the cube to stay in a specific radius but moves with different speed .

---

can use "Break force" option to make joint to break after it reaches desired speed. also you can use "rigidbody.addtorque()" instead of transform rotate to let physics handle the rotation.
> 1 votes

# Answer
The best way would be to use `Rigidbody.addTorque()` if the rotation speed is too low (I think there was some "motor" join, but I'm not sure now). That way the physics engine will move the cube because of the velocity of the cylinder. (*Make sure that the cube and the cylinder have some friction (e.g. \>0.5), otherwise **nothing** will happen!*)

The problem with the joint method is that it doesn't allow for the cube to fall from above, or fall off (break speed might do it, but only to some extend).
> 0 votes

---
Tags: unity
---


# Question
Title: Wrapping things up in opengl based library
I am currently building a render library, based on opengl : problem is that I'm starting to get a lot of different ccomponents (Shaders, Materials, Textures, Meshes, ...), and I'm trying to wrap things up, without any success; I've had several ideas, like making a render class, or a scene class, but it did not turn out well...enter link description here. So I would ask you if any of you can suggest a way to wrap things up, if possible, still allowing the user to access Shaders, and low level rendering ! Here is the main code where I use all my objects :

Main.cpp :

```
/**
    PLEASE IGNORE : this is a test file for the alpha++ library !
*/

#define GLM_FORCE_RADIANS
#include <stdlib.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/string_cast.hpp>
#include "alpha/Shader.h"
#include "alpha/Window.h"
#include "alpha/Vertex.h"
#include "alpha/Mesh.h"
#include "alpha/Texture.h"
#include "alpha/Material.h"
#include "alpha/Transform.h"
#include "alpha/Camera.h"
#include "alpha/ModelLoader.h"
#include "alpha/InputHandler.h"
#include "alpha/wrapper/SDL_Handle.h"
//#include "alpha/LuaLoader.h" ///WARNING : INCLUDING LuaLoader SERIOUSLY increases compile time (~ 10 seconds)
#include "alpha/Util.h"
#include "alpha/FPSLook.h"
#include "alpha/Light.h"

static const unsigned WIDTH = 1000.0;
static const unsigned HEIGHT = 900.0;
static const unsigned FPS = 200;
static const float MOUSE_SENSITIVITY = 5.0;
static const glm::ivec2 MOUSE_TRAP(WIDTH / 2, HEIGHT / 2);
static const float CAMERA_MOVE_SPEED = 0.01;
static bool isRunning = false;

int main(int argc, char **args){
    Window window(300, 100, WIDTH, HEIGHT, "This is a test !", false, false);
    window.SetMouseVisible(false);

    //Material material;
    //material.AddTexture("grid_metal", new Texture("res/MercureRelief.png", GL_TEXTURE_2D, GL_LINEAR));

    Texture texture("res/MercureRelief.png", GL_TEXTURE_2D, GL_NEAREST);

    Mesh mesh("res/Test.obj");
    Mesh lightMesh("res/cube.obj");
    Shader shader;
    shader.loadFromFile(GL_VERTEX_SHADER, "res/basicShader.glslv");
    shader.loadFromFile(GL_FRAGMENT_SHADER, "res/phongShader.glslf");
    shader.CreateAndLink();
    Camera camera(glm::vec3(0, 0, 2.5), 70.0f, (float)window.GetWidth() / (float)window.GetHeight(), 0.01, 1000.0f);
    Transform transform;
    InputHandler input = InputHandler();
    glm::mat4 modelView = transform.GetModelView();
    glm::mat4 projectionView;
    glm::mat4 modelViewProjection;
    glm::mat3 normalMatrix;
    glm::vec3 cameraPosition;
    float time = .0f;
    float materialShininess = 100.0f;
    glm::vec3 materialSpecularColor = glm::vec3(2.0, 4.0, 6.0);
    PhongLight phongLight;
    phongLight.position = glm::vec3(5.0, 5.0, -5.0);
    phongLight.intensities = glm::vec3(2.0, 4.0, 5.0);
    phongLight.attenuation = 0.25f;
    phongLight.ambientCoeff = 0.0008f;

    isRunning = true;
    util::InMainLoop(3000, isRunning,
    [&](float delta){
        shader.Bind();

        static float timer = 0;
        timer += 0.0005;

        transform.GetScale() = glm::vec3(timer , timer , timer);
        transform.GetRot() += glm::vec3(timer / 20, timer / 20, timer / 20);

        normalMatrix = glm::inverseTranspose(glm::mat3(modelView));
        modelViewProjection =  camera.Combined() * transform.GetModelView();
        cameraPosition = -camera.GetPosition();

        glUniformMatrix4fv(shader.GetUniformLocation("MVP"), 1, GL_FALSE, glm::value_ptr(modelViewProjection));
        glUniformMatrix4fv(shader.GetUniformLocation("modelView"), 1, GL_FALSE, glm::value_ptr(modelView));
        glUniformMatrix3fv(shader.GetUniformLocation("normalMatrix"), 1, GL_FALSE, glm::value_ptr(normalMatrix));
        shader.UpdateUniform3fv("light.lightPosition", glm::value_ptr(phongLight.position));
        shader.UpdateUniform3fv("light.lightIntensities", glm::value_ptr(phongLight.intensities));
        shader.UpdateUniform3fv("cameraPosition", glm::value_ptr(cameraPosition));
        shader.UpdateUniform3fv("materialSpecularColor" ,glm::value_ptr(materialSpecularColor));
        shader.UpdateUniform1f("light.lightAttenuation", phongLight.attenuation);
        shader.UpdateUniform1f("light.lightAmbientCoeff", phongLight.ambientCoeff);
        shader.UpdateUniform1f("materialShininess", materialShininess);

        window.Update();
        input.Update();
        isRunning = !(input.CloseRequested() || input.KeyDown(SDL_SCANCODE_ESCAPE));
        util::ApplyFreeFPSLook(camera, input, window, delta, CAMERA_MOVE_SPEED, MOUSE_SENSITIVITY, MOUSE_TRAP);
     }
    ,
    [&](){
        window.Clear(.0f, .0f, .0f, .0f);
        texture.Bind();
        mesh.Draw();
        window.SwapBuffers();
    }
    );
    return EXIT_SUCCESS;// :) Nothing bad happened
}

```

# Answer
Looks not too bad to me. Only thoughts are to consolidate your camera to have a setMVPUniform(GLuint uloc, matrix model) or similar function. Likewise make similar classes for Lights, textures, VAOs, etc. Wrap anything you find yourself copypasting into a function.

As long as you keep your things public you'll still have low level access where needed.

Definitely make a renderer class for each group of objects which share the same program.

```
class Renderer{
    vector<object> objects;
    shader;

    void renderAll(camera cam){
        bindShaderLightsMaterials();
        for(objects){
            cam.setUniform( shader.uloc("cam"), object.trans );
            object.bindVAO();
            render();
        }
    };
}

```
> 0 votes

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


# Question
Title: How to move the generated polygon horizontally in openGL?
I am trying to develop a small ball game in OpenGL where rectangular bars of random height is generated and moved towards left and there is a ball which should be moved up and down(like jump action) whenever mouse left button is pressed. I am generating the polygon pattern but the problem is the movement

What is the best way to move the rectangles(of random height) horizontally? (or any generated pattern preferably polygon from right to left.)

I tried code below for movement of a single rectangle but i am getting a blank screen

```
void move_polygon()
 {
    int px,py;
    px=randr(50,100);
    py=randr(100,600);
    float r,g,b;
    r=(float)(rand()%10);
    g=(float)(rand()%10);
    b=(float)(rand()%10);
    float rf=r/10,gf=g/10,bf=b/10;
    glColor3f(rf,gf,bf);
    for(int pos=800;pos<=0;pos-=10)
    {
        Sleep(200);
        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_POLYGON);
        glVertex2f(pos,0);
        glVertex2f(pos,py);
        glVertex2f(px+pos,py);
        glVertex2f(px+pos,0);
        glEnd();
        glFlush();
        Sleep(100);
    }
}

```

# Answer
Lets say you have your rectangles at a certain coordinate to the right (x,y). Then, an easy way is that on each rendering call you reduce the x coordinate of the rectangles by some dx.

```
#define dx 0.1

render(){
    draw_rectangle(xrec, yrec, zrec);
    xrec -= dx;
}

```

If you have a logic loop separated from the rendering loop, then it is better to do the decrement in the logic loop.

EDIT: For the example you have added, it would be something like this

```
// global variable
int pos = somevalue;

// move function
void move_polygon(int pos){
    int px,py;
    px=randr(50,100);
    py=randr(100,600);
    float r,g,b;
    r=(float)(rand()%10);
    g=(float)(rand()%10);
    b=(float)(rand()%10);
    float rf=r/10,gf=g/10,bf=b/10;
    glColor3f(rf,gf,bf);
    Sleep(200);
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_POLYGON);
        glVertex2f(pos,0);
        glVertex2f(pos,py);
        glVertex2f(px+pos,py);
        glVertex2f(px+pos,0);
    glEnd();
    glFlush();
    Sleep(100);
}

// render function, decrement position here
void render_loop(){
    // ... other code
    move_polygons(pos--);
    // ... other code
}

```

The reason why you were getting a blank screen is because you are updating all the rectangle positions in one draw call, therefore the rectangle passes before you can even see it. You have to draw it once for each new position, try the code I showed you.
> 1 votes

---
Tags: opengl, movement
---


# Question
Title: Run one cycle of animation when button is pressed in libgdx
I am looking for a way to run my animation a complete cycle when a button is pressed. The animation runs as long as the button is pressed but the animation takes a second to play so it becomes too short. I would like to have it played through once, even if the button only was pressed very fast.

It's a character's slash with the knife and it needs to be one complete cycle, I just don't get how to do this.

Anyone has an idea on how I could do this in a better way?

The specific code is now inside render():

```
 if(Gdx.input.isKeyPressed(Input.Keys.SPACE)) {
        if(direction == HEADING.NORTH) {
            animation = knifeslashnorth;
        } else if (direction == HEADING.WEST) {
            animation = knifeslashwest;
        } else if(direction == HEADING.EAST) {
            animation = knifeslasheast;
        } else if(direction == HEADING.SOUTH) {
            animation = knifeslashsouth;
        }
    }

```

# Answer
I think it will work if you combine your input listener with:

```
animation.isAnimationFinished(stateTime);

```

While playing animation ignore attack input and let it just continue playing. When the animation finishes you can respond again and start a new animation by reseting the stateTime.

But I would also have in mind that the player can move meanwhile and there you have 2 options:

* Allow movement and cancel animation when direction changes.
* Also ignore directional changing input until animation finishes.

I hope it helps!
> 3 votes

---
Tags: libgdx, animation
---


# Question
Title: How to calculate if a point is contained in rectangular camera viewport with rotation?
I am working with my camera, and am trying to improve it so that I can calculate if a world point is on screen, taking rotation into account. Currently, my camera rectangle is calculated as so:

```
    public Rectangle Rectangle
    {
        get
        {
            int width = (int)((ViewportWidth / _zoom));
            int height = (int)((ViewportHeight / _zoom));
            return new Rectangle((int)(_pos.X - width / 2), (int)(_pos.Y - height / 2), width, height);
        }
    }

```

Then, to check if a point is on screen, I call one of the following functions:

```
    public bool IsOnScreen(Point location)
    {
        return this.Rectangle.Contains(location);
    }

    public bool IsOnScreen(Rectangle bounds)
    {
        return this.Rectangle.Intersects(bounds);
    }

```

However, none of these calculations take the rotation factor into account; only position and the zoom factor. I know that I can calculate the corners of the camera, in world space, using the following transformations:

```
var topLeftCorner      = Vector2.Transform(new Vector2(0, 0), Matrix.Invert(ViewMatrix));
var topRightCorner     = Vector2.Transform(new Vector2(ViewportWidth, 0), Matrix.Invert(ViewMatrix));
var bottomLeftCorner   = Vector2.Transform(new Vector2(0, ViewportHeight), Matrix.Invert(ViewMatrix));
var bottomRightCorner  = Vector2.Transform(new Vector2(ViewportWidth, ViewportHeight), Matrix.Invert(ViewMatrix));

```

However, the rectangle object that I am using is not able to take this into account, since it cannot store rotation. What is the calculation that I can use to check if a point is inside the virtual rectangle with these points, or if a rectangle intersects with the virtual rectangle?

Here's some graphics to better illustrate some of my code:

# Answer
Since you are working in 3d world space, why not use the `BoundingFrustum` class?

```
BoundingFrustum cameraBounds = new BoundingFrustum(view * projection);

if(cameraBounds.contains(location))
{
   // it is in view
}
else
{
  // not in view
}

```

edit. I assumed you are using XNA. If not, you can still reflect the XNA code to see how to make a Bounding frustum class and a .contains method.

The mechanics behind the BoundingFrustum class:

The ctor creates 6 planes in 3d space; one that is the left edge of all that the camera sees, one that is the right edge, top, bottom, near plane, far plane. It stores those planes for intersection tests just like you want. They can be reset anytime the view or projection changes. They automatically take into account the rotation of the camera. the .Contains method checks the test point (your location) against all 6 planes to decide if it is inside the camera's view or not. http://www.monogame.net/documentation/?page=T\_Microsoft\_Xna\_Framework\_BoundingFrustum

Here is a link to many forum questions about the BoundingFrustum found on the old XNA creators hub: http://xboxforums.create.msdn.com/search/SearchResults.aspx?q=BoundingFrustum
> 1 votes

---
Tags: mathematics, camera, rotation, matrix, vector
---


# Question
Title: How do i move a 2D object with angle and speed variables in unity?
I want to move an object with a certain angle and speed, is there a was to set this as an initial velocity so that it is still possible for the object to collide and bounce of other objects using its rigid body?

# Answer
Figured it out, here is the code that i made:

```
float angle, speed;
Vector2 newVelocity;

//use sin and cos to work out x and y speed
velocity.x = Mathf.Cos(angle) / speed;
velocity.y = Mathf.Sin(angle) / speed;

//apply the new velocity to the current object
this.GetComponent<Rigidbody2D>().velocity = newVelocity;

```
> 1 votes

---
Tags: unity, 2d, physics
---


# Question
Title: Why does flipping 1 texture region cause an identical texture region to also be flipped? (libGDX)
Sorry for the bad title. I didn't know how else to explain it.

The following is a portion of my code:

```
public class AssetLoader {

    public static TextureAtlas spriteSheet;

    public static TextureRegion hill, hillTop, hillBottom, rabbitJumped, background1, background2, water, spikes, playButtonDown, playButtonUp, dust;

    public static void load() {
        spriteSheet = new TextureAtlas(Gdx.files.internal("data/SpriteSheet.txt"));

        background1 = spriteSheet.findRegion("background");
        background2 = spriteSheet.findRegion("background");

        TextureRegion[] runFrames = {spriteSheet.findRegion("Frame01"), spriteSheet.findRegion("Frame02"), spriteSheet.findRegion("Frame03"),
                spriteSheet.findRegion("Frame04"), spriteSheet.findRegion("Frame05"), spriteSheet.findRegion("Frame06"),
                spriteSheet.findRegion("Frame07"), spriteSheet.findRegion("Frame08"), spriteSheet.findRegion("Frame09"),  };

        runningAnimation = new Animation(.03f, runFrames);
        runningAnimation.setPlayMode(Animation.PlayMode.LOOP);

        background2.flip(true, false);

    }
}

```

For some reason, the texture Region background1 is also flipped. Any help would be appreciated.

Some irrelevant code was ommitted.

# Answer
> 8 votes
`TextureAtlas#findRegion(String)` returns a region with a name that matches the name specified. It does not copy the region, therefore any changes you make to the region will be reflected in the TextureAtlas.

To overcome this issue, simply instantiate a new TextureRegion object and pass it the region found inside your TextureAtlas:

```
background1 = new TextureRegion(spriteSheet.findRegion("background"));
background2 = new TextureRegion(spriteSheet.findRegion("background"));

```

---
Tags: java, android, libgdx, textures, texture-atlas
---


# Question
Title: Manually creating cycles in planar, procedural trees?
I am creating a procedural map using delaunay triangulation and an MST. I'd like to have a bit more control over my final graph. Like when i was looking looking at the MST I wondered how I can connect specific points of the MST? The following image shows the MST in green and the points I want to connect in red.

I was thinking about traversing from a dead end and counting the steps. When it gets within a certain treshhold add a connection. But this might add a connection when there is still a room closer to it. So I have to check for that as well.

Same goes for entrance, exit and perhaps other important places on the graph. I want to end up with a random yet fun and playable dungeon. There must be proven concepts about controlling a graph for procedural dungeons and I would love to learn from it.

# Answer
> 4 votes
Given only the sparse information you've supplied, and assuming that when creating a red edge, you wish to avoid collisions against **both** other edges **and** rects (which I assume are rooms)...

What you are trying to avoid are *crossings*. What you want (red + green loops) are *cycles* in graph theory. Minimum Spanning Trees are tree-graphs - that means no cycles to start with. So MST should possibly not be your starting point(?). I assume that you generate the rects first, remove any overlaps, and then generate the MST from the remaining rects, in which I can see the reason why you have opted for this kind of graph, although it is by no means your only option to build a procedural map.

**Option 1**: Avoid MSTs. Consider ways of building a graph that can inherently contains cycles without the risk of generating crossings. How to do this runs the gamut from using the incredibly complex Boyer-Myrvold algorithm to pure trial and error approaches like you have already suggested.

If you insist on MSTs, and are using a grid (as it appears you are by the image background):

**Option 2**: Just walk the grid from one node to another, and check for obstacles along the way. You can even do this along multiple parallel lines to ensure you have sufficient space for passage. There is nothing wrong with this approach (for small/coarse grids), and it is trivial to implement.

**Option 3**: Check collisions geometrically, by doing line-vs.-line and line-vs.-rectangle tests. This avoids having to step too many times, as you would have to do using the above approach on a large/fine grid.

**Option 4**: Represent all connecting lines / passages as bounding rects. Now look at your bottom-most red line. Can you see how the the space it occupies *between* the two rects would actually fit into quite a small axis-aligned rect? Consider that if you can figure that rect out, and it does not occupy the same space as anything else, you can consider the passage to be valid. Of course this will not be as accurate as a direct walk, but it will probably be a lot cheaper. Not sure if this is of any use though.

**Note**: Trial and error processes are a fairly normal part of the process of procedurally generating paths. Don't be put off by it. The cost of backtracking is need not be prohibitive.

**Disclaimer:** There really is no canon when it comes to procedural approaches. You are operating in the realms of pure logic here. As such, there are as many ways to tackle one problem as you can imagine. So don't expect "proven concepts" or "established approaches". *DO* think and code creatively.

# Answer
> 2 votes
The simplest solution is to use the Relative Neighbourhood graph which provides a nice balance between the Delaunay Triangulation and MST.

---
Tags: tilemap, procedural-generation, data-structure, random
---


# Question
Title: How to implement Index Buffer Object (IBOs) with texture coordinates in OpenGL?
I was using **IBOs** to render meshes (for example a cube) from wave-front files (.obj), without texture coordinates or normals, in OpenGL.

Following this, I attempted to implemented texturing. The mesh was distorted because the indices are not referencing the correct vertices. There is a one-to-one relation between texture coordinates and vertices. Therefore, by implementing texture coordinates, extra vertices have been added to the vertex array/buffer (vertices with the same position but with different texture coordinates). Therefore, existing vertices have been offset and no longer correspond to the indices array/buffer.

Related rendering Code:

```
private int vbo;
private int ibo;
private int size;

public Mesh() {
    vbo = glGenBuffers();
    ibo = glGenBuffers();
    size = 0;
}

public void addVertices(Vertex[] vertices, int[] indices) {
    size = indices.length;

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, Util.createFlippedBuffer(vertices),
            GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
            Util.createFlippedBuffer(indices), GL_STATIC_DRAW);
}

public void draw() {
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0);
    glVertexAttribPointer(1, 2, GL_FLOAT, false, Vertex.SIZE * 4, 12);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 0);

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}

```

I had to switch to a vertex buffer object **(VBO) only** method of rendering to properly display the mesh with its texture. However, now will not gain any benefits of IBOs when render other, more complex meshes.

Related rendering Code:

```
private int vbo;
private int size;

public Mesh() {
    vbo = glGenBuffers();
    size = 0;
}

public void addVertices(Vertex[] vertices, int[] indices) {
    size = vertices.length;

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, Util.createFlippedBuffer(vertices),
            GL_STATIC_DRAW);
}

public void draw() {
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0);
    glVertexAttribPointer(1, 2, GL_FLOAT, false, Vertex.SIZE * 4, 12);

    glDrawArrays(GL_TRIANGLES, 0, size);

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}

```

Code for loading meshes from wave-front files:

```
ArrayList<Vertex> vertices = new ArrayList<Vertex>();
    ArrayList<Integer> indices = new ArrayList<Integer>();
    ArrayList<Integer> textureIndices = new ArrayList<Integer>();
    ArrayList<Vector2f> textureCoordinates = new ArrayList<Vector2f>();
    BufferedReader meshReader = null;

    try {
        meshReader = new BufferedReader(new FileReader("./res/models/"
                + fileName));

        String line;

        while ((line = meshReader.readLine()) != null) {
            String[] tokens = line.split(" ");
            tokens = Util.removeEmptyStrings(tokens);

            if (tokens.length == 0 || tokens[0].equals("#"))
                continue;
            else if (tokens[0].equals("v"))
                vertices.add(new Vertex(new Vector3f(Float
                        .valueOf(tokens[1]), Float.valueOf(tokens[2]),
                        Float.valueOf(tokens[3]))));
            else if (tokens[0].equals("vt"))
                textureCoordinates.add(new Vector2f(Float
                        .valueOf(tokens[1]), Float.valueOf(tokens[2])));
            else if (tokens[0].equals("f")) {
                for (int t = 1; t < 4; t++) {
                    String[] splitToken = tokens[t].split("/");

                    indices.add(Integer.parseInt(splitToken[0]) - 1);
                    textureIndices.add(Integer.parseInt(splitToken[1]) - 1);
                }
            }
        }

        meshReader.close();

        ArrayList<Vertex> processedVertices = new ArrayList<Vertex>();

        for(int i = 0; i < indices.size(); i++) {
            processedVertices.add(new Vertex(vertices.get(indices.get(i)).getPos(), textureCoordinates.get(textureIndices.get(i))));
        }

        // Then 'indices' and 'processedVertices' are sent to the GPU.

```

How can I **correctly implement IBOs** with texture coordinates, **so that an IBO is 'aligned' to a VBO after adding extra vertices** (vertices with the same position but with different texture coordinates)?

# Answer
The problem is that obj files contain vertex data in parts:pos,tex,normal and indices in them point to each of these parts individually. In OpenGL you need to combine those parts into one data object - vertex. And have your indices point to vertices, not their parts.

My code (scala, but should be ok)

```
val vertexListB = new RList[vec3]()//output positions
val texListB = new RList[vec2]()//output texCoords
val normalListB = new RList[vec3]()//output normals
val indexListB = new RList[Int]()//output indices

val vertices = new RList[VertexFull]()//output vertex structure list, consists of pos, tex, normal

for(i <- 0 until vertexIndicesTriangleList.size()){
  val vI = vertexIndicesTriangleList(i) //vertexIndicesTriangleList - all scanned vertex positions from obj file
  val tI = texCoordsIndicesTriangleList(i) //texCoordsIndicesTriangleList - all scanned vertex texture coords from obj file
  val nI = normalIndicesTriangleList(i)//normalIndicesTriangleList - all scanned vertex normals from obj file
  //we are looping through all vertex positions

  val v = vertexList(vI) //some pos
  val t = textureList(tI)//some texCoord that corresponds to that pos
  val n = normalList(nI)//some normal that corresponds to that pos

  val hv = vertexListB.getIndex(v,false)
  val ht = texListB.getIndex(t, false)
  val hn = normalListB.getIndex(n, false)

  if(ht != -1 && hv == ht && hn == ht){ //check for duplicate vertex data, its duplicated if and only if all of 3 components:pos, tex and normal are equal
    indexListB << hv //if ht != -1 then our list does contain that vertex already
  }
  else{
    vertexListB << v //if doesnt contain/not duplicated then put data into the lists
    texListB << t
    normalListB << n
    indexListB << vertexListB.size() - 1//index points to the last put vertex, vertexListB, texListB, normalListB are equal sized
  }

}

for(i <- 0 until vertexListB.size()){
  vertices << new VertexFull(vertexListB(i), texListB(i), normalListB(i))
}

```
> 2 votes

# Answer
Basically, there is Vertex data, which is stored in one or more VBOs. Typical (3D) vertex has like: vec3 pos, vec2 uv, mat3 tbn (or vec3 normal) - maybe some other modifiers, possibly several different uv coords or something like that. Anyways, no matter if you store those to 1 or multiple VBOs, IBO will index all the buffers with same index.

So, each pos/uv/tbn combination is unique vertex: three vertices may have same pos, but if one has different uv (and thus tbn) and one has different tbn/normal, they are then three different vertices. That means, that if you use e.g. three VBOs (one for pos, one for uv, one for normal/tbn), they all need to be exactly the same size.

So, to make your IBO to work, you create an array with all the unique vertex attributes, and index them. I found it easier to use interleaved VBO. Here is my implementation of wavefront OBJ loader (in D; missing some things like normal smoothing):

https://github.com/mkoskim/games/blob/master/engine/blob/wavefront.d

In my own project, I'm slowly moving towards ASSIMP suggested in this thread, too. But still, IMO it is worthwhile to examine your own loaders/generators to get deeper view how GPUs (or at least OpenGL shaders) work with vertex data.
> 3 votes

# Answer
When using index buffers, you are indexing into all of the buffers at the same time. That means that if you have a point which can have multiple texture coordinates(If there is a seam at that point) or normals(for example if faceted) then you need to duplicate the given points vertex coordinates with all possible combinations.

---

If you want to have indexing with texture coordinates and normals, then you have 2 options:

* Export the .obj so that it has all the duplicates already(a.k.a. baking)(I believe you can set this up in 3ds max GW obj exporter by disabling "optimize")
* Do this duplicating of vertices in your own code.

---

I would recommend either leaving this system as-is and worry about performance later or use Assimp, which not only does this all for you, it supports more formats with consistency, and will save you some headaches later with its tangent generation and other useful preprocessing.

Some pseudocode for aligning as asked for:

```
float* verticess = new float[NumFaces * 9]; // vertices : input, verticess ouptut to VBO
float* normalss = new float[NumFaces * 9];  // normals: input, normalss outut to VBO
float* texcoordss = new float[NumFaces * 6];
for(int i = 0; i < NumFaces; i++)
{
    //For 3 vertices with 3(xyz coordinates) va - A vertex index, vb - B vertex ....
    verticess[i * 9] = vertices[faces[i].va-1].v[0]; // vertices[i].v is array of 3(xyz)
    verticess[i*9+1] = vertices[faces[i].va-1].v[1];
    verticess[i*9+2] = vertices[faces[i].va-1].v[2];

    verticess[i*9+3] = vertices[faces[i].vb-1].v[0];
    verticess[i*9+4] = vertices[faces[i].vb-1].v[1];
    verticess[i*9+5] = vertices[faces[i].vb-1].v[2];

    verticess[i*9+6] = vertices[faces[i].vc-1].v[0];
    verticess[i*9+7] = vertices[faces[i].vc-1].v[1];
    verticess[i*9+8] = vertices[faces[i].vc-1].v[2];

    //For normalss 3 normals with 3(xyz coordinates) na - A normal index...

    normalss[i * 9] = normals[faces[i].na-1].v[0];
    normalss[i*9+1] = normals[faces[i].na-1].v[1];
    normalss[i*9+2] = normals[faces[i].na-1].v[2];

    normalss[i*9+3] = vecnormals[faces[i].nb-1].v[0];
    normalss[i*9+4] = vecnormals[faces[i].nb-1].v[1];
    normalss[i*9+5] = vecnormals[faces[i].nb-1].v[2];

    normalss[i*9+6] = vecnormals[faces[i].nc-1].v[0];
    normalss[i*9+7] = vecnormals[faces[i].nc-1].v[1];
    normalss[i*9+8] = vecnormals[faces[i].nc-1].v[2];

    //for texcoordss 3 coords with 2(st coordinates) ta - A tex index ....

    texcoordss[i * 6] = texcoords[faces[i].ta-1].v[0];
    texcoordss[i*6+1] = texcoords[faces[i].ta-1].v[1];

    texcoordss[i*6+2] = texcoords[faces[i].tb-1].v[0];
    texcoordss[i*6+3] = texcoords[faces[i].tb-1].v[1];

    texcoordss[i*6+4] = texcoords[faces[i].tc-1].v[0];
    texcoordss[i*6+5] = texcoords[faces[i].tc-1].v[1];
}

```
> 0 votes

---
Tags: opengl, textures, uv-mapping, obj, index-buffer
---


# Question
Title: Does libgdx implement the game loop for you?
Initially, I assumed that the developer has to implement the game loop because libgdx is a library - not an engine. But then I found out that Graphics has `getDeltaTime()` and `getRawDeltaTime()` so I assume that the game loop is already implemented.

If it is implemented, could someone explain what method libgdx uses? I'm mainly referring to this article. My guess is that it uses a semi-fixed time step? If that's the case, then why might `getDeltaTime()` "be smoothed over n frames?" How exactly is `getDeltaTime()` smoothed?

If the game loop is not implemented, what is the purpose of `getDeltaTime()` when you have `getRawDeltaTime()`?

# Answer
> 1 votes
LibGDX is formally a Framework and does implement the game loop for you. `getDeltaTime()` does smooth out over a number of frames. Instead you could use `getRawDeltaTime()`. I have seen some people get smoother results by capping the framerate to 30/60 instead of using `getDeltaTime`.

---
Tags: java, libgdx, game-loop
---


# Question
Title: Can DirectX9 be used without HWND handle?
I found an excellent code here that does almost everything I need: running an HLSL shader on memory texture to process video frames into another texture buffer without displaying it. http://www.codeproject.com/Articles/207642/Video-Shadering-with-Direct-D?msg=5092502#xx5092502xx

My question is: can DirectX9 be used to work purely with in-memory data without display and without specifying a HWND handle? What needs to change in the code if not giving it a HWND?

The code I'm writing is a DLL that has no graphical interface.

# Answer
> 1 votes
The short answer is that DirectX CreateDevice will simply fail without a HWND. However, a HWND can easily be created with this:

```
HWND dummyHWND = CreateWindowA("STATIC", "dummy", NULL, 0, 0, 100, 100, NULL, NULL, NULL, NULL);

```

---
Tags: c++, directx, directx9
---


# Question
Title: How to Create Device with D3DFMT_A32B32G32R32F
I'm trying to create a DirectX9 device to copy video frame data from one memory buffer to another while processing it through a HLSL shader. I will need half-float or float precision for each channel. For now, D3DFMT\_A32B32G32R32F will do.

I can create the device when passing D3DFMT\_X8R8G8B8 in the presentation parameters, but it will fail when passing D3DFMT\_A32B32G32R32F. I don't want to display this on the screen nor convert it between formats. Both the source and destination texture buffers have the same format.

How can I create a device that will allow me to display the output into another texture of type D3DFMT\_A32B32G32R32F?

# Answer
> 1 votes
You can use `CheckDeviceFormat` to determine if a given `D3DFORMAT` is suitable for the device's backbuffer; it's unlikely that particular format will be.

Instead, try creating the device with any old acceptable backbuffer format (`D3DFMT_X8R8G8B8` for example); it doesn't matter since you won't be rendering to it.

Then create a new texture with the desired destination format (`D3DFMT_A32B32G32R32F`), set it as a render target, and render to *that*.

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