title: Sound Effects on Monogame delay

text:
# Question
Title: Sound Effects on Monogame delay
I have recently added some Sound Effects to my game, but the problem that I am dealing with now, is that they have for a half of second delay, or more sometimes.

Also, if I press repeatedly on that button, the sound effect does not play each time that I press on the button, and when I finish pressing, it plays at least once (I think from the previous presses).

How can I fix this problem? Here is my Play function, if it will help with something ...

```
public void Play(SFX effect)
    {
        if(!Muted)
        {
            switch(effect)
            {
                case SFX.ButtonTap:
                    tapSfx_Instance.Play();
                    break;
                case SFX.Hit:
                    hitSfx_Instance.Play();
                    break;
                case SFX.Die:
                    dieSfx_Instance.Play();
                    break;
            }
        }
    }

```

Thanks.

# Answer
It may just be that the sound is not done playing, and you are continually asking it to resume. This could potentially create a delay, depending on your logic.

You may want to add a few lines to see if solves your problem:

```
public void Play(SFX effect)
{
    if(!Muted)
    {
        switch(effect)
        {
            case SFX.ButtonTap:
                if (tapSfx_Instance.State != SoundState.Playing)
                    tapSfx_Instance.Play();
                break;
            case SFX.Hit:
                if (hitSfx_Instance.State != SoundState.Playing)
                    hitSfx_Instance.Play();
                break;
            case SFX.Die:
                if (dieSfx_Instance.State != SoundState.Playing)
                    dieSfx_Instance.Play();
                break;
        }
    }
}

```
> 2 votes

---
Tags: xna, c#, monogame
---


# Question
Title: Instantiation of a GameObject not working for a threading reason
I receive the following error

> "INTERNAL\_CALL\_Internal\_InstantiateSingle can only be called from the main thread." "Constructors and field initializers will be executed from the loading thread when loading a scene." "Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function."

whenever I try to instantiate some `GameObject's` using this function:

```
public void DisplayCalls () {
    for (int i = 0; i < calls [0].Count; i++) {
        for (int j = 0; j < impFields.Length; j++) {
            GameObject textClone = Instantiate (textBox, Vector3.zero, Quaternion.Euler(Vector3.zero)) as GameObject;
            textClone.transform.SetParent (canvas.transform);
            Text text = textClone.GetComponent <Text> ();
            text.text = calls[impFields [j]][i];
            text.alignment = TextAnchor.MiddleCenter;
            textClone.transform.localPosition = new Vector3 (-262.5f + (175f * j), (182f + (30f * i)), 0f);
        }
    }
}

```

The function is called using this other function:

```
public void GetPanelInfo () {
    string file = "getpanelinfo.php";
    string hash = Md5Sum (mostRecentID.ToString () + SecretKey1 + SecretKey2);
    string parameters = "?mostrecentid=" + mostRecentID.ToString () + "&hash=" + hash;
    string fullURL = baseURL + file + parameters;
    Uri fullURI = new Uri (fullURL);
    WebClient client = new WebClient ();

    string jsonString = string.Empty;
    client.DownloadStringCompleted += (sender, e) => {
        if (!e.Cancelled && e.Error == null) {
            jsonString = e.Result;
            JSONNode json = JSON.Parse (jsonString);
            for (int i = 0; i < json["calls"].Count; i++) {
                for (int j = 0; j < calls.Length; j++) {
                    calls[j].Add (json["calls"][i][names [j]]);
                }
                mostRecentID = json["calls"][i]["callID"].AsInt;
            }
        } else if (e.Cancelled && e.Error == null) {
            Debug.Log ("Cancelled");
        } else {
            Debug.Log ("Error: " + e.Error);
        }
        loading = false;
        LogCalls ();
        DisplayCalls ();

    };
    client.DownloadStringAsync (fullURI);
}

```

Which is called once using a button.

I cannot seem to find the problem, but as stated above, the error says that it is a threading problem and that I cannot call instantiate from another thread other than the main one. I do not know how to change the instantiation to another thread, but any help to solve this problem would be much appreciated.

# Answer
> 2 votes
Looking at the WebClient docs, the method is described as:

> Downloads a `string` from a resource, without blocking the calling thread.

and given the error message:

> `INTERNAL_CALL_Internal_InstantiateSingle` can only be called from the main thread

It's clear that you need to download the data and store it, and only call `DisplayCells`, in the main thread, once the download is complete. This is not unique as in Cocoa, for example, you can only call UI-related API methods on the main thread.

It took me some hunting on Google to find any decent info on this (I am a beginner when it comes to Unity/C#), but I *think* this will do it:

Create a boolean that is shows there is data to display:

```
private bool _callsToDisplay = false;

```

Set that when the data has downloaded:

```
client.DownloadStringCompleted += (sender, e) => {
    ...
    loading = false;
    LogCalls ();
    _callsToDisplay = true;
};

```

and then in the `Update()` method (which runs on the main thread), call `DisplayCalls()` if that boolean is set:

```
void Update()
{
    if (_callsToDisplay) {
        DisplayCalls();
        _callsToDisplay = false;
    }
}

```

# Answer
> -1 votes
I think this is happening because you are trying to Instantiate() in a class that does not derive from MonoBehaviour.

Ensure that the class you use to "Instantiate" gameobjects, derive from the MonoBehaviour base class, otherwise, you will be getting this error.

---
Tags: unity, c#, multithreading, instancing
---


# Question
Title: How does Direct3D know if a constant buffer is for the vertex or pixel shader?
I have a question about constant buffers in directX 11. They really confuse me and after searching on google most sites simply supply sample code without explaining how it works. I am probably overlooking something but, as of now, they appear to me to work by sheer magic. Say I have two constant buffers in an hlsl file:

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

cbuffer cbPerFram
{
    Light light;
};

cbuffer cbPerObject
{
    float4x4 WVP;
    float4x4 World;
};

```

And I create an equivalent buffer in my C++ program like so:

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

cbbd.Usage = D3D11_USAGE_DEFAULT;
//cbPerObject is a struct with same layout as cbPerObject in HLSL file
cbbd.ByteWidth = sizeof(cbPerObject);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;

hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
//Create the buffer to send to the cbuffer per frame in effect file
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));

cbbd.Usage = D3D11_USAGE_DEFAULT;
//cbPerFrame is struct with same layout as in cbPerFrame in effect file
cbbd.ByteWidth = sizeof(cbPerFrame);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;

```

And then I update one like this:

```
d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer);

```

How does directX know which constant buffers in my shader are going to be used for VS and which for PS and which buffers in my codes correspond to which buffers in my hlsl? For example I call VSSetConstantBuffers above and pass the arguments and it automatically knows to throw that stuff in the per object buffer as opposed to trying to put it in the perFrame buffer. As far as I can tell when creating cbPerObjectBuffer, I never explicitly bound it to the cbPerObject buffer in my hlsl. Is slot number dependent on the order the buffers appear in hlsl? The only way I can figure is that the data structures simply define an interface to the buffer memory on the card and it is up to the programmer to use the correct one. For example, I COULD attempt to use cbPerFrame in my vertex shader and indeed the same data can be accessed that way but in order to get correct results you would have to access it using offsets into the light object. Does what I am asking make any sense? lol

# Answer
> 6 votes
The key step that you're missing is the implicit slot assignment that occurs when you compile a shader. When you compile an HLSL shader that contains a bindable object (be it a `Texture2D`, `RWStructuredBuffer`, or `cbuffer`), each object must be assigned a slot number. This corresponds to the `UINT StartSlot` parameter to e.g. `VSSetConstantBuffers`. You can optionally declare a slot explicitly using e.g. `: register(c0)` as a declaration suffix, but if you omit the slot, the compiler will assign the lowest free slot available.

As for your original question, how DidrectX "knows" what cbuffer to bind, well it doesn't. What's actually happening is that since in your vertex shader, you only refer to one `cbuffer`, that gets assigned slot 0 for the vertex shader when you compile it, and the other is ignored. Likewise, the same occurs for the pixel shader, except the other `cbuffer` is assigned to slot 0. This means that when you assign buffers to the 0 `StartSlot` for both the vertex and pixel shader stages, it just so happens that those are the right buffers for those shaders. Basically, it just happens to work because slot 0 is always the right slot. Once you get to more advanced shaders that reference multiple `cbuffer`s, you'll want to get into the habit of assigning slots explicitly.

# Answer
> 6 votes
`VSSetConstantBuffers` stands for `VertexShaderSetConstantBuffers`. Hence you also got `PSSetConstantBuffers` for the pixel shader.

---
Tags: directx11, hlsl
---


title: Clean way to do sprite flashing?

text:
# Question
Title: Clean way to do sprite flashing?
In old, 8-bit/16-bit games, sprites flashing every other frame were common. I don't want to use the hacks I've used before. Is there an elegant/clean way to do this? This is how I usually do it:

```
bool everyother = false;
// update
everyother = !everyother;
// draw
if (flashing && everyother)
    // do nothing
else
    // draw

```

Seems like a hack to me.

# Answer
> 2 votes
For those unfamiliar with the concept, the proper term is **sprite flickering**. Old consoles like the NES could only display a certain number of sprites simultaneously, so to work around this limit and show more sprites, games would show them on alternating frames.

Your solution can get quite complex if you want to properly emulate the effect, that is, ensure that only X number of sprites are shown simultaneously, which means coordinating the flickering between sprites.

But assuming you don't need to be that authentic and just fake the appearance, a boolean flag is pretty much the simplest way to do it, for 2-frame flickers.

Another method, which doesn't require extra state, is to check whether the current **game frame** is odd or even. E.g.

```
for (int game_frame = 0; ; game_frame++) {
    if (game_frame & 1) {
        sprite.draw();
    }
}

```

# Answer
> 2 votes
There's nothing particularly inelegant or "unclean" about what you're doing already (toggling every frame), especially if you're also using a fixed framerate.

If you're *not* using a fixed framerate, you may want to consider a slight change to toggle the sprite visibility based on elapsed real-time instead, as this will ensure a more consistent flicker rate than tying it to a variable framerate would.

This looks basically the same:

```
void updateGame (float elapsedSeconds) {
  // ...

  flickerAccumulator += elapsedSeconds;
  if (flickerAccumulator >= 0.25f) {
    // Quarter-second flicker-on/flicker-off periods.
    sprite.visible = !sprite.visible;

    // You could just reset to 0 and probably be safe, this
    // attempts to account for "overflow" into the next
    // quarter-second period.
    flickerAccumulator -= 0.25f;
  }

  // ...
}

```

---
Tags: c++, sprites
---


# Question
Title: Creating an Android port of old PC games
I have seen some decent ports to Android of old PC games.

The graphics and game engines are the same, and all that seems to have been changed was the key mapping, and adding touch-screen events.

I want to play around with learning how to do this, but I have done a lot of searching online, and haven't been able to find a general overview of how to begin.

What would I to do, or at least, where can I learn how, to take an old, existing PC game, and port it to Android, only changing the key-mappings, and add touch-screen support?

From what I have seen, a native app is created to launch the game, and then from that point, you're just playing the original game.

And I'm not referring to playing games through emulators. This is something that would be able to be downloaded from the Google App store. And I would first get rights to do so, of course, unless it was, or has been released as, an open-source game.

# Answer
Which game specifically? What engine does it run on? Is the source available? If the source isn't available then you're SOL unless you REALLY like decompiling.

Chances are good the code base is C or C++ (lets hope so). That means you have to compile with the Android NDK which isn't trivial. My experiences with it have been painful. You're right you have to refactor the game to use touch events which means a complete overhaul of the input system and designing a control scheme that works on a phone. You'll also need to re-write the window management system. Android uses an Activity system and you'll need to create an activity and a GL context from inside the NDK (which sucks) or you'll need to create the Activity in Java and call all the game logic through the JNI.

Lets also not forget that older games sometimes use assembler. x86 isn't compatible with ARM so you'll need to rewrite those sections in either ARM assembler or just C/C++ and let the compiler handle it.

It's not easy but at the end of the day you'll end up with (hopefully) an APK that you can install on your phone!

Speaking of assembler, compilers suck. Different platforms implement C/C++ slightly differently so there may be some parts of the code where the developers relied on assumed type sizes which can change from platform to platform. These problems might manifest when you try to run the game as random crashes which will require some serious debugging so watch out!

Lets not forget about drawing to the screen! Older games sometimes used "software rendering" where the program itself (rather than a GPU) would draw to the screen. This is big no-no nowadays so you'll need to refactor all that code to use OpenGLES. If the game uses hardware it will probably use an older fixed function version of DirectX which will need to be rewritten as modern GLES. Heck even if the game is using a modern OpenGL drawing system you'll still need to make sure all the shaders will work well on mobile.

A lot of problems can be alleviated by using SDL2's Android port. It should make it a bit easier to handle input and setup all the OpenGL goodies you want. Heck you could probably use the SDL surfacing system to draw instead of doing all the OpenGL yourself.

Here's a good article on writing native activities in Android: http://developer.android.com/reference/android/app/NativeActivity.html

Here's the SDL documentation for Android: https://wiki.libsdl.org/Android

For SDL you'll probably need to be using a \*nix environment. Check out Cygwin or CMDER if you're on Windows (I like CMDER)

Good Luck! Don't forget to come back and ask more specific questions if you get stuck.
> 2 votes

---
Tags: android, platformer, pc, porting
---


title: Quadtree splitting

text:
# Question
Title: Quadtree splitting
A quadtree has limit on number of item in each nodes. Suppose a node has already has same number of item as the limit. If I add another item on same node the node should split and new item should be added there. What I dont understand, Is previously existed node should be shifted to the new node? or they will remain where they were (parent of newly craeted node)?

# Answer
It's a quad tree so when you split it into 4 parts any entities belonging to the parent get divided between the children based on position.
> 3 votes

---
Tags: data-structure, quadtree
---


title: Mapping a C++ struct to an HLSL cbuffer

text:
# Question
Title: Mapping a C++ struct to an HLSL cbuffer
Out of curiosity (and peace of the mind...) I wondered how DirectX decides which attribute from a `struct` corresponds to the right variable inside an HLSL cbuffer-register(x) (apart from the order/type they are declared with).

My main concern is my structs not only have member variables but 2 constructors each. So how can I be sure the constructors are not at the beginning of my struct definition (memory wise - C++ question I guess) so my variables would overflow after my cbuffer ? Additionnaly, can I only rely on declare-order/type matching ?

Is there a more precise/explicit way than doing :

```
struct foo {
    int a;
    int b;
    int c;

    foo () {}
    foo (int a, int b, int c) : a{a}, b{b}, c{c} {}
}

D3D11_BUFFER_DESC constantBufferDesc;
...
constantBufferDesc.ByteWidth = sizeof(foo) + (16 - sizeof(foo) % 16);
hr = g_d3dDevice->CreateBuffer(...);
g_d3dDeviceContext->VSSetConstantBuffers(0, 1, &fooBuffer);
g_d3dDeviceContext->UpdateSubresource(&fooBuffer, 0, nullptr, &foo, 0, 0);

```

With HLSL :

```
cbuffer foo: register(b0) {
    // constructor here ?
    int a;
    // constructor here ?
    int b;
    int c;
    // constructor here ?
}

```

I am aware this is more a C++ question - Thanks for your insight.

# Answer
> 8 votes
> Out of curiosity (and peace of the mind...) I wondered how DirectX decides which attribute from a struct corresponds to the right variable inside an HLSL cbuffer-register(x) (apart from the order/type they are declared with).

Purely through memory layout. You give D3D a pointer to a chunk of memory which you claim to be organized in a certain fashion (for example, via your cbuffer definition). It's up to you to ensure that organization is actually true.

> My main concern is my structs not only have member variables but 2 constructors each. So how can I be sure the constructors are not at the beginning of my struct definition

In C++, member functions (such as constructors) do not take up space in the memory layout of an instance of a structure type. In your example, `sizeof(foo)` is going to be `3 * sizeof(int)`, so it will map correctly to the `foo` structure in HLSL. So you don't need to worry about this.

Most of the time.

---

One potential issue would be if you have any *virtual functions* define in your type. Although it is implementation-defined how the virtual methods are handled, the far-and-away most common implementation is to stuff a pointer to the type's virtual table at the start of an instance of a type. This will offset everything by `sizeof(void*)` and render your structures mismatched.

Another potential issue is structure padding; compilers can and will insert dummy data between structure members (padding) to ensure the data is appropriately aligned. *Generally* you don't need to worry too much about this, as the types you are likely to use in your structures are those that usually end up tightly-packed once default compiler alignment comes into play. However if you have specialized alignment needs for either your CPU-side or GPU-side structures, and have padding in your type as a result, this is something you need to be aware of.

Thus, as long as you don't have any virtual methods defined in your structure types that you're mapping to GPU buffers, and you don't have any weird padding going on, you have nothing to worry about.

# Answer
> 1 votes
My assumption based on my experiences with shader reflection in DX11 is that it's mapped by name. If you check out the DX11 shader reflection API you'll see that there is a `D3D11_SHADER_VARIABLE_DESC` struct that you can rip from the shader. Notice the LPCSTR for the name of the variable. OpenGL also handles variable mapping by name.

Of course the best way to find out is to try it yourself! Try repositioning your constructors and see if it affects your cbuffer buffering.

https://msdn.microsoft.com/en-us/library/windows/desktop/ff476213%28v=vs.85%29.aspx

---
Tags: c++, directx11, hlsl, memory-efficiency
---


# Question
Title: Java Game How to change opacity of an image?
Hello I have a game where you feed animals. A few minutes after you feed them they do a poo. I want the poo to fade away after a few seconds. I want to know how to change the opacity on the image. How can I do this?

here is my code:

```
package items;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class poo {

    public int x, y;
    private Image img;

    public int time = 0;
    public int timer = 100;
    public boolean remove;

    public float alpha = 1f;

    public poo(int x, int y) {
        this.x = x;
        this.y = y;

        alpha = 1f;
    }

    public void tick() {
        if (time >= timer) {
            time = 0;
            // remove = true;
        } else {
            time++;
        }
        if (alpha > 2) {
            // alpha--;
        } else {
            // remove = true;
        }

    }

    public void render(Graphics g) {

        ImageIcon i2 = new ImageIcon("res/items/poo.png");
        img = i2.getImage();

        g.drawImage(img, x, y,6,8, null);

    }
}

```

# Answer
You could use an AlphaComposite to draw your Image transparently on top of what you have already drawn.

```
//...
float alpha = 0.5 //draw half transparent
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,alpha);
g.setComposite(ac);
//g.drawimage...

```

Here is a question with a similar topic: https://stackoverflow.com/questions/17731576/making-an-image-fade-in-and-fade-out/17731785#17731785

And this is the official help topic from oracle, that explains the blend modes: https://docs.oracle.com/javase/tutorial/2d/advanced/compositing.html
> 6 votes

---
Tags: java
---


# Question
Title: Creating Fog Of View in 2D game with lighting method
I'm creating 2D side scrolling game with Unity, and i want to add feature where the player come into a cave, then all going dark, the player turn on the flash light, so the player can see around ( With limited range )

I have done creating that by setting all object color to Black, and if the light is touching the object, the object color turned to White, but the problem is, if just a little of light touching the object, the entire object color turned to white ( No Gradation or something like shading )

so my question is

Is there any suggestion or another method to fix that ?

# Answer
> 0 votes
Maybe i dont understand what you are trying to do, but the standard way to do this is to have a spot light as your flash light. In your case you would disable all lighting sources in the scene and set global ambient lighting to 0. This will make the scene pitch black where only the spot light attached to the player visible.

For 2d you will need to add normals maps to your sprites. this tutorial covers this. https://www.codeandweb.com/blog/2015/05/04/2d-dynamic-lighting-tutorial-for-unity.

With normal mapped sprites your sprites can perform lighting calculations with the regular unity lighting system.

Note you dont need normal maps for sprite lighting, if you angle the spot light correctly you will still light up your sprites. Unity will use the default normal's for lighting calculations.

---
Tags: unity, 2d, lighting, shadows, side-scroller
---


# Question
Title: Is there a way to make a dynamic world such as a MMORPG horizontally scalable?
Imagine a open-world of 500+ players with data changing as fast as 20 updates/player/second. Last time I worked in a similar MMORPG, it used SQL, so obvioulsy it couldn't query the DB all the time. Instead, it loaded all players from the DB to memory as C++ objects and used them. That is, it scaled vertically. Would it be possible to make that server horizontally scalable instead? Is there a database designed to support that amount of updates concurrently?

# Answer
Test case of 500 players all communicating, that's 250K streams of information flying around at 20Hz. The internal bandwidth for that would be, assuming 100 bytes each message, about 500MB/sec. Sounds ambitious. Especially between processes.

If you segregate players to groups of 100, that lowers to 20MB/sec, and so on. Which is why MMOs have zones, and in those zones little bubbles of influence, and so on downwards until bandwidth becomes reasonable.

The original problem can be stated that **if you have 10 people all sharing realtime information, but you want 500 all sharing**, that's an exponential growth of communication links and **how can we get around that**. I'm afraid that there's no magic bullet that I've ever heard of that can magically make geometric progression go away.

Don't use a database to communicate, that's what messaging is for. Use the database to enforce transactions and store info you don't want players to lose. Most MMOs that I'm familiar with only update the database with dynamic player info every 1-10 minutes, or at handy points like zone transitions or entering "safe" zones in the design.

You may have to redesign the game's **need** for every player, no matter how far away, to have realtime updates of every other player's backpack contents.

Also change the update pattern from 20Hz to a speed based on distance, someone 1 mile away does not need to know that you moved 1 foot at exactly 230.6 seconds, then another foot at 231.4 seconds, they can deal with you moving 15 feet every 10 seconds.
> 17 votes

# Answer
Use area of interest filtering. If a world is broken into 3 servers, and the area on server 1 is nowhere near the area of server 3, there's no reason for them to share information about entities at all.

Likewise, on a single server, only send relevant information to clients. If player A is on the totally opposite end of the map from player B, there's zero reason to send updates about B to A, or vice versa.

When you have multiple servers in a continuous world, you will have entities near an edge on server 2 that are close to entities on server 1. You can send updates from the "authoritative" server for an entity to the other server (when appropriate), and likewise forward any messages to the authoritative server as appropriate.

Yes, in this case, one server will be slightly out of date for particular entities. Don't try to solve that. Just deal with it. Assume that entities may be a little out of date. Do any logic that needs up-to-date information only on the server that authoritatively owns the entities. When an entity affects another, send a message and assume that it may take multiple game logic ticks before it is processed and your view updates.

This design also makes it much easier to thread a single server. No entity should directly modify another, only send messages, and the local per-server/per-thread proxy caches should be assumed to be slightly out of date.

For example, if entity A attacks entity B, don't check the life of B and then send a death message if it hits 0. Just send a "damaged" message, let the authoritative server for B handle it, and then handle any "entity-died" message sent out by server B later if entity A cares about that.

The same applies to any large, scalable non-games application. A central database is not a magical instant-sharing technology. Two servers must communicate with messages, asynchronously, in batches, in order to maintain high throughput. Hence the popularity of technologies like AMPQ and the like. Databases are for storage and support synchronization out of necessity allowing them to be used for communications, not because they are themselves meant for synchronization or communication.
> 5 votes

# Answer
You will be probably interested in this article on Gamasutra, where Eve Online developers discuss how it's possible to succesfully run a game with 400 000 active players... in one SQL database.
> 3 votes

# Answer
Don't think of the database as some kind real-time shared world model storing everything about everything at all times — as you've noticed, that can't possibly work.

Instead, treat the database more like an automatically-updated save file: you update the database only occasionally, such as when players log in or out or move from one zone to another, or whenever something important happens that you don't want to be lost in case of a server crash.

The actual real-time world state should be held by the game servers, in memory, just as in your original example. Now, the trick for horizontal scaling is that **not every server needs to know everything at every moment**. For example, if player A is playing in zone A on server A, server B running zone B doesn't usually need to know what player A has in their backpack — and, if it *does* need to know that for some reason (say, because player B in zone B casts some kind of remote spying spell on A) it can just **ask the other server for that information**.

This does require you to assign clear responsibilities to the servers, so that when server B wants to know about player A's backpack, it will know which server has the authoritative information on that. You will also likely want to include some kind of update subscription mechanism, so that e.g. server B can just tell server A "*I have someone spying on player A, keep me updated about everything they do until I tell you otherwise.*" You will probably also want to include some kind of global broadcast system for important global events that players may need to know about no matter where they are; of course, such events should also be recorded in the database, but having them actively broadcast to all server means that the servers won't have to keep polling the database for updates.
> 2 votes

# Answer
Other responses have done a good job of pointing out how to use a database, and not to use a database for communication. One other aspect that you might look into is to categorize your updates based on how the information needs to be communicated to other entities. Rather than scope communication to servers, you could distribute your messaging and use pubsub mechanisms for communicating updates between entities. For instance, you might treat location differently based on who's close to you:

* Precise, real-time location might be useful within radius R
* Less-precise, less frequent location updates might be useful within radius 2\*R
* No location information might be needed beyond radius 2\*R

You might communicate location information for an entity by periodically scanning for entities within radius 2\*R (or some multiple of that based on update rate and maximum velocity of an entity), and subscribing the entity to the other entity's precise or imprecise location feed.

You could have different strategies for different types of information, group common things into the same message queues, or have different queues for messages that need to go to different entities (or just send them to the broadest set of entities and have messages discarded if they're not useful).
> 2 votes

---
Tags: mmo, data-structure, databases, scalability
---


# Question
Title: Unity error "must have a body because it is not marked abstract, extern, or partial"
I'm trying to setup a system where I pickup an object drop it into a zone, and then the object is destroyed.

So far I have:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class TriggerZone2 : MonoBehaviour {
    public Text MyText;
    private int score;
    public bool CompareTag(string Player);

    // Use this for initialization
    void Start () {
        MyText.text = "";
    }

    // Update is called once per frame
    void Update () {
        MyText.text = "$" + score;
    }

    void OnTriggerEnter(Collider coll) {
        score = score + 1;

        if (other.CompareTag ("Player")) {
            Destroy (other.gameObject);
        }
    }
}

```

Everything works up until I try to destroy the game object. The console keeps saying

> Assets/Scripts/TriggerZone2.cs(11,21): error CS0501: \`TriggerZone2.CompareTag(string)' must have a body because it is not marked abstract, extern, or partial.

I've looked up quite a few threads, but I'm still not sure what it wants me to do with it. How do I fix this?

# Answer
That error is saying there's no CompareTag() method defined. That error points to line 11 in your script; note that CompareTag() is called on that line, but there is no CompareTag() defined in your script.

In this case, I don't think you wanted to write `public bool CompareTag(string Player);` I'm not sure what you're even trying to do there, but it looks unnecessary so just delete that entire line.
> 2 votes

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


# Question
Title: Getting mouse movement value with DirectX Tool Kit
today I want to ask a question about how to get mouse movement value with DirectX Tool Kit.

While I can certainly use `Mouse::SetMode(MODE_RELATIVE)`, to do this, I want to be able to get the mouse cursor position at the same time (which can only be done with `MODE_ABSOLUTE`).
The method I thought of involves leaving mouse mode as the default `MODE_ABSOLUTE`, and then subtract the mouse position from the previous frame from that of the current one.
But with this method, the mouse cursor can jump out of the window.
So I thought of restricting the mouse cursor to a certain point, but this obviously prevents me from calculating the movement value with said method.
Does anyone have some ideas on how to achieve this with DirectX Tool Kit ?
Or am I missing some obvious thing ?
Thanks in advance!

# Answer
> 1 votes
If I am understanding the question correctly, you just want the delta mouse when you are in relative mode.

According to the mouse documentation, when you query the state of the mouse, the x and y coordinates return the delta.

Note, because you are in relative mode and the mouse is locked, the mouse is likely always in the center of the window so any fixed position is worthless. (You could always use the native APIs to get it's true position if you so desire)

---
Tags: directx, directx11, input, mouse
---


# Question
Title: Background Scrolling like Zelda - A Link To The Past with XNA
i am trying to create a background that scrolls like the one in zelda - a link to the past. in other words: i have a bigger "screen" than the camera covers, so i need to scroll over it, when moving. if the player reaches an edge of the screen, the camera is going to stop and the character moves out of the center.

my actual problem is, that i have to draw the objects in an other way than the background. i am getting the camera to track the player, but if i want to add another object like an enemy, i have to draw it with screen coordinates, which are not the same as the background coordinates. (background image is 1280x720 with a source rectangle of 640x360). so the player is usually drawn at 640/2, 360/2. but the player also is at position 600,600 of the background image. so, if there is an enemy at 200,200 and the player moves to that point i want to draw the enemy on the screen. but, of course, i cant draw it at 200,200 in the screen that displays the sorucerectangle of the texture.

so i am looking for a way to kinda get the object into the texture, that there is only one coordinate system or at least a second coordinate system where all the object are in., which is as big as the texture itsself. with such a coordinate system i could get the absolute positions of the objects and draw it like the sourcerectanlge of a texture.

# Answer
So basically what you want to do is check to see what the scroll position is after a key is pressed, and with an if else statement, check to see whether you should move the background or the character. For example:

```
    if (CurrentKeyboardState.IsKeyDown(keys.Right))
    {
        if (BackgroundXPosScroll < BackgroundTexture.Width - CurrentScreenLength - 5)
        {
            BackgroundXPosScroll += 5;
        }
        else
        {
            CharacterXPosScroll += 5;
        }
    }
    BackgroundXPosition = -BackgroundXPosScroll;
    CharacterXPosition = CharacterXPosScroll + CharacterXPositionOnScreen;

```

Then you want to check with the left arrow key if the character X position is bigger than the center of the screen... if so, move the character, if not, change the BackgroundXPosScroll by -5. That takes care of moving one direction... the other directions are just different implementations of that code.
> 0 votes

---
Tags: xna, c#, scrolling
---


# Question
Title: How can I change my rendering loop to improve scalability across effect types?
This is the code that I use to setup my shader:

```
char* vertexShaderSource = getResource("vert.shad");
char* fragmentShaderSource = getResource("frag.shad");

vshad = readFile(vertexShaderSource);
fshad = readFile(fragmentShaderSource);

free(vertexShaderSource);
free(fragmentShaderSource);

GLuint getShaderProgram(const char* vshad, const char* fshad)
{
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);

    glShaderSource(vertexShader, 1, &vshad, NULL);
    glCompileShader(vertexShader);

    GLint success;
    GLchar infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

    if(!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        printf("ERROR VERTEX COMPILATION_FAILED %s\n",infoLog);
        SDL_Quit();
    }

    GLuint fragmentShader  = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fshad, NULL);
    glCompileShader(fragmentShader);

    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);

    if(!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        printf("ERROR FRAGMENT COMPILATION_FAILED %s\n",infoLog);
        SDL_Quit();
    }

    GLuint shaderProgram = glCreateProgram();

    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);

    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if(!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        printf("ERROR SHADER PROGRAM COMPILATION_FAILED %s\n",infoLog);
        SDL_Quit();
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    return shaderProgram;
}

```

This code sets up a VAO to render a textured quad:

```
glGenVertexArrays(1, &vao);
    glGenBuffers(1, &verticesBuffer);
    glGenBuffers(1, &colorBuffer);
    glGenBuffers(1, &indicesBuffer);
    glGenBuffers(1, &texCoordBuffer);

    glBindVertexArray(vao); //bind vertex array buffer

    glBindBuffer(GL_ARRAY_BUFFER, verticesBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(r->vertices), r->vertices, GL_STATIC_DRAW);

    //bind n setup indices
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(r->indices), r->indices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind indices

    //bind n setup colors
    glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(r->colors), r->colors, GL_STATIC_DRAW);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind colors

    //bind n setup texture coords
    glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(r->texCoords), r->texCoords, GL_STATIC_DRAW);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(2);
    glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind texture coords

    glBindVertexArray(0); //unbind vertex array buffer

```

And this sets up my texture:

```
glGenTextures(1, &colorTextureID);
glBindTexture(GL_TEXTURE_2D, colorTextureID);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexImage2D(GL_TEXTURE_2D, 0, Mode1, colorSurface->w, colorSurface->h, 0, Mode1, GL_UNSIGNED_BYTE, colorSurface->pixels);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
free(colorSurface);

```

Finally, the rendering code:

```
void render()
{
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    glUseProgram(sp);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, colorTextureID);//ourTexture
    ourTexture = getUniformLocation(sp, "ourTexture");
    glUniform1i(ourTexture, 0);

    glBindVertexArray(verticesBuffer);
    viewMat = getUniformLocation(sp, "viewMat");
    modelMat = getUniformLocation(sp, "modelMat");
    projMat = getUniformLocation(sp, "projMat");

    maxIterLoc = getUniformLocation(sp, "maxIterations");
    centerLoc = getUniformLocation(sp, "center");
    scaleLoc = getUniformLocation(sp, "scale");

    glUniformMatrix4fv(viewMat, 1, GL_FALSE, vm.m);
    glUniformMatrix4fv(projMat, 1, GL_FALSE, opm.m);
    glUniformMatrix4fv(modelMat, 1, GL_FALSE, tm.m);

    glUniform1i(maxIterLoc, maxIterations);
    glUniform1f(scaleLoc, scale);
    glUniform2f(centerLoc, cx, cy);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);

    SDL_GL_SwapWindow(window);
}

```

This whole setup is just to render a textured quad; basically a non-alpha-blended sprite.

I already put the code to create the shader program in a class of it's own but there's still all the other code of setting up the VAO, texture and the state setup before rendering.

How are these things structured in bigger systems? Imagine if I had to render a textured, normal mapped, shadow mapped 3D model. This code would get significantly longer.

This sample code below is how I was thinking of generalizing the rendering code. This way I can create a few different types of shaders without have so much clutter right in my main class.

```
    gluint shader_program = -1;
    glint vao, vBuff, iBuff, cBuff, tBuff;
    glint textures;

    shader_program create_sprite_shader()
    {
     glGenVertexArray(...)
     glGenBuffers(...)
     .... do all bind buffer and buffer data
    }

    void use_shader(shader_program s)
    {
     glUseProgram(s->program);
     glActivateTexture(gl_texture0);
     glBindTexture(sp->texture_type, sp->texture);

     get all uniform and attribute locations from shader..
     bind their values
    }

    render(mat44 model, mat44 view, mat44 proj)
    {
      //pass model view and projection matrices to the shader
    }

    unbind_shader()
    {
     glUseProgram(0);
    }

```

Then, in the main program:

```
shader_program s_shader;

init_main()
{
  s_shader = create_sprite_shader()
}

while(game_running)
{
  update_game() { .. };
  handle_input() { .. };

  render()
  {
   use_program(s_shader);
   for(0 ... 10)
   {
     s_program->render(sprite[i].modelMatrix, viewMatrix, projMatrix);
   }
   unbind_shader();
  }
}

clean_up() { //clean up resources }

```

I could have a `toon_shader`, a `metal_shader`, etc. Is that the way these parts of the code are built?

I've seem some reference works looking at Intel, Nvidia, etc., but those are usually laid out how my code is currently right now, which doesn't scale well.

# Answer
> 3 votes
I can give one small piece of advice. Don't do this in your render loop:

```
viewMat = getUniformLocation(sp, "viewMat");
modelMat = getUniformLocation(sp, "modelMat");
projMat = getUniformLocation(sp, "projMat");

maxIterLoc = getUniformLocation(sp, "maxIterations");
centerLoc = getUniformLocation(sp, "center");
scaleLoc = getUniformLocation(sp, "scale");

```

You should get the uniform locations only once, usually just after you've compiled your shader and linked it. Then save the locations and just write to them. Getting data from OpenGL tends to be very slow.

Or, as mentioned in the comments, don't even query them at all. In newer versions of OpenGL (3.0 and later, I think), you can specify uniform locations in the shader using layout specifications. Then you don't need to query what they are. It would look something like this:

```
layout (location = 0) in vec4 vPosition;
layout (location = 1) in vec3 vNormal;
layout (location = 2) in vec3 vTangent;
layout (location = 3) in vec3 vBinormal;
layout (location = 4) in vec2 vTexCoord;

```

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


title: OpenGL what is VBO and when to use it?

text:
# Question
Title: OpenGL what is VBO and when to use it?
So I am currently creating a game based on static voxels, there is no manipulation of voxels, which allows me to optimize it more.

Now, my friend was kind enough to teach me modern OpenGL. Currently I use OpenGL 1.1, and the primitive glBegin/glEnd methods. We went straight into VBOs because I wanted to render voxels using modern OpenGL, but we went too far because I didn't understand much about the fundamentals, such as vectors. That's been resolved and I asked what a VBO is, and he responded with an answer that I think it isn't the right one.

"It stores static vertices on the gpu", I'm not sure if this is correct, so please answer what a VBO is.

TL;DR: read the last sentence.

Thanks in advance!

# Answer
A Vertex Buffer Object (in short VBO) is an object(buffer) that holds vertex data. It's your job, as the programmer, to fill the VBO with this data (usually Vertex positions, texture coordinates and normals) and then send it to be handled by the GPU.

This is an example of VBO initialization:

```
glGenBuffers( 1, &vbo ); // Generate a VBO handler
glBindBuffer( GL_ARRAY_BUFFER, vbo ); // Bind the handler
glBufferData( GL_ARRAY_BUFFER, 3 * 6 * 4 * sizeof( float), cubeVertices, GL_STATIC_DRAW );
// Allocate and initialize storage space

```

We're saying that we want a VBO that will store 72 floats (3 coords xyz, 6 faces, 4 vertices per face). `cubeVertices` is just an array of vertices (floats), and it has redundant vertice data (but don't mind that, it's just an example).

Later when you want to draw the cube you only have to bind the VBO again and draw it using a single function call. (Well, you still need a few more to bind buffers again).

By using VBOs you'll send your Vertex data only once during initialization, whereas using the deprecated functions `glBegin/glEnd/glVertex` you would have to send Vertex data every frame.

Back to the `GL_STATIC_DRAW` in my initialization example, this means that you won't be changing the buffer data later on. But you could also use `GL_DYNAMIC_DRAW` so that you can change vertices later. There are other flags.

However, these flags are just a hint for the GPU to decide where and how to store them. A dynamic VBO is easier / faster to update than a static one, but you can also change data on a static VBO (though you should of course use the right flag for your purposes).

For more info check: https://www.opengl.org/sdk/docs/man3/xhtml/glBufferData.xml

And also: https://www.opengl.org/sdk/docs/man3/xhtml/glBufferSubData.xml

---

In OpenGL 3+, you'll also use Vertex Array Objects (or VAOs) that will store multiple VBOs. These can be setup to hold the data to be sent to your own shaders, so you can even make a VBO holding vertex temperature, vertex happiness, whatever you want.
> 4 votes

# Answer
VBO's (**V**ertex **B**uffer **O**bject) are used to upload data to the GPU (**G**raphic **P**rocessing **U**nit, in other words your graphic-card). The data does not have to be vertices, it could be used for anything. The data can also be changed later on.
> 0 votes

---
Tags: opengl, voxels, vbo
---


# Question
Title: Removing default badlogic from desktop launcher
I'm making a game in java/libgdx. when I run the code in the desktop launcher it gives me a bunch of errors. All the errors are from the badlogic default package.

My code:

```
package com.wyvern.paperplane.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.wyvern.paperplane.PaperPlane;

public class DesktopLauncher {
    public static void main (String[] args) {
      LwjglApplicationConfiguration cfg = new
      LwjglApplicationConfiguration();
      cfg.title = "my game";
      cfg.useGL30 = true;
      cfg.width = 720;
      cfg.height = 1280;
      new LwjglApplication(new PaperPlane(), cfg);
    }
}

```

I don't understand why it gives me all the default badlogic errors when I only use my own package.

Here are some of the errors, note that i don't use any of the com.badlogic:

```
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:92)

at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:88)

at com.wyvern.paperplane.PaperPlane.create(PaperPlane.java:16)

at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:143)

at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: badlogic.jpg (Internal)

at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:136)

at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:222)

at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:137)

```

# Answer
Please go through this tutorial, published by libgdx,

https://github.com/libgdx/libgdx/wiki/A-simple-game

In above tutorial, in "Loading the assets" section, you can change/remove the image (badlogic's by default image) as per your requirement.
> -1 votes

# Answer
You need to to point your working directory to the assets folder.

Snippet from https://github.com/libgdx/libgdx/wiki/Manual-project-setup

> The Android project has a subfolder named assets, which is created automatically. Files available to the Android application must be placed here. This is problematic, because these same files must be available to the desktop application. Rather than maintain two copies of all the files, the desktop project should be configured to find the assets in the Android project:
>
> In the Properties for the core project: click the Source tab, click Link Source, Browse, select the "assets" folder from your Android project and click OK. Specify "assets" for the folder name and click Finish then OK. Note: If your desktop and Android projects are in the same parent folder, you can use "PARENT-1-PROJECT\_LOC/gamename-android/assets" for the location of the linked assets folder, where "gamename-android" is the name of your Android project. This is better than a hard-coded path if you plan on sharing your projects with others.
> 0 votes

---
Tags: java, libgdx, eclipse
---


title: To find a success list in group

text:
# Question
Title: To find a success list in group
I try to find a success list among players for my project. I thought If I find the winning probability of players , it would give me the success list in group.

I would like to give an example to explain in a score table.

* Player A won Player B 2 times in 3 matches .
* Player C won Player B 1 time in a match.
* Player C won Player A 1 time in 4 matches.

My idea to find the winning probabilities:

p(Player X)=Total Winning number of Player X / Total Match Number

Thus we can calculate individual probabilities as above.

p(A)=5/8

p(B)=1/8

p(C)=2/8

The success list shows that p(A)\>p(C)\>p(B)

If we get new player (Player D) and the new player gets a match with Player C. if Player D wins the match, we will get a new success list according to my formula above.

p(A)=5/9

p(B)=1/9

p(C)=2/9

p(D)=1/9

In last status: p(A)\>p(C)\>p(B)=p(D)

I do not feel that method is good enough because Player D won Player C but Player D is behind Player C. As a sense, I feel Player D must be more that Player C in the list.

And other disadvantages are

1. if a player do not make match so often ,it can go down in the list. For example , if Player A do not make match for a while and Other players make matches, Player A will go down in the list even if he has good winning rate among users. I feel my method does not give exact player power
2. If a player in middle of the success list makes so much match with a weak player, The middle player will get top in the list even the player is not good enough.

Please let me know your ideas and solutions . Which methods can be used to define for better success list? How did you solve that issues in your game project while preparing a success list for death matches.

Thanks

# Answer
> 1 votes
* "**Success list**" is a term you made up, don't use it. What you want to compute is some kind of **score** or **rating** of each player as an estimate of "player power".
* The difference between a score and a rating is that a score is typically expected to increase with more games played (e.g. the number of knockouts in a boxer's career), while a rating is expected to remain constant unless the player becomes stronger or weaker, and unaffected by the number of games played (e.g. batting averages of baseball players).
* Clearly you want a rating, not a score. The closest formula to what you are doing now is taking the ratio between a player's won games and a player's total games. At the beginning A is rated 5/7, B is rated 1/4, C is rated 2/5; after D beats C, D jumps on top at 1/1 and C slips to 2/6.
* The problems with this simplistic rating formula are trusting statistically small samples too much (with only 1 game played, D should be still close to a medium "newbie" rating, not at the top or at the bottom of the ladder) and neglecting the opponent's skill: winning against a stronger player should improve the rating more. Both issues are addressed, for example, in ELO scores for chess and similar systems.

---
Tags: mathematics, data-structure
---


# Question
Title: Collision response and delta-time problems
I'm working on a 2d top-down shooter game. At the time, I am trying to get the movement and collision right, but I have a few problems with this. First of all, I am making my game frame independent with delta time but that makes it harder for me to implement a collision system.

For example, I am checking collisions like this(java and libgdx):

```
public boolean collision(Rectangle collision) {
    this.setX(this.getX() + this.delta.x);
    this.AABB.x = this.getX();

    if (this.AABB.overlaps(ext))
    {
        this.setX(this.getX() - this.delta.x);

        this.AABB.x = this.getX();

        collided = true;
    }

    // The same for Y
    this.setY(this.getY() + this.delta.y);
    AABB.y = this.getY();

    if (AABB.overlaps(ext))
    {
        this.setY(this.getY() - this.delta.y);

        AABB.y = this.getY();

        collided = true;
    }

    if (collided)
        System.out.println("Collided, setting X to " + this.getX() + " and Y to " + this.getY());

    return collided;
}

```

Basically, I move the character on X, if there is a collision, I move it back to where it was before, and do the same for Y.The problem with this approach is that as the movement is frame independent, every frame delta.x and delta.y will be different, so when moving the player back to where it was before colliding will end up in different results.

```
    this.setX(this.getX() + this.delta.x); // delta.x is a little bit different every frame because of delta time.
    this.AABB.x = this.getX();

    if (this.AABB.overlaps(ext))
    {
        this.setX(this.getX() - this.delta.x); // So this will also bring me back to a different location every frame.

        this.AABB.x = this.getX();

        collided = true;

```

How can I deal with this(or is this acceptable, as it is almost invisible)?

Any help apreciated, thanks!

# Answer
> 1 votes
What you want to do is determine how much the two AABBs overlap and then move them apart based on that amount.

You already have an `overlaps` method. If you tweak that to return the amount that the AABBs overlap (on each axis) then you can just move your player back by that amount. That assumes that what you're colliding with doesn't need to be pushed back either. If that IS the case then you'll have to move both AABBs back by some ratio of the overlapping value. You can probably just get away with moving both AABBs back by half of the overlapping value but a more generic solution would be to move them back based on their speed so a faster object moves back more than a slower object.

# Answer
> 1 votes
I think if it is invisible and if it is not affecting gameplay it is acceptable. But if you want a solution you can set a flag when starting collision detection, when the flag is true don't move your objects and store how amount they should move. If a collision happens extract how much it should go back from stored value and apply the stored value then set your flag false again.

I hope you understand it and I hope you asked that too.

# Answer
> 1 votes
Use of delta is to smooth your animation or as you said "making it independent of frames".

So may be separating animation with the position calculation can solve your problem.

For example, First calculate your next position in separate method then show your animation, by adding delta to initial position to final position, without loosing the initial position. And if you detect any collision, simple traverse back or swap initial and final position, by adding delta.

It's just a logic, I have to look into your code to find out how to incorporate this in your code.

One of my favorite blog which motivated me towards game development. Here is his views on your problem, hope it will help to resolve your problem.

http://obviam.net/index.php/getting-started-in-android-game-development-with-libgdx-tutorial-part-4-collision-detection/

---
Tags: java, libgdx, collision-resolution
---


title: Amount of Data Calculated in a Game

text:
# Question
Title: Amount of Data Calculated in a Game
So... I am theorizing the development of a 2d living persistent fullsized world with simulated ecossystem, etc..., and many, many objects, but how can I handle the giant amount of data that will be calculated per instance. I mean, as the ecossystem is simulated and alive, animals would roam, plants would grow the climate would change etc... I already planned on how to implement the simulated ecossystem, but I wanted them to happen all at once, not in separated instances like World of Warcraft's dungeons or different maps. Just one entire and fullsized chunck with all the things happening on it.

Is it possible, even for an extreme low graphical game? I know of games that do something like it. Eg.: Dwarf Fortress, but what I am aiming for is way bigger than that.

EDIT: For the "AI", I was planning on do behavioral intelligent organization or BIO, something I am planning and theorizating. It would be like a giant The Sims, every object(animal, plant, etc...) would have it's needs, characteristics, possibilities and impossibilities, they need to eat so they interact with the enviroment and with other objects on their own with modified version of A\* lead by his senses(vision, audition, ect...). I know it is complicated and not polished, its because I am still studying everything and I'm more like a amateur programmer.

# Answer
> 1 votes
No. Not at least from what you're describing.

An AI that's unique to one animal that takes into account all of the variables of such a complex environment would be taxing to simulate just on it's own. Plant life would be easier, but the cost to simulate all the plants would add up fast. A continuous simulation of the entire ecosystem would be virtually impossible to achieve without faking most of it.

Essentially, you wouldn't be able to do the simulation outside of the immediate area of the player, unless you make the simulation dirt cheap. And at that point, the computing power would be so stretched out across all the parts of the world that the simulation wouldn't really even be a simulation anymore.

But instead of that, I'd recommend just not doing it. Using the computing power towards the part of the game the player is actively engaging in would be better than running some simulation in the background.

# Answer
> 0 votes
Simulating the whole world in real time on a single PC is unlikely to be possible.

What you could do, however, is split your world in several chunks (I mean chunks, not shards). You'd have to adapt your world for an agent (AI) to be able to exist in a single chunk at any given time. For instance, you could have one big island per chunk.

And then you could have one computer per chunk that manage the simulation. For that much stuff to simulate, I would suggest you use a very low frame rate, i.e. 1-2 Hz. Your game servers would be somehow all connected together, with a master server that stores data. And you'd need a way for your simulated agents to transfer from one chunk to another (like a mega teleporter bridge or something).

A thing you could do: if a player is in a chunk, set your simulation speed to a higher frame rate (4 Hz, for instance), while if no one is there reduce it to a lower frame rate (i.e. 0.5 Hz).

Of course, you'd have carefully decouple your graphics from your logic, and make it so that your graphics look smooth and not show that the logic is really slow.

---
Tags: 2d, software-engineering, memory-efficiency
---


title: Java game Inventory problem

text:
# Question
Title: Java game Inventory problem
I have a game where you walk around picking up items. They are supposed to go into the next empty slot in your inventory, but when I pick up an item all the empty inventory spots get filled with it.

How can I only have the first empty one be filled by the item that is being picked up:

Here is my code:

```
for (int i = 0; i < c.toArray().length; i++) {
  c.get(i).tick();

  for (int i1 = 0; i1 < play.items.p.toArray().length;i1++) {
    if (c.get(i).holdingid == 0) {
      // check if the player walks onto the item which means it should
      // be picked up:
      if(play.items.p.get(i1).r.intersects(play.p.r)) {
        // remove the item from the ground:
        play.items.p.get(i1).remove = true;
        // change the empty inventory spots to be filled with the item
        // that has been picked up
        c.get(i).holdingid = play.items.p.get(i1).holdingid;
      }
    }
  }
}

```

The problem is it fills all the inventory spots how can I make it only fill the first inventory spot.

# Answer
> 0 votes
It looks like you're incorrectly assuming that the item is removed from the ground immediately upon picking it up. However, it isn't, and the player keeps intersecting with the same item, picking it up multiple times. Before pickup, you should check if the item has already been put in an inventory slot:

```
  if(play.items.p.get(i1).remove != false &&
     play.items.p.get(i1).r.intersects(play.p.r))

```

---

The above should fix the problem, but I wouldn't keep going this route.

I agree with the comments & answers that the original code is structured a little strangely, in a way that is hard to articulate. It goes something like this: the items on the ground have no relationship to the number of slots you have in your inventory, so they should not be tied together.

A cleaner method would be to go through the list of items the player is intersecting with - just once, not for every inventory slot. Every time you find an item the player is intersecting with, find the first empty inventory slot. Put the item in that slot.

# Answer
> 1 votes
Make the inventory a 1D Array and just use:

```
void onpickup(Item item)
{
     for(int i = 0; i < inventory.length; i++)
         if(inventory[i]==0) //using an int array for item ids where 0 is null
         {
             inventory[i]=item.id;
             break;
         }
}

```

# Answer
> 1 votes
Assuming you have a class named Slot.

```
Public class Slot
{
    Public Item item;

    Public bool IsEmpty ()
    {
        If (item == null)
            Return true;
        Return false;
    }
}

```

Then make a method to return the next empty slot.

```
Public Slot GetEmptySlot()
{
    For (int slotIndex = 0; slotIndex < inventorySlots.Length; slotIndex++)
    {
        Slot currentSlot = inventorySlots[slotIndex];
        If (currentSlot.IsEmpty()
            Return currentSlot;
    }
    Log ("Unable to find an empty slot... Inventory is full!");
    Return null;
}

```

There are several ways to optimize this but I won't be showing you because that isn't the question.

This is just a super basic example of how to find an empty slot and it assumes you have an array of "Slot" which is used as your inventory.

You could then store the item in the current slot like so...

```
Slot emptySlot = GetEmptySlot();
If (emptySlot != null)
    emptySlot.item = pickedupItem;

```

Understand?

Note: I wrote this on my phone so it is untested and is semi c# / pseudocode.

---
Tags: java
---


# Question
Title: C++ struct doesn't align correctly to a pixel shader cbuffer
To expand from my previous question, I must add I can't correctly map my C++ structs to a corresponding `cbuffer` inside the **pixel shader**. When outputing random colors defined in the struct C++ side, it happens I get wrong results i.e. an `XMFLOAT4(0,0,0,1.0)` would give me a red color (?).

So here is a code sample :

```
__declspec(align(16)) struct SceneParams {
    bool DEAOEnabled;
    XMFLOAT4 DEAOColor;
    double DEAOPow;
    bool lightEnabled;
    XMFLOAT4 lightColor;
    XMFLOAT3 lightDirection;
    bool lightMultiply;
    double lightMultiplyFactor;
    bool ambiantLightEnabled;
    XMFLOAT4 ambiantLightColor;
    bool HSEnabled;
    int HSSpread;
    bool fogEnabled;
    XMFLOAT4 fogColor;
    double fogDistanceMax;
    bool glowEnabled;
    XMFLOAT4 glowColor;
    double glowRadius;
    XMFLOAT4 skyColor;
    bool skyBoxEnabled;
    //uniform sampler2D skyBoxTexture;
    int skyBoxScheme0; // top
    int skyBoxScheme1; // left
    int skyBoxScheme2; // front
    int skyBoxScheme3; // right
    int skyBoxScheme4; // back
    int skyBoxScheme5; // bottom
    int skyBoxRotate;
    double skyBoxRotateSpeed;
    XMFLOAT3 skyBoxRotateAround;
    bool orbitTrapsEnabled;
    int orbitTrapsId;
    XMFLOAT4 objectColor;

    SceneParams(
        bool DEAOEnabled,
        XMFLOAT4 DEAOColor,
        double DEAOPow,
        bool lightEnabled,
        XMFLOAT4 lightColor,
        XMFLOAT3 lightDirection,
        bool lightMultiply,
        double lightMultiplyFactor,
        bool ambiantLightEnabled,
        XMFLOAT4 ambiantLightColor,
        bool HSEnabled,
        int HSSpread,
        bool fogEnabled,
        XMFLOAT4 fogColor,
        double fogDistanceMax,
        bool glowEnabled,
        XMFLOAT4 glowColor,
        double glowRadius,
        XMFLOAT4 skyColor,
        bool skyBoxEnabled,
        //uniform sampler2D skyBoxTexture,
        int skyBoxScheme0, // top
        int skyBoxScheme1, // left
        int skyBoxScheme2, // front
        int skyBoxScheme3, // right
        int skyBoxScheme4, // back
        int skyBoxScheme5, // bottom
        int skyBoxRotate,
        double skyBoxRotateSpeed,
        XMFLOAT3 skyBoxRotateAround,
        bool orbitTrapsEnabled,
        int orbitTrapsId,
        XMFLOAT4 objectColor
        ) : DEAOEnabled{ DEAOEnabled }, DEAOColor{ DEAOColor }, DEAOPow{ DEAOPow }, lightEnabled{ lightEnabled }, lightColor{ lightColor }, lightDirection{ lightDirection },
        lightMultiply{ lightMultiply }, lightMultiplyFactor{ lightMultiplyFactor }, ambiantLightEnabled{ ambiantLightEnabled }, ambiantLightColor{ ambiantLightColor },
        HSEnabled{ HSEnabled }, HSSpread{ HSSpread }, fogEnabled{ fogEnabled }, fogColor{ fogColor }, fogDistanceMax{ fogDistanceMax }, glowEnabled{ glowEnabled },
        glowColor{ glowColor }, glowRadius{ glowRadius }, skyColor{ skyColor }, skyBoxEnabled{ skyBoxEnabled }, skyBoxScheme0{ skyBoxScheme0 },
        skyBoxScheme1{ skyBoxScheme1 }, skyBoxScheme2{ skyBoxScheme2 }, skyBoxScheme3{ skyBoxScheme3 }, skyBoxScheme4{ skyBoxScheme4 }, skyBoxScheme5{ skyBoxScheme5 },
        skyBoxRotate{ skyBoxRotate }, skyBoxRotateSpeed{ skyBoxRotateSpeed }, skyBoxRotateAround{ skyBoxRotateAround }, orbitTrapsEnabled{ orbitTrapsEnabled },
        orbitTrapsId{ orbitTrapsId }, objectColor{ objectColor } {}

    SceneParams() {}
};

...
// create a scene params object
...

constantBufferDesc.ByteWidth = sizeof(SceneParams);
hr = g_d3dDevice->CreateBuffer(&constantBufferDesc, nullptr, &g_d3dConstantBuffers[CB_Scene_Params]);
g_d3dDeviceContext->PSSetConstantBuffers(4, 1, &g_d3dConstantBuffers[CB_Scene_Params]);
g_d3dDeviceContext->UpdateSubresource(g_d3dConstantBuffers[CB_Scene_Params], 0, nullptr, &g_SceneParams, 0, 0);

```

With HLSL :

```
cbuffer sceneParams : register(b4) {
    bool DEAOEnabled;
    float4 DEAOColor;
    double DEAOPow;
    bool lightEnabled;
    float4 lightColor;
    float3 lightDirection;
    bool lightMultiply;
    double lightMultiplyFactor;
    bool ambiantLightEnabled;
    float4 ambiantLightColor;
    bool HSEnabled;
    int HSSpread;
    bool fogEnabled;
    float4 fogColor;
    double fogDistanceMax;
    bool glowEnabled;
    float4 glowColor;
    double glowRadius;
    float4 skyColor;
    bool skyBoxEnabled;
    //uniform sampler2D skyBoxTexture;
    int skyBoxScheme0; // top
    int skyBoxScheme1; // left
    int skyBoxScheme2; // front
    int skyBoxScheme3; // right
    int skyBoxScheme4; // back
    int skyBoxScheme5; // bottom
    int skyBoxRotate;
    double skyBoxRotateSpeed;
    float3 skyBoxRotateAround;
    bool orbitTrapsEnabled;
    int orbitTrapsId;
    float4 objectColor;
}

```

I changed my `cbuffer` `float`s to `double`s to match the C++ struct but to no avail. What's wrong with the way I did the mapping ?

---

Additionnaly, here is a byte-size dump of the struct members :

```
std::cout << sizeof(p.DEAOEnabled) << std::endl;
std::cout << sizeof(p.DEAOColor) << std::endl;
std::cout << sizeof(p.DEAOPow) << std::endl;
std::cout << sizeof(p.lightEnabled) << std::endl;
std::cout << sizeof(p.lightColor) << std::endl;
std::cout << sizeof(p.lightDirection) << std::endl;
std::cout << sizeof(p.lightMultiply) << std::endl;
std::cout << sizeof(p.lightMultiplyFactor) << std::endl;
std::cout << sizeof(p.ambiantLightEnabled) << std::endl;
std::cout << sizeof(p.ambiantLightColor) << std::endl;
std::cout << sizeof(p.HSEnabled) << std::endl;
std::cout << sizeof(p.HSSpread) << std::endl;
std::cout << sizeof(p.fogEnabled) << std::endl;
std::cout << sizeof(p.fogColor) << std::endl;
std::cout << sizeof(p.fogDistanceMax) << std::endl;
std::cout << sizeof(p.glowEnabled) << std::endl;
std::cout << sizeof(p.glowColor) << std::endl;
std::cout << sizeof(p.glowRadius) << std::endl;
std::cout << sizeof(p.skyColor) << std::endl;
std::cout << sizeof(p.skyBoxEnabled) << std::endl;
std::cout << sizeof(p.skyBoxScheme[0]) << std::endl;
std::cout << sizeof(p.skyBoxScheme[1]) << std::endl;
std::cout << sizeof(p.skyBoxScheme[2]) << std::endl;
std::cout << sizeof(p.skyBoxScheme[3]) << std::endl;
std::cout << sizeof(p.skyBoxScheme[4]) << std::endl;
std::cout << sizeof(p.skyBoxScheme[5]) << std::endl;
std::cout << sizeof(p.skyBoxRotate) << std::endl;
std::cout << sizeof(p.skyBoxRotateSpeed) << std::endl;
std::cout << sizeof(p.skyBoxRotateAround) << std::endl;
std::cout << sizeof(p.orbitTrapsEnabled) << std::endl;
std::cout << sizeof(p.orbitTrapsId) << std::endl;
std::cout << sizeof(p.objectColor) << std::endl;

```

Which outputs :

```
1
16
8
1
16
12
1
8
1
16
1
4
1
16
8
1
16
8
16
1
4
4
4
4
4
4
1
8
12
1
4
16

```

Here is the compiler layout :

```
1>      +---
1>   0  | DEAOEnabled
1>      | <alignment member> (size=3)
1>   4  | XMFLOAT4 DEAOColor
1>      | <alignment member> (size=4)
1>  24  | DEAOPow
1>  32  | lightEnabled
1>      | <alignment member> (size=3)
1>  36  | XMFLOAT4 lightColor
1>  52  | XMFLOAT3 lightDirection
1>  64  | lightMultiply
1>      | <alignment member> (size=7)
1>  72  | lightMultiplyFactor
1>  80  | ambiantLightEnabled
1>      | <alignment member> (size=3)
1>  84  | XMFLOAT4 ambiantLightColor
1>  100 | HSEnabled
1>      | <alignment member> (size=3)
1>  104 | HSSpread
1>  108 | fogEnabled
1>      | <alignment member> (size=3)
1>  112 | XMFLOAT4 fogColor
1>  128 | fogDistanceMax
1>  136 | glowEnabled
1>      | <alignment member> (size=3)
1>  140 | XMFLOAT4 glowColor
1>      | <alignment member> (size=4)
1>  160 | glowRadius
1>  168 | XMFLOAT4 skyColor
1>  184 | skyBoxEnabled
1>      | <alignment member> (size=3)
1>  188 | skyBoxScheme0
1>  192 | skyBoxScheme1
1>  196 | skyBoxScheme2
1>  200 | skyBoxScheme3
1>  204 | skyBoxScheme4
1>  208 | skyBoxScheme5
1>  212 | skyBoxRotate
1>  216 | skyBoxRotateSpeed
1>  224 | XMFLOAT3 skyBoxRotateAround
1>  236 | orbitTrapsEnabled
1>      | <alignment member> (size=3)
1>  240 | orbitTrapsId
1>  244 | XMFLOAT4 objectColor
1>      | <alignment member> (size=4)
1>      +---

```

# Answer
Non-array struct members for constant buffers in HLSL are packed on four byte offsets, as many as it can into 16-byte vectors. If a member would straddle a vector boundary, it starts a new vector.

You cannot achieve this with just an alignment and pack directive, you need to have explicit padding in your CPU-side structure to emulate the CB layout rules.

Laying your structure out by hand:

```
Legend:
[--]             4 bytes, bool/short/int/float
[------]         8 bytes, double/float2
[----------]     12 bytes, float3
[--------------] 16 bytes, float4, double2

0123456789abcdef
[--]             *- bool DEAOEnabled;
[--------------] *- XMFLOAT4 DEAOColor;
[------][--]     *- double DEAOPow;
                 \- bool lightEnabled;
[--------------] *- XMFLOAT4 lightColor;
[----------][--] *- XMFLOAT3 lightDirection;
                 \- bool lightMultiply;
[------][--]     *- double lightMultiplyFactor;
                 \- bool ambiantLightEnabled;
[--------------] *- XMFLOAT4 ambiantLightColor;
[--][--][--]     *- bool HSEnabled;
                 |- int HSSpread;
                 \- bool fogEnabled;
[--------------] *- XMFLOAT4 fogColor;
[------][--]     *- double fogDistanceMax;
                 \- bool glowEnabled;
[--------------] *- XMFLOAT4 glowColor;
[------]         *- double glowRadius;
[--------------] *- XMFLOAT4 skyColor;
[--][--][--][--] *- bool skyBoxEnabled;
                 |- int skyBoxScheme0; // top
                 |- int skyBoxScheme1; // left
                 \- int skyBoxScheme2; // front
[--][--][--][--] *- int skyBoxScheme3; // right
                 |- int skyBoxScheme4; // back
                 |- int skyBoxScheme5; // bottom
                 \- int skyBoxRotate;
[------]         *- double skyBoxRotateSpeed;
[----------][--] *- XMFLOAT3 skyBoxRotateAround;
                 \- bool orbitTrapsEnabled;
[--]             *- int orbitTrapsId;
[--------------] *- XMFLOAT4 objectColor;

```

We can see here that you have a lot of gaps in the canonical CB layout due to would-be straddling elements which you need to emulate on the CPU side.
> 5 votes

# Answer
I believe your DEAOColor crosses the 16 byte alignment boundary. Your first bool is 4 bytes so DEAOColor get's cut in two. Try switching them (and any other variable that doesn't fit within the 16 byte steps).
> 0 votes

---
Tags: directx11, hlsl, memory-efficiency, c++
---


title: Handling Input During Frame Drop?

text:
# Question
Title: Handling Input During Frame Drop?
So i was wondering how games handle input so that the input is still handled even in cases of the frame rate being really low. Assuming the input logic is in the same thread as the rendering in the main thread. If the input is handled by some popular API (SDL/SFML/etc) the code will look something like this as a simple example:

```
if(KeyIsDown(keyCode))
{
    // do stuff
}

```

If the game is lagging then the above solution won't be able to catch the input cause the code won't be reached cause it is running behind. I notice in some games though when the framerate is low some games are still able to capture input. So if pressing Esc while the game is lagging eventually the key press will be registered. Is there any implementation of how this might work?

# Answer
There are two options for receiving input, generally.

The first - and most common in general applications - is to **use the OS event queue**. This is `PeekMessage`/`WaitMessage` in Win32, or `SDL_PollEvent`/`SDL_WaitEvent` in SDL2, and so on. With this model, it doesn't matter how slow your application becomes, as the input will be put into the queue and the app will eventually see it.

The second method - common in games - is to **poll input devices** directly. This would be how `XInput` works in Win32 or `SDL_GetKeyState` in SDL2, for instance. In these APIs, you only see input in its current state, so if you don't poll frequently enough you might miss the user pressing a key or the like.

Each have advantages and disadvantages. The OS messages often don't have precise timing information nor do they support high-resolution devices or low-latency devices, but they work well enough for quite a few games. The polling methods are more difficult to use correctly but if used right are more accurate.

In either case, your application's frametime *shouldn't affect input*. Don't render or do game logic on the same thread that reads input. The game should be run in a separate thread from your main thread (the one reading OS events), which is a good idea anyway (the main thread should poll the OS queue and call the `Present` function for your graphics API and that's about it). If you're doing polling, consider offloading that to an input thread. Alternatively, just sample input more often in a frame, e.g. read the OS event queue or poll input devices more than just once per game loop.
> 3 votes

# Answer
There's a pretty simple explanation to this. When a game is lagging, it means the entire system is under stress, and as such, lagging as well (while in the game at least). So when you hit an input, the OS registers it, and sends it to the game. But if the entire system and thus the OS are lagging and behind, the input will be queued up, and then once reached, it will be executed. Usually this effect doesn't show up on small, non-extremely-graphically-intensive games until sub-5 or 10 FPS, and most prominent once under 1 FPS, because the OS and the game have so much to deal with.

So, simply, there usually is no solution to this. But in all the laggy games I have dealt with, every single one *eventually* turns up the input key I pressed. Unless of course it is a Triple-A game that once it lags enough discards buffers.

On the other hand, if you are talking about a stock game engine such as Unity, if the FPS drops below 1, and such `Update ()` and `FixedUpdate ()` are both called less than one time per second, there is nothing to do really other than hope that the OS is queuing up your inputs.

In the case of Unity, there is a way around this problem, but it requires you go outside Unity to a native library to get your input. There are some more advanced input handlers out there on the Unity Asset Store such as Rewired but that really comes down to preference.
> 3 votes

---
Tags: input
---


# Question
Title: Multiple semi-dynamic objects in one VBO
I am working on a game that uses **opengl 3**. The huge geometry is spread over a grid of about **270,000 cells**. The geometry in each cell, though not very frequently, can change independently from other cells. Usually most of these cells don't contain any geometry at all.

Until now my approach was to have **one vertex buffer object per cell**. Today i discovered that alone generating all these VBOs (without any data in them) results in almost **1GB of main memory usage**. That would be equivalent to an **overhead of around 3KB per VBO**.

As it seems this overhead can not be avoided, i first thought of generating a VBO only when the cell creates its first geometry and deleting it once the cell becomes empty again. This might work quite well, but it would still be inefficient if the geometry happens to have very few geometry in every cell.

So i searched for a different solution and read, that one approach is to **put multiple meshes in a single VBO**. The problem with that is, that the mesh of a cell may change its size and require more memory in the VBO than initially. This would require subsequent meshes in the VBO to be shifted.

Now my question is: How do i do that?

Do i have to save the mesh for every cell, so i can rewrite it into the VBO when it needs to be shifted?
Would *glMapBuffer* help me?
Also: Is there a better, completely different solution?

Thanks in advance!

# Answer
What you could do is use a pool of big VBOs, with a PoolManager.

The PoolManager would only allocate "big" VBOs, each one having the same size, for example 4/16/256MB, not sure of how much vertex data you have...

Each VBO in the PoolManager would have associated lists of "used" and "free" regions (a region is defined by an offset from VBO start and a size).

When a new object is added to a cell you would ask the PoolManager to give you a VBO + a region inside it.

Internally the PoolManager will either find an available region matching the vertex size needed for the object in an existing big VBO or will need to create a new big VBO.

You would then use glMapBuffer in order to load the object data in the region of the VBO returned by the PoolManager.

Until this point this is easy to implement ...

Things will start to get more complicated as soon as you will need to unload some objects because then you will start to get region fragmentation issues : unloading objects will create holes in the VBOs and you'll need to implement algorithms similar to what is done by memory allocators in order to fix that (those algorithms may force you to have to move/reorganize vertices inside VBOs, which is not very GPU friendly since those VBOs are at the same time used for rendering)

It is not specified in your question if you ever need to unload objects to save memory. If you can afford to only hide an object instead of unloading its vertices from its VBO region then no need to care about region fragmentation.
> 1 votes

---
Tags: opengl, vbo, memory-efficiency
---


# Question
Title: Get OnMouseDown to work with a 2D Polygon Collider
I'm having a hell of time getting a 2D polygon collider to register a mouse click. I've attached images and code to show where I'm at. I cannot get the click to work.

Ultimately, the thing I'm trying to achieve is to just set the area defined by the collider to be clickable rather than the entire image sprite.

What am I doing wrong here? Need help!

I've defined the collider:

I've setup the components for my image:

```
using UnityEngine;
using System.Collections;

public class MouseClick : MonoBehaviour
{
    void OnMouseDown()
    {
        Debug.Log ("Clicked the Collider!");
    }
}

```

# Answer
> 1 votes
As already stated you should move to physics raycasts as they allow for greater debugging with on click events.

Your problem with the raycast is mixing Unity's 2DPhysics with 3DPhysics calls.

If you want to Raycast to an object with 2D physics components you must use. Physics2D.Raycast.

The code below should help you find what is obscuring your collider. Attach to any object and use left click.

```
void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(mouseWorldPos, Vector2.zero);
        if(hit != null){
            Debug.Log("Hit Collider: " + hit.transform.name);
        }
        else {
            Debug.Log("No colliders hit from mouse click");
        }
    }
}

```

# Answer
> 0 votes
You can use a RayCast:

```
     Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
     RaycastHit hit;

     if( Physics.Raycast( ray, out hit, 100 ) )
     {
         Debug.Log( hit.transform.gameObject.name );
     }

```

# Answer
> 0 votes
Attach a button component to your image after create a script with a public function (any name) then attach your script to any game object, add this game object to the button component and call the function.

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


# Question
Title: How to lerp all members of array in Unity 5?
I've an array of gameobjects called **cards** and I have this code to run when clicking a button

```
public void mover()
{
  for (int x = 0; x < cards.Lengh; x++)
  {
    cards[x].transform.position = Vector3.Lerp(
      cards[x].transform.position,
      new Vector3( Random.Range(2.5f, 15.5f), 1.5f, Random.Range(-5.2f, -13.5f)),
      CardMoveSpeed * Time.deltaTime);
  }
}

```

But when I click on the button it moves instantly.

How can I move all of them smoothly (by using lerp)?

I read about using co-routines but I don't fully understand how to implement it in this situation.

# Answer
The 't' quantity you specify in Vector3.Lerp is likely larger than one, causing your first problem. Secondly even if you make it smaller, your cards will never reach their destination because the 't' value will never equal 1. They'll approach it quickly at first and then slow down, but never reach the end point.

You'll need to change your functions to store the end positions you want, and also how far into the current transition we are. To do this I'll create two new variables

```
float cardTransition = 0.0f;
Vector3[] cardEndPositions = new Vector3[cards.Length];

```

Then you can change your mover function then to look like this

```
public void mover(Vector3[] endPositions, float transition)
{
    for (int x = 0; x < cards.Lengh; x++)
    {
        cards[x].transform.position = Vector3.Lerp(cards[x].transform.position, endPositions[x], transition);
    }
}

```

When you want to start a transition now, you can intialize the cardEndPositions like this

```
for (int x = 0; x < cardEndPositions.Length; x++)
{
    cardEndPositions[x] = new Vector3(Random.Range(2.5f, 15.5f), 1.5f, Random.Range(-5.2f, -13.5f));
}

```

Also make sure to update the cardTransition variable in your Update loop while a transition is occuring, add a small value to it each time step similar to what you had in the original call to Vector3.Lerp()

```
Update() {
    if(cardTransition < 1)
        cardTransition += CardMoveSpeed * Time.deltaTime;
}

```

CardMoveSpeed should be much smaller than what you have it, since currently this product is greater than 1. Tune it a bit, or use the debugger to see what values would be reasonable in here.
> 4 votes

---
Tags: unity, lerp
---


title: Problem with SSAO

text:
# Question
Title: Problem with SSAO
I'm trying to implement SSAO based on this tutorial (and other). My setup:

* XNA 4.0
* Deferred
* depth = z/w

This is result:

Lines across buildings are moving when I move camera. So I'm wondering is this problem in code or in parameters?

Here is code:

```
    float3 normal_from_depth(float depth0, float2 texcoords) {

    const float2 offset1 = float2(0.0, 0.001);
    const float2 offset2 = float2(0.001, 0.0);

    float depth1 = dot(tex2D(depth, texcoords + offset1).rgb, byte_to_float);
    float depth2 = dot(tex2D(depth, texcoords + offset2).rgb, byte_to_float);

    float3 p1 = float3(offset1, depth1 - depth0);
    float3 p2 = float3(offset2, depth2 - depth0);

    float3 normal = cross(p1, p2);
    //normal.z = -normal.z;

    return normalize(normal);
}

float4 Ssao(VSIO input) : COLOR0
{
    const float total_strength = 1.0;
    const float base = 0.2;

    const float area = 0.75;
    const float falloff = 0.000001;

    const float radius = 0.002;

    const int samples = 16;
    float3 sample_sphere[samples] = {
        float3(0.5381, 0.1856, -0.4319), float3(0.1379, 0.2486, 0.4430),
        float3(0.3371, 0.5679, -0.0057), float3(-0.6999, -0.0451, -0.0019),
        float3(0.0689, -0.1598, -0.8547), float3(0.0560, 0.0069, -0.1843),
        float3(-0.0146, 0.1402, 0.0762), float3(0.0100, -0.1924, -0.0344),
        float3(-0.3577, -0.5301, -0.4358), float3(-0.3169, 0.1063, 0.0158),
        float3(0.0103, -0.5869, 0.0046), float3(-0.0897, -0.4940, 0.3287),
        float3(0.7119, -0.0154, -0.0918), float3(-0.0533, 0.0596, -0.5411),
        float3(0.0352, -0.0631, 0.5460), float3(-0.4776, 0.2847, -0.0271)
    };

    //float3 random = normalize(tex2D(noise, input.uv * 4.0).rgb);

    float depth0 = dot(tex2D(depth, input.uv).rgb, byte_to_float);

    float3 position = float3(input.uv, depth0);
    float3 normal = normal_from_depth(depth0, input.uv);

    float radius_depth = radius / depth0;
    float occlusion = 0.0;
    for (int i = 0; i < samples; i++) {

        float3 ray = radius_depth * sample_sphere[i];
        float3 hemi_ray = position + sign(dot(ray, normal)) * ray;

        float occ_depth = dot(tex2D(depth, saturate(hemi_ray.xy)).rgb, byte_to_float);
        float difference = depth0 - occ_depth;

        occlusion += step(falloff, difference) * (1.0 - smoothstep(falloff, area, difference));
    }

    float ao = 1.0 - total_strength * occlusion * (1.0 / samples);
    return float4(ao, ao, ao, 1.f);
}

```

# Answer
I guess it's something wrong with your normal buffer. Render out the normal buffer to screen and make sure it's in view space. (or world if the depth is so)
> 1 votes

---
Tags: xna, rendering, post-processing, ssao
---


# Question
Title: AC3 FlashPunk Console doesn't show anything
I am making my project using flashpunk , I knew that it has a good console gui to give feed about states of the game , however when I tried making it appear with the FP.console.enable() method it shows its dark transparent GUI but no text appears .

I though it might be something wrong with my project so I downloaded some examples and they all failed .

Here is a pic from pink example :

As you see the console displays no text while it should give feed .

# Answer
Just try clicking \` (Under esc) It will show you the console , the text , the statistics , everything but it will also pause the game (program).
> -2 votes

---
Tags: flash, actionscript-3, flash-develop
---


title: Skeletal animation in OpenGL

text:
# Question
Title: Skeletal animation in OpenGL
I'm using Assimp to do skeletal animation in my OpenGL application.

I used Blender to export this one-boned model to a COLLADA file:

The model has only one bone, called *arm bone*, that controls the arm mesh. All the other meshes are static.

I made several structures and classes that help me play animations. All the nodes are added to an std::vector of Node objects. each Node contains aiNode data and a `toRoot` matrix. The bone hierarchy is encapsulated in a Skeleton class, and the animation matrix (T * R) are updated for each bone in a class called Animation.

My Model::Draw() function is this:

```
void Model::draw()
{
    //iterate through all animation sets. if the animation is running, update the bones it affects.
    for(size_t i = 0; i < _animations.size(); i++)
        if(_animations[i].running())
            _animations[i].updateAnimationMatrices(&_skeleton);

    //calculate Bone::finalMatrix for each bone
    _skeleton.calculateFinalMatrices(_skeleton.rootBone());

    //iterate through the nodes and draw their meshes.
    for(size_t i = 0; i < _nodes.size(); i++)
    {
        _shaderProgram.setUniform("ModelMatrix", _nodes[i].toRoot());

        _nodes[i].draw();
    }
}

```

To get the "animationMatrix" for each bone (the TR matrix) I call `Animation::updateAnimationMatrices()`. Here's what it looks like:

```
void Animation::updateAnimationMatrices(Skeleton *_skeleton)
{
    double time = ((double)_timer.elapsed() / 1000.0);
    while(time >= _animation->mDuration) time -= _animation->mDuration;

    //iterate through aiNodeAnim (called channels) and update their corresponding Bone.
    for(unsigned int iChannel = 0; iChannel < _animation->mNumChannels; iChannel++)
    {
        aiNodeAnim *channel = _animation->mChannels[iChannel];
        Bone *bone = _skeleton->getBoneByName(channel->mNodeName.C_Str(), _skeleton->rootBone());

        //rotation
        glm::mat4 R = ... //calculate rotation matrix based on time

        //translation
        glm::mat4 T = ... //calculate translation matrix based on time

        //set animation matrix for the bone
        bone->animationMatrix = T * R;
        bone->needsUpdate = true;
    }
}

```

Now in order to calculate the "finalMatrix" for each bone (based on `animationMatrix`, `offsetMatrix` etc..), and upload it to the vertex shader, I call `Skeleton::calculateFinalMatrices()`.

```
void Skeleton::calculateFinalMatrices(Bone *root)
{
    if(root)
    {
        Node *node = _getNodeByName(root->name->C_Str());
        if(node == nullptr) {
            std::cout << "could not find corresponding node for bone: " << root->name->C_Str() << "\n";
            return;
        }

        if(root->needsUpdate) //update only the bones that need to be updated (their animationMatrix has been changed)
        {
            root->finalMatrix = root->animationMatrix * root->offsetMatrix;

            //upload the bone matrix to the shader. the array is defined as "uniform mat4 Bones[64];"
            {
                std::string str = "Bones[";

                char buf[4] = {0};
                _itoa_s(root->index, buf, 10);

                str += buf;
                str += "]";

                _shaderProgram->setUniform(str.c_str(), root->finalMatrix);
            }

            root->needsUpdate = false;
        }

        for(unsigned int i = 0; i < root->numChildren; i++)
            calculateFinalMatrices(root->children[i]);
    }
}

```

Here's my bone structure, if it helps.

My glsl vertex shader is pretty standard. Here it is.

And finally, here's the result I get: (ignore the model's static legs. that must be some bug in the Blender exporter).

And here's the result I **should** get: (using a 3d party software)

It looks like there's something wrong with the bone's matrix calculation, although I don't know what. Any ideas or tips?

Thanks!

# Answer
Read this through and my best guess is that there is something wrong here:

```
root->finalMatrix = root->animationMatrix * root->offsetMatrix;

```

How is offsetMatrix calculated? And what is it supposed to do (I know somekind of offset).

Would also like to see these calculations:

```
//rotation
glm::mat4 R = ... //calculate rotation matrix based on time

//translation
glm::mat4 T = ... //calculate translation matrix based on time

```

From what you have showed my guess is that **root-\>offsetMatrix** translates the arm away from origo to somewhere (maybe the position where u would like it to be). And then **root-\>animationMatrix** first takes the inverse of **root-\>offsetMatrix** and then puts the rotation you want on that.

For a quick try, see if this works:

```
root->finalMatrix =  root->offsetMatrix * root->animationMatrix * root->offsetMatrix;

```

Although this has some extra calucation atm (if it is like I think it might be), but you will quickly find out if it works.
> 2 votes

---
Tags: opengl, glsl, skeletal-animation, assimp, skinning
---


title: Linking maps in Java game

text:
# Question
Title: Linking maps in Java game
In my Java game, I've got a number of randomly-generated maps made of tiles. I'm struggling with writing the code to handle the entering/exiting of the maps.

Originally, I only had Ascend and Descend. Easy. Enter exit, arrive at entrance. Basically, I used depth-- and depth++. Start at level 1, descend to level 2. Ascend to level 1 if desired.

Now I have maps that have North, East, South, and West entrances. So when I exit North, I need to arrive at the South entrance. Similarly, when I enter East, I need to arrive at the West entrance.

I'm working on an elaboration of the Ascend/Descend --/++ system. This basically means I have to have code for:

eastEntrance sends player to westExit,

westEntrance sends player to eastExit,

northEntrance sends player to southExit,

southEntrance sends player to northExit.

westExit sends players to eastEntrance (etc for east, south, north).

This seems pretty cumbersome. What is a good way to link my maps?

I'd really appreciate any input on this.

# Answer
A simple solution would be to assign the doors IDs, where the matching pairs would share an ID, and have them send the player to the other door with the same ID.

Or, if for whatever reason you find the need to make such IDs unique, you could assign door pairs matching IDs where one is negative and one is positive but the same absolute value, and when teleporting get the door's ID and multiply it by -1 to get the ID of the destination door.
> 2 votes

---
Tags: java, game-design, maps, architecture
---