title: Armor VS Weapon types

text:
# Question
Title: Armor VS Weapon types
I have these armor types:

* LEATHER
* MAIL
* PLATE

which are, basically, light, medium and heavy, and these weapon types:

* BLADE
* PIERCE
* BLUNT

I need a sensible 3x3 table which tells what armor type is succeptible to (and, possibly, good against, though it's not necessary) which damage type. **In other words, how good the mail armour *actually* is against pikes/arrows, etc...** Any ideas?

P.S. Wikipedia search and personal gameplay experience didn't help me too much, as both are mostly concluding: the heavier, the better.

# Answer
The best way I've seen to give benefits to leather are (a) to give it increased mobility and (b) it being treated as beneficial against (certain) elemental attacks as in Might & Magic VI \- presumably the assumption is that leather has some innate organic property that works well against the elements and/or magic forms (at least for cold and electricity, this is clearly true).

Obviously, chainmail was used for good reason and often in the areas like neck, skirts, arm joints etc. - at least until far more advanced jointed armour appeared close to or during the renaissance. So for cost and amount of material used, chainmail is conceivably better than plate - the obvious exception being against crushing attacks such as dealt by maces or hammers.

I'd do something like this, though it adds factors to what you've mentioned (hope okay) for balance:

```
      Leath Chain Plate
Slash 1     2     2
Pierc 0     1     2
Blunt 0     1     2
Elemn 2     0     1
Mobil 2     1     0
-------------------
TOTAL 5     6     7  <- plate still best overall.

```
> 6 votes

# Answer
Your conclusion that "the heavier the better" is not wrong. You have to think of it in terms of an important detail of these game-design issues: trade-offs. It's generally important to make game choices have different costs, so the player can balance her/his choices depending on the gameplay she/he aims, knowing that each choice will have game-play cost (besides buying the item, of course).

So, suppose as you said, a 3x3 matrix that describes loosely the relationship between each weapon and each armor. The trade-off can be put either directly within the matrix, or left to an external element that is outside the matrix. Let's see.

**1) Trade-off inherent to the weapon/armor relationship (within the matrix)**

For example. If you think of weapon-armor relationships in which each weapon is more suited for each type of armor, your matrix is similar to the following:

```
      Leather Mail Plate
Blunt    +     -    -
Pierce   -     +    -
Blade    -     -    +

+ = strong; - = weak

```

In that, you can clearly see that Blunt is better for Leather, Piece is better for Mail and Blade is better for Plate. So in that example Blade against Leather is not as effective as Blunt against Leather. Here, the trade-off is given by the matrix, is inherent to the matrix: when you choose a weapon, you already know that you will be the better equipped against one type of enemy, but less equipped against another type. That's what typically is the case with fire/water specialization spells in RPG games

**2 ) Trade-off by an element outside the weapon/armor relationship (outside the matrix)**

However, someone could argue that in that specific example, it is not very realistic that Blade is less effective against Leather than Blunt. Blade is powerful against any of these armors. So, someone could instead think of a different type of relationship matrix for these armors and weapons:

```
      Leather Mail Plate
Blunt    +     -    -
Pierce   +     +    -
Blade    +     +    +

+ = strong; - = weak;

```

Notice that now, there is no trade-off within the matrix: Blade is the best choice because it's good against three types of armors. Pierce is the second best and Blunt is the worst because it's only good against Leather armor. So, to avoid Blade being the obvious choice ever, the trade-off is put outside the matrix, i.e. in an element that is not represented in the matrix. For instance, armor and weapon weight (and its consequences to mobility, agility, etc).

That's why armor/weapon powers vs. mobility/agility is indeed among the most common trade-offs. For example. The reason for the armor to follow the path "the heavier the better" is because while you get more protection from the better armor, they might make you slower, or diminish your ability to carry more items. Then, you trading strength per agility, or even defense per attack if in your game agility is important for attacking.

In another front, weapons can also follow the heavier-the-better rule for similar reasons. Heavier swords of course tend to do more damage in a medieval-ish setting. But they have to occupy both hand s of the character, or make she/he hit less times per minute, etc.

---

All that said for conceptual explanation as you asked, nothing prevents you from thinking of armors and weapons in different ways. If you are not happy with the second type of matrix, you can certainly aim for the first. It means, you can choose weapons and armors that are each appropriate for each case instead of relaying on external elements to create the trade-off.

So, to sum up, there is no single answer for your question. The most correct answer is: you have to choose a trade-off between what the armor or weapon gives to the player, and what it takes from the player (i.e. in terms of gameplay mechanics, besides the cost to buy). If the power vs. agility/mobility does not appeal to you, you can totally come up with another more fitting to your game depending on its characteristics.

EDIT: note that the answer was heavy edited for clarity, although the content is the same.
> 9 votes

# Answer
It's been a while since I've played, but the types of armor and damage you've listed, are pretty much exactly what **Dark Age of Camelot** uses (with some added flair). I don't think I could come up with anything better.

The following is from my memory. It's been ages since I've played, so there might be slight inconsistencies.

```
       Cloth Leather Mail  Plate
Blunt    =     =       -     +
Pierce   =     -       +     =
Blade    =     +       =     -
Magic    =     =       =     =

```

As you can see, I've added a new armor type: cloth. Let's ignore that for now.

While this looks similar to the tables the others have provided, I still think it's the best and most realistic of them all. Of course some choices are up for debate, e.g. blunt vs. plate (are you breaking the plates rather than poking around them?), but it works pretty well overall.

As for the other armor types vs. damage types you can clearly see that each and every weapon and armor has one strength (`+`), one weakness (`-`), and one neutral (`=`) counter-part. This ensures that there's never any significant (dis)advantage.

What do those modifiers mean? If some weapon is effective, it will deal 50% extra damage, while being ineffective will deal 25% less damage (50% sounds a bit extreme here).

To spice things up, armor items in DAoC give you a specific amount of armor rating per level. Leather and mail armor both grant you 100% of that value, plate provides 125%, and cloth only 50%. (Spellcasters have their own spells to double their armor rating, which makes cloth unattractive for others, while countering this disadvantage.)

But does this make plate armor the best choice again? Not necessarily. This really depends on many other factors. In DAoC you were simply forced to wear some specific armor type at most, based on your class. For example, a sorcerer could only wear cloth, while a paladin could wear any armor.

More recent games, like **The Elder Scrolls Online**, allow the player far more flexibility. To balance things out, they tie specific passive bonuses to armor pieces, based on their classification.

So rather than using the armor modifiers (50%/100%/125%) above, in your own game you could grant cloth a bonus to mana and/or spellcasting, or just magic defense. Leather could gain benefits when using endurance focused things (archery or stealth), and plate would still retain better defenses or simply more health. Chain armor could remain as a neutral choice in the middle.

Of course you could mix and match all of them, but this is really just a question of your actual game mechanic design.
> 4 votes

# Answer
What about a simple 2d array?

First define

```
int leather = 0;
int mail = 1;
int plate = 2;
int blade = 0;
int pierce = 1;
int blunt = 2;

float[][] effectiveness = new float[][] {{1.5f,1.0f,0.5f},{,,},{,,}};
//this is for blade, as blade is the first, so 1.5x effectiveness vs leather, 1.0f vs mail, 0.5f vs plate, fill in the others as needed

```

then you can just do :

```
float factor = effectiveness[blade][leather];
//blade and leather will then be replaced with your units stat.

```

and you get a factor which determines how much more or less damage you do with your weapon vs the armor type.
> 3 votes

---
Tags: game-design, combat
---


# Question
Title: In Unity, on an Android device, CaptureScreenshot writing to Phone, but persistentdatapath linking to the external card
I'm using `CaptureScreentshot()` to get an image. But when I try to access it on an Android device it's giving me: `Could not find file "/storage/emulated/0/Android/data/appname/screenshot.png"`

When I go the external storage, it's not there, but rather on the phone storage. So why is persistentdatapath accessing something different?

My code is the following: `byte[] Bytes_File = System.IO.File.ReadAllBytes(currentScreenshotPathname);` with thepathname obtained using: `currentScreenshotPathname = System.IO.Path.Combine(Application.persistentDataPath, currentScreenshotName);`

Is there anyway to make the persistenDataPath go to the phone storage rather than emulated to read the file? I've tried changing the `WriteAccess` perimission to `External`as well as `Internal` in the player settings, but it's still the same.

Edit: Here's what's happening: PersistentDataPath is /storage/emulated/0/Android/data/myapp/files/, but the screenshot is being saved to /mnt/sdcard/Android/data/myapp/files, despite the documentation saying that it should save to the PersistentDataPath.

# Answer
Why not using a custom method to take screenshots and save them wherever you want ?

I use this method in my games:

```
    private IEnumerator TakeScreenshot(string screen_path)
    {
        yield return new WaitForEndOfFrame();

        int width = Screen.width;
        int height = Screen.height;
        // Creates a new texture of the size of your screen.
        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
        // Reads every pixel displayed on the screen.
        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        tex.Apply();

        // Save the screenshot as a byte array.
        byte[] bytes = tex.EncodeToPNG();
        Destroy(tex);
        // Save the screenshot on disk.
        File.WriteAllBytes(screen_path, bytes);
        Debug.Log("Screenshot (" + screen_path + ") saved!");
    }

```

I hope it helps.
> 1 votes

---
Tags: android, unity, file, screenshot
---


# Question
Title: Unity: Apply an Image Effect on one layer only
Please consider this simple scene.

It’s composed of 3 different game objects. 1 background image + 1 static character image + 1 small part (with the pet) that is changed at runtime to perform an animation.

The Background is rendered using a dedicated camera. The character (static + anim) is rendered using another dedicated camera. Both camera are set to *Depth Only* with a different culling mask (each camera renders only its part). Note that the camera in charge of the character has a greater depth than the one in charge of the background (i.e. Character is rendered after the background).

I need to apply an image effect only on the character camera, but I can’t manage to find a way for this effect to not affect the background.

Example here with a Vortex effect on the character camera.

How would you do such a trick?

# Answer
> 7 votes
The problem is that the image effect grab the current screen after render.

Since your camera render directly to backbuffer (they only clear depth), the image effect is apply to everything.

Solution can be :

* Setup a Camera first that clear to a transparent color, with a setup RenderTarget (you can create it by script so it is the same size as your screen) and the wanted postprocess.
* Setup a Camera second that render your background, that clear to background color/skybox
* Setup a Camera third, that render nothing (culling mask set to Nothing), clear nothing and have the AlphaBlit.cs script attached to it. AlphaBlit need two info : a material that use the AlphaBlit.shader and the rendertarget to blend (you'll need to assign it by script if you created it by script in the 1st step)
* Setup a Camera fourth that render your forward character.

CAREFUL: this is a painter algorithm. Meaning everything the third camera render is rendered on top of what already there, and the fourth camera will render on top that.

I'm not sure there is a way to do better, as it would require to also distort the depth buffer, which is not possible... (not without directly rendering with a vortex effect which is more difficult)...

Of course the more optimised way to do it would be to not apply the postprocess on the 1st camera, but just make it render in a rendertarget and modify the AlphaBlit.shader to do the vortex effect as it blit that RenderTarget. But that's more complexe.

---
Tags: unity, rendering, graphic-effects
---


title: What is unit slotting?

text:
# Question
Title: What is unit slotting?
I was watching the "Devs Play" S01E05 where JP LeBreton sat down with John Romero and played through Doom, while Romero would explain some of the game/level design choices they made.

There are loads of great points that both of them juggle around, though, there is one that I cannot fully understand. Maybe that's my language barrier or something, but yeah - **Unit slotting**.

It's a short segment of the video, starting at 2m56s where Romero has a little laugh about *slotting* in modern games.

I cannot seem to grasp the concept of it. Is it that units are auto-swarming towards you and attack in somewhat of a queue? Or maybe it's that their attacks are synchronized as to not overwhelm you? Or... what the heck is slotting?

# Answer
Slotting is a technique which is used to confront the player with an overwhelming number of enemies and still give them a chance to win.

Instead of having all enemies attack at once, there is a limited number of "slots" of enemies which attack the player seriously, while the rest of the enemies keep their distance and just look threatening but do not do anything effective. In an FPS, for example, those enemies which don't have a "slot" might fire in the general direction of the player, but behave defensively while both their damage and aim is severely nerfed. But those enemies which got one of the limited "slots" will behave far more aggressively, charge the player and use far more effective attacks.

It is a very common technique which is surprisingly effective at allowing the player to fight large hordes of enemies while still not making single enemies so weak they don't pose a challenge at all.

It sounds strange, but it works surprisingly well because:

* In a stressfull situation, the player will concentrate their attention on immediate threats first (the slotted enemies which charge them) and not pay much attention to the behavior of minor threats (those mooks standing far away), so they will not even notice that the majority of the enemies behaves rather strange.
* While players are often very annoyed when games obviously cheat against them, they are often very forgiving to games cheating in their favor.
* Players like winning against seemingly impossible odds and are more likely to attribute their victory to their supposedly good skills instead of suspecting that they got help.

Remember: When designing AI for a single-player game, the goal of your AI is not to win. It is designed to lose, preferably in a way which makes the player feel good about themselves.
> 112 votes

# Answer
It's, I guess, about how the enemies run toward the player. Slotting implies that, to let the player survive and give her a chance to continue surviving, enemies coordinate themselves to not attack at the same time. So EnemyA will attack and continue attacking while EnemyB will wait his turn.

John Romero, in this video, explains that to avoid slotting but keep giving a chance to the player, in Doom ennemies are just slow. It gives the player a chance to run, avoid, and organize her strategy.
> 18 votes

---
Tags: game-design, ai, terminology
---


title: RTS combat system

text:
# Question
Title: RTS combat system
I am developing a small-scale TB/RT Strategy hybrid, not unlike the Total War series. It's in the classic medieval setting, with only melee infantry combat currently implemented for testing. Units are fighting in small squads, but the egagements are individual (for example: 1v1, 1v2, 1v4 etc, but not 2v2, 2v3, 3v5, etc) and are taking place on whats usually considered an RPG level of detail (stats, items, scripts...).

The current rules use Java, with `class Engagement implements Runnable` and its `run()` method simply alternating the attack phases of two units until one of them is incapacitated. That was usefull for ATT/DEF equation balancing, but I'm not sure how to model the following:

* unit's attack, block, parry/conterattack phases during the engagement (deciding when to block, for additional DEF - one simple loop or a separate thread?)
* multiple units engaging one unit (for, say, caster/leadership takedown), where the outnumbered unit has to choose which attacker to repel/conterattack (loop or a check within aforementioned decision thread?)

**Is real-time usually modelled as just a really quick loop, or a thread with `interrupt` and `sleep`/`wait`/`join`?**

If needed, I can add the relevant code, but I think of this as a purely design, flow-modelling problem; **simply put:** *What are the classes/interfaces* (and their traits) *I should rely on while resolving this problem*?

# Answer
> 3 votes
> Is real-time usually modelled as just a really quick loop, or a thread with interrupt and sleep / wait / join?

Good that you edited to add this since I cast my eye over this 10 hours ago, because *this* is at the core of your question. Since we're otherwise unaware of your requirements, it isn't immediately clear whether you suggested threading for any pressing purpose.

The answer should always be `a really quick loop` until you get to the point where that can no longer do the job. There is always a price paid in complexity and opacity when using threads.

To make steady progress and properly understand how things *should* work when threaded, set it up to run on a single thread first, *then, if required after standard optimisations,* go multi-threaded. This was how I got started with threading in Java; if I hadn't, it would have taken probably double the time to get things right given complexity of the base functionality (dynamic mesh construction) running in a single thread. For AI, similarly - don't complicate things more than necessary *right now*.

YAGNI \- you ain't gonna need it.

# Answer
> 2 votes
## Real Time

In addition to Arcane Engineer's answer. Real Time refers to the users experience, less than the actual state of code.

Turn based games wait for player input. Real time games constantly continue, regardless of if the player is acting or not.

How you implement it isn't important, so long as it forces the player to respond actively to game events.

That being said, avoid threads until you need them.

## Unit Engagement

The other part of your question centers around unit engagement. Essentially what you need here is AI. A quick way to start is to define the behavior you want from your units in a given situation. "Unit A is outnumbered 2 to 1, it should do this."

You may consider a system that can read the state of an engagement and tell the individual actors what they should do. It can also determine the order of actions, which may become an issue as the order of actions can vastly change the outcome of an engagement.

---
Tags: java, rpg, multithreading, strategy, realtime
---


# Question
Title: Is Google's Protocol Buffer viable for the serialisation of game data?
Simple yes it is suitable, no it is not suitable for communications between game clients and/or server clients. Also is it suitable for serialising and storing game data or is a more customisable, minimisable solution recommended.

# Answer
> 6 votes
It is suitable, though perhaps not ideal.

First, do note that ProtoBufs are no longer state of the art in its class. Consider Cap'n Proto, Fast Buffers, or Flat Buffers. I'm personally a fan of Flat Buffers these days, but I'm sure there's already something even better out there; this is hardly a "solved" problem.

For serializing game data, you have several (competing) goals and you have several different use cases. Protobufs is not ideal, but it certainly does work. Even for networking, despite your supposition; I've used it for the network packet format in a (non-realtime) MMO for instance.

## Source Format

Here we're talking about the format that content is authored in. We might also be talking about intermediate formats (e.g. the raw source may be some model editor's native format but we also need an intermediate format that the engine or asset pipeline knows how to work with).

1. Ease of debugging, though not necessarily ease of editing.
2. Easy to merge with standard merge tools and source control tools by designers or even artists.
3. Easy to transform and update as the engine evolves and the data needed to be stored in source assets changes.
4. Lots of tools to manipulate the data for scripting, testing, etc.

I honestly find XML to be the best choice for most types of data here. It's easy enough to read, merges by non-engineers are *far* better than JSON (seriously, don't use JSON, it's a horrible format for on-disk permanent data), XML's flexible enough to deal with evolving formats, and there's a buttload of common tools and libraries for working with it. XML is the hands down winner, no question, in my book.

There are some other formats that are nearly as good at XML on the first three points (YAML, Human-JSON, etc.) but they mostly all fail on the fourth point. Just stick to XML.

## Runtime Format

Here we're talking about the files loaded in by the engine at release time. For many engines, this is actually all the time, even during development: source assets in these engines must always be converted into a different runtime format.

1. Minimizing size, because disks are slow the smaller the data, the faster it loads.
2. Minimizing runtime transformation between the on-disk format and the in-memory format.
3. Safety from crashes or buffer overruns or the like if the data is retrieved automatically from the Web from untrusted sources, e.g. some types of mods in multiplayer games.
4. Avoid needing to resync all data on version updates, esp. for clients.

Much of the time, satisfying all of these requires some kind of engine-specific binary format. However, good serialized formats *do* work well here for some types of data. Item number 4 is particularly hard to solve with your own format but easy to solve with ProtoBufs or FlatBuffers or the like.

---
Tags: client-server, data-structure, databases
---


# Question
Title: How to make installable .exe file for unity games
I just completed my game but after i built the game from unity to *.exe* it also has `filename_data` folder i know it has all the resources for the game. I tried `iexpress` and `innosetup` to make the install-able file. I installed the game from the setup then i ran it but the game gives the error "There should be '`HouseFixIt_Data`' folder next to the executable", but i added data folder while making install-able file but still i'm getting this error. Please anyone help me...

# Answer
> 6 votes
This is the online tutorial I used for InnoSetup, and I can confirm it worked for me.

At the part about the DataFolder they say this:

> Point the wizard to the main executable of your game. Now we have to add the MyGame\_Data folder. Click the Add folder. A quick note about the MyGame\_Data folder. You can select it directly, then click edit and set the destination subfolder to “MyGame\_Data”. This will create the proper subdirectory once the installation is done and you will not be including any unnecessary files.

**EDIT:** As later asked by the OP in the comments, here is how to remove the Set Resolution Settings popup for a Unity game. Select Edit-\>PlayerSettings-\>Resolution and Presentation. Then select this option:

---
Tags: unity, export, installer, build-process
---


title: DX11 Losing Instance Buffer Data

text:
# Question
Title: DX11 Losing Instance Buffer Data
I've got a function that basically creates different instance buffers into an array for me to use in my `DrawIndexedInstanced` call.

But when I pass the vertex buffer and instance buffer through to my shader, my instance data is completely lost when the shader goes to use it, so none of my objects are being relocated and are thus all rendering in the same place.

I've been looking at this for hours and literally cannot find anything that is helpful.

Creating the Vertex shader input layout:

```
D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
{
    //Vertex Buffer
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },

    //Instance buffer
    { "INSTANCEPOS", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
    { "INSTANCEROT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 12, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
    { "INSTANCESCA", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 24, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
    { "INSTANCETEX", 0, DXGI_FORMAT_R32_FLOAT, 1, 36, D3D11_INPUT_PER_INSTANCE_DATA, 1 }
};

```

Creating an instance buffer (called multiple times per frame, to create all necessary buffers):

```
void GameManager::CreateInstanceBuffer(ID3D11Buffer** buffer, Mesh* mesh, std::vector<Instance> instances)
{

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

    instBuffDesc.Usage = D3D11_USAGE_DEFAULT;
    instBuffDesc.ByteWidth = sizeof(Instance) * instances.size();
    instBuffDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    instBuffDesc.CPUAccessFlags = 0;
    instBuffDesc.MiscFlags = 0;
    instBuffDesc.StructureByteStride = 0;

    int i = sizeof(Instance);

    D3D11_SUBRESOURCE_DATA instData;
    ZeroMemory(&instData, sizeof(instData));

    instData.pSysMem = &instances;
    instData.SysMemPitch = 0;
    instData.SysMemSlicePitch = 0;

    CheckFailWithError(dxManager.GetDevice()->CreateBuffer(&instBuffDesc, &instData, buffer),
        "An error occurred whilst building an instance buffer",
        "[GameManager]");

    meshBuffers.push_back(mesh->GetBuffer(VERTEX_BUFFER));
}

```

The draw command:

```
dxManager.GetContext()->DrawIndexedInstanced(instanceIndexCounts[buffer], instanceCounts[buffer], 0, 0, 0);

```

I've used the graphics debugger built into Visual Studio. Initially it appeared to be assigning variables in the Vertex shader back to front, however removing `APPEND_ALIGNED_ELEMENT` from the `AlignedByteOffset` has fixed that, however the per-instance data seems to be corrupt and is not getting recieved.

If there is anything else you need let me know and I'll update the post as necessary.

# Answer
> 0 votes
This is how I do it, vb.net and sharpDX but u should be able to port it over. I also found that I hade to put the sort the elements but there size eg.

vect4 vect3 vect2 float

```
    Dim elements As InputElement() = New InputElement() {New InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                                                              New InputElement("NORMAL", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                               New InputElement("BINORMAL", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                               New InputElement("TANGENT", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                                New InputElement("COLOR", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                                New InputElement("TEXCOORD", 0, DXGI.Format.R32G32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                                 New InputElement("WORLD", 0, DXGI.Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1),
                                                                 New InputElement("WORLD", 1, DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1),
                                                                 New InputElement("WORLD", 2, DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1),
                                                                 New InputElement("WORLD", 3, DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1)
                                                         }

```

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


# Question
Title: Passing data into a vertex shader for perspective divide
In OpenGL and GLSL, I am just learning about perspective projection and the vertex shader. However, I am a little confused about what data actually needs to be passed to the vertex shader, and what needs to be done in the shader code itself.

I have two questions:

Suppose I have a triangle defined in 3D coordinates (x,y,z). Do I need to pass a 4D vector with values (x,y,z,w), where w = z? Or do I just pass the 3D vector? The reason I ask is that I know that somewhere in the pipeline, the x and y coordinates are divided by the w component, in the perspective divide.

In the vertex shader code, do I need to manually divide the x and y components by the w component myself? Or is this taken care of automatically?

Thanks!

# Answer
# Input requirements

OpenGL doesn't care what you pass in to the vertex shader. In fact, you could even pass nothing and somehow generate the input in the vertex shader. You may want to consider leaving the W out of the input to save RAM and bandwidth. That's because you won't have to pass the 4th value for every vertex.

# The W divide

GPUs have optimizations made for dividing by W. Dividing manually is a very bad thing. You know how you can't divide a number by 0? Well what happens when the W is 0? The GPU handles this for you. Just make sure that you are passing out a vec4.

If you are receiving a vec3 as input, this is how you should set gl\_Position:

```
// Assuming "inputVector" is a vec3
gl_Position = vec4(inputVector, 1.0);

```
> 2 votes

# Answer
> Do I need to pass a 4D vector with values (x,y,z,w), where w = z?

No, you don't need to. And this would even be *wrong*, w is `1` for positions and `0` for directions. When you want to multiply the vertex with a `mat4` usually you convert it to a `vec4` on the fly with `vec4(your_position, 1.0)`.

> In the vertex shader code, do I need to manually divide the x and y components by the w component myself? Or is this taken care of automatically?

No, you can just ignore the fact that this happens. All you care is your normal coordinate system, everything else will be handled by your multiplication with your perspective matrix and by OpenGL itself.
> 1 votes

---
Tags: opengl, glsl
---


title: Will DirectCompute run this HLSL code

text:
# Question
Title: Will DirectCompute run this HLSL code
I found a sample about how to run a HLSL code with DirectCompute.

https://code.msdn.microsoft.com/windowsdesktop/DirectCompute-Basic-Win32-7d5a7408

This is the HLSL script I want to run

https://github.com/zachsaw/MPDN\_Extensions/blob/master/Extensions/RenderScripts/SuperRes/SuperResEx.hlsl

It doesn't seem the same as the BasicCompute sample. First, the main function's name is called "main" instead of "CSMain". Second, it uses data types like float2, float3 and float4 while BasicCompute uses standard data types. So, is it the same or something else?

Will DirectCompute run this script or it has to be done through other means?

# Answer
It appears there are syntax differences between HLSL for DX9 and DX11. I'm pretty such the above script was written for DX9, so it won't work as-is on DX11.

https://stackoverflow.com/questions/2853997/directx-9-hlsl-vs-directx-10-hlsl-syntax-the-same

EDIT: After doing research, HLSL is supported both in DX9 and DX11. You generally pre-compile HLSL with fxc.exe and you have to specify the language format being used (ps\_3\_0 in my case). Thus, there are various versions of the language but it's not related to the DirectX version. As for the main function's name, fxc.exe also takes the main function's name as a parameter so that's not restricted to a standard name, the function can be called whatever you want.
> 0 votes

# Answer
If you are targeting ps\_3\_0 then u are using a pixel shader not a compute shader, compute shaders can only be use from dx10 and up.

The code u linked is a pixel shader not a compute shader.

Like chuck said u can use the /gec switch but unless u need to port shaders from dx9-dx11 I would just write dx11 hlsl and forget the dx9 stuff.

The main difference is the way u sample textures in dx11 hlsl vs dx9 hlsl, just having a look at that shader u linked u will only need to change 10-15 lines of code for it work.

look at the msdn docs for directX they are a massive help.
> 0 votes

---
Tags: c++, shaders, directx11, hlsl
---


# Question
Title: Is it ok to use polymorphism as a way of "interfacing" with objects in a scene?
I'm designing a class that holds values representing a 3D scene. This includes lights, cameras, meshes, materials, etc.

The way how I'm setting it up is that each "thing" has a name. A camera has a name, a light has a name, etc. But they also have an "interface" to access the object via pointer instead of having to name it each time something needs to be changed.

For example:

```
Light *light = scene.getLight("light2");
light->setBrightness(2.0f);

```

The problems is what `Light` is. Ideally, it's "proper C++" where it's a pointer directly to the internal object. However, these classes are closely tied to how the scene class works, which makes maintainability a mess. It's seems much easier to just have private implementations that do all the dirty work and only let the user receive pointers to an interface.

What I want to do is make `Light` an interface (struct with virtual functions, no data, no non-virtual functions except empty constructor) and implement the internal details as a private class inside the scene class. While this makes it more maintainable, it comes at the cost of using polymorphism where I'm not dealing with more than one implementation.

Any thoughts or ideas are helpful.

# Answer
> 2 votes
Unless you really have a good reason for having a pure virtual interface, I wouldn't bother. Nothing to do with performance, just the fact that with the interface setup, you have one extra class declaration that needs maintaining.

If your scene objects are already encapsulated inside classes, there's no gain in having a virtual interface just to hide a couple private methods and data (which are not accessible outside the class anyways). And it doesn't make it more maintainable, makes it less, because you have two identical public interfaces that have to be kept in sync.

Now if you do need to have multiple implementations, then it is a viable approach. Assuming you'd have a `Light` as interface and then `DirectionalLight`, `PointLight`, etc as implementations, it makes sense, but while it is a single concrete impl, just use it directly.

As a side note, to make it "proper C++", consider using smart pointers or even plain references instead of raw pointers to objects.

---
Tags: opengl, c++, 3d, scene
---


# Question
Title: How to prevent tendencies to upper-left corner?
In a 2D tile-based game I'm making, I have a loop that runs through each of the tiles to check and apply values. One of the effects is intended to make a circle around itself, using a similar method. However, instead of making a circle (or a square, due to the shape of the map), it tends to smear towards the upper left corner.

In have tried running the loop in the reverse direction every other round, but oddly the effect persists.

I am wondering if there are any tips for preventing such a buildup.

edit: here's the current code of the simulation system http://pastebin.com/NsgK0SxP

# Answer
You are experiencing a distortion because you are asking tiles to the left and top of you a different question to the ones on the bottom right.

To the left and top you are asking "what's your state right now" because they were updated before you whereas you're asking tiles to the bottom right "what was your state one tick ago" because they haven't been updated yet.

This causes effects to travel very fast in the +x and +y directions but slow in the -x and -y directions. Causing your distortion.

To deal with this you have to ask all tiles "what was your state one tick ago". So you need a concept of "last tick" and "this tick" for all your tiles. You can do this many ways, the easiest is to have 2 matrices fulfilling this role. Alternatively this can be managed on the tile level with each tile having `createNextState` and `commitNextState` methods where the state is only committed after all tiles have had their new state build (and questions to neighbouring tiles are always about the **committed** state)
> 3 votes

---
Tags: c++, tilemap
---


# Question
Title: Effectively implementing a game view using java
I am writing a 2d game in java. The game mechanics are similar to the Pokémon game boy advance series e.g. fire red, ruby, diamond and so on.

I need a way to draw a huge map maybe 5000 by 5000 pixels and then load individual in game sprites to across the entirety of the map, like rendering a scene. Game sprites would be things like terrain objects, trees, rocks, bushes, also houses, castles, NPC's and so on. But i also need to implement some kind of camera view class that focuses on the player. the camera view class needs to follow the characters movements throughout the game map but it also needs to clip the rest of the map away from the user's field of view, so that the user can only see the arbitrary proximity adjacent to the player's sprite. The proximity's range could be something like 500 pixels in every direction around the player’s sprite. On top of this, i need to implement an independent resolution for the game world so that the game view will be uniform on all screen sizes and screen resolutions.

I know that this does sound like a handful and may fall under the category of multiple questions, but the questions are all related and any advice would be very much appreciated. I don’t need a full source code listing but maybe some pointers to effective java API classes that could make doing what i need to do a lot simpler. Also any algorithmic/ design advice would greatly benefit me as well.

example of what i am trying to do in source code form below

```
package myPackage;

/**
 * The Purpose of GameView is to: Render a scene using Scene class, Create a
 * clipping pane using CameraView class, and finally instantiate a coordinate
 * grid using Path class.
 *
 * Once all of these things have been done, GameView class should then be
 * instantiated and used jointly with its helper classes. CameraView should be
 * used as the main drawing image. CameraView is the the window to the game
 * world.Scene passes data constantly to CameraView so that the entire map flows
 * smoothly. Path uses the x and y coordinates from camera view to construct
 * cells for path finding algorithms.
 */

public class GameView {

    // Scene is a helper class to game view. it renders the entire map to memory
    // for the camera view.
    Scene scene;

    // Camera View is a helper class to game view. It clips the Scene into a
    // small image that follows the players coordinates.
    CameraView Camera;

    // Path is a helper class to game view. It observes and calculates the
    // coordinates of camera view and divides them into Grids/Cells for Path
    // finding.
    Path path;

    // this represents the player and has a getSprite() method that will return
    // the current frame column row combination of the passed sprite sheet.
    Sprite player;
}

```

# Answer
> 1 votes
I don't think Java will be able to deal directly with an image this size very effectively, especially if the intended target is online. I think you would do well to construct a run-time view at screen resolution from multiple tiles at precomputed multiple resolutions.

# Answer
> 0 votes
You could use an array array to set up the grid for a lot of my code I use a grid class that contains the width and height of the map and i have the tile size. Say the tile size is 50px x 50px then I would set my array array to draw accordingly. for example

```
Grid<Tiles> map = new Grid(100, 100);

```

This would set up my grid to hold "Tiles" which would be a different class I had that would have the texture I'd and possibly more info depending on the game I am making. This grid would hold 100 tiles x 100 tiles each 50 pixels making the map 5000px X 5000px.

later when I draw I would have something like this:

```
for(int r = 0; r < map.getRows(); r++)
{
    for(int c = 0; c < map.getColumns(); c++)
    {
        draw(map.get(r,c).getTextureID, r*50, c*50)
     }
}

```

This would draw the map at the row and column time the pixels to put it in the right place but if you only want to draw part of the screen it gets a little more complex and you only loop through the rows and columns drawing on your screen.

---
Tags: java, game-design, sprites, game-mechanics, rendering
---


# Question
Title: transform.Rotate needs to change axis of rotation
So I'm making a game in Unity. After many failed attemps from either being bored of the idea, or something going wrong and me giving up I think (hope) that will be the good one.

I have made a simple racing game with a track and a car. I am using transform.Translate to move it, but when I use transform.Rotate to turn it goes around the x axis. How do I change the axis it goes around? I cant find anything online.

```
            if (Input.GetAxisRaw("Horizontal") > 0.5f)
    {
        transform.Rotate(Vector3.right * Time.deltaTime * handling);
    }
    if (Input.GetAxisRaw("Horizontal") < -0.5f)
    {
        transform.Rotate(Vector3.left * Time.deltaTime * handling);
    }
    if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f)
    {
        transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime, 0f));
    }

```

Thanks for any help you can give me.

# Answer
The parameter you pass to `transform.Rotate` is a a vector with 3 elements. The 3 elements say how far to rotate around the x-axis, y-axis and z-axis. `Vector3.right` and `Vector3.left` are shorthands for `Vector3(1.0f, 0.0f, 0.0f)` and `Vector3(-1.0f, 0.0f, 0.0f)`. These are rotations around the x-axis.

When you want to turn an object around the z-axis, for example, you would use:

```
transform.Rotate(new Vector3(0.0f, 0.0f, 1.0f) * handling * Time.deltaTime);

```

which can be abbreviated as

```
transform.Rotate(Vector3.forward * handling * Time.deltaTime);

```

When you use vectors for rotation instead of translation, the names of the constants defined in Vector3 are a bit misleading. So I would recommend you to either write out all three components as in my first example, or define your own constants like this:

```
static class RotationVector {
    static readonly Vector3 rollLeft = Vector3.forward;
    static readonly Vector3 rollRight = Vector3.backward;
    static readonly Vector3 yawRight = Vector3.up;
    static readonly Vector3 yawLeft = Vector3.down;
    static readonly Vector3 pitchDown = Vector3.left;
    static readonly Vector3 pitchUp = Vector3.right;
}

```

Note: these assignments assume that in your game x-axis means "forward" and the y-axis means "up" (like the Vector3 constants assume). They are different depending on which axis represents which direction in your game (in 2d-games seen from the bird-eye perspective, many people use y as the north-south axis and z as the up-down axis).
> 5 votes

# Answer
I worked it out finally. I use forward and back as the rotation direction. I was literally just rolling through vector options to find it though. Pure luck.
> 1 votes

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


title: Get array from JSON in Libgdx?

text:
# Question
Title: Get array from JSON in Libgdx?
I wanted to load in map information using JSON, is there a way to get String, Int, float etc lists or arrays from JSON in Libgdx?

My structure looks like this

```
{
    "data": [{
        "name": "startmap",
        "actors": [{
            "name": "ryder"
        }]
    }]
}

```

And I want to get Actors as either a String List or Array, but there is no GetList or GetArray function. Is there any other way to do this?

# Answer
> 1 votes
I have found the solution. First I add a JsonValue to my map object. Then I add a String list to my map object as well. JsonValue has this handy method called Child, wich allows me to loop through every child in the JsonValue, wich I add to my list of Strings.

The code looks like this.

```
newMap.actorstorage = saveJson.get("actors");
    for (JsonValue actor = newMap.actorstorage.child; actor != null; actor = actor.next){
        for(int c = 0; c < actor.size; c++){
            newMap.actors.add(actor.getString(c));
    }
}

```

Wich returns something like this

```
[name1,name2]

```

---
Tags: libgdx, json
---


# Question
Title: Last Row of the perspective projection matrix
Could you explain to me what is the **purpose** of -1 in the last row of the gl\_projection matrix? And how it affects the perspective division step ?

# Answer
> 2 votes
It's purpose is simple, the -1 gets multiplied with the z-value of any vertex you multiply the perspective matrix with.

So w = -z

Then during the perspective division each component (x, y, z, w) get's divided by w, (x/w, y/w, z/w, w/w). So the bigger the z-value is, the bigger the values x,y,z are divided by and the closer to zero the values become. Zero being the center of the screen thus making the objects appear smaller and closer to the center.

The reason it's -1 and not 1 is because the typical convention in OpenGL is to use a right-handed coordinate system. This means that z's negative direction is inward into the screen. However OpenGL defines normalized device coordinates (NDC) to have z be positive into the screen, so we need to flip the z axis before rendering and having it be -1 is one of the side-effects. If you look at a perspective-projection matrix for DirectX it should say 1 instead as it by convention uses left-handed coordinate system.

I recommend this resource if you want to learn more: http://www.songho.ca/opengl/gl\_projectionmatrix.html

---
Tags: matrix, perspective, projection-matrix
---


# Question
Title: How can I compute delta time in a cross platform fashion in C++?
I need a way to get time for calculating the delta time.

I see that OpenGL and GLFW have methods for it, but unfortunately I can't use them since I need to make server software too.

What is the best way to get the time, without using OpenGL/GLFWs methods? Either in milliseconds or microseconds.

Note: Must be cross platform, preferably in the default c++ 11 library or a part of the boost library.

# Answer
> 3 votes
The standard library header chrono (available since C++11) provides various clock and duration types you can use to compute time intervals (in theory -- see my footnote and the comments). You probably want `steady_clock`. Your periodic update method would look something like:

```
auto currentTime = std::chrono::steady_clock::now();
auto elapsed = previousTime - currentTime;

... do stuff with elapsed time...
float elapsed_f = elapsed.count();

previousTime = currentTime;

```

(where `previousTime` is a member or some other persistent storage for the time point). The subtraction of two time points will result in a `duration` object. This site also contains a more concrete example of using the clock mechanism.

If `steady_clock` isn't fine-grained enough for you, you can look at `high_resolution_clock`. However, it's important to test if the clock that backs the high resolution clock is monotonically increasing (check the `is_steady` member function), because it's not guaranteed to be so.

Note that as discussed in the comments, `chrono` has some issues which tend to make it less than ideal for games -- some of them are due to the wording of the standard providing lots of leeway, some of them are just down to poor implementations. Even though it would not be a great answer to your *question*, using platform-specific timer mechanisms (possibly wrapped up on your own abstraction) are likely the better solution to your *problem*.

---
Tags: timer, c++
---


# Question
Title: How to change XNA coordinates directions?
**Usually XNA increases X coordinate to right and Y to down.** Like this:

But in my project i have 2D map. Drawing tile with bigger Y coodinate below OX looking strange (usually people imagines these tiles above OX).

Yeah i can just use

```
spriteBatch.Draw(Turf.Texture, new Rectangle(Turf.X*32, Turf.Y*32*-1),Color.White);

```

//32 is width and height of tile, also code simplified

But it makes a code harder and uglier. ***Don't XNA have any setting \ variable to make spritebatch counting Y to top?***

# Answer
> 1 votes
alternatively you can create your own functions to do it, like:

```
void drawSprite(Texture2D texture, Rectangle rect, Color color)
{
    spriteBatch.Draw(texture, new Rectangle(/*modifying the given rectangle*/), color);
}

```

---
Tags: xna, coordinates, axis
---


title: Libgdx: If Rectangle overlaps anything?

text:
# Question
Title: Libgdx: If Rectangle overlaps anything?
I've written a code that allows me to talk with an NPC. This works as long as there is only 1 NPC on the map. I'll explain why.

```
public void getNPCCollision(){
    for (int i = players.size() - 1; i >= 0; i--) {
        Player player = players.get(i);
        for (int j = beings.size() - 1; j >= 0; j--) {
            Being being = beings.get(j);
            if(player.getBounds().overlaps(being.getBounds())) {
                setX(oldX);
                velocity.x = 0;
                setY(oldY);
                velocity.y = 0;
            }
            else if(player.getBounds().overlaps(being.getTalkingBounds())) {
                canTalk = true;
                talkAbleBeing = being;
            }
            else{
                talkAbleBeing = null;
                canTalk = false;
            }
        }
    }
}

```

I check every update if my Player walks into an NPC's Talking Rectangle. It goes by every NPC on the map. The thing is If I'm not on NPC 1's rectangle but on NPC 2's rectangle, It'll still set canTalk to False because I'm indeed not in his rectangle.

Is there any way I can fix this issue? Please, any help appreciated.

# Answer
If I understood you correctly, instead of defining "canTalk" as a boolean, you can just define it as an integer and start by assigning it either a NULL value or a -1. Then when the player is within the square range of any of the NPC, you just assign the canTalk = NPC index (0,1,2...n where n is total number of NPCs).

Then, you set the dialogue function to run not when canTalk is equal to true, but when it is greater than -1 or different from NULL. Inside the call function, you can even use the canTalk values to define which dialogue will be displayed. For instance, if canTalk = 3, display the dialogue related to NPC 3, if canTalk = 15, display the dialogue related to NPC 15, etc.

This way you can solve your problem and also win for free an easier way to identify which dialogue to display.
> 4 votes

# Answer
If I understand you correctly...and you only want to be able to talk to one NPC at a time: once you overlap an NPC's talking rectangle, you could break away from the for loops, thus leaving the variables as they were, not allowing another NPC who is not within range to reset the variables to False. For instance:

```
else if(player.getBounds().overlaps(being.getTalkingBounds())) {
       canTalk = true;
       talkAbleBeing = being;
       // Break out of the NPC loop
       break;
}

```

I'm not entirely sure, but you should still be able to iterate through all of the players? If not you may have to break out of both of the loops. Hopefully I helped.
> 1 votes

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


title: Comparing the images

text:
# Question
Title: Comparing the images
I have a drawable, which I want to compare to. I created a drawable object with it, and when I log it with toString, I get:

```
android.graphics.drawable.BitmapDrawable@41f95548

```

I am randomly selecting a button, and I want to keep randomly selecting until the image of the image button is not `android.graphics.drawable.BitmapDrawable@41f95548` Now, I want to compare using this code:

```
do{
}while(buttonBackground = android.graphics.drawable.BitmapDrawable@41f95548 ));

```

**buttonBackground is a drawable object.**

This, for some reason, gets me an error:

How can I compare images with a code like this `android.graphics.drawable.BitmapDrawable@41f95548`. What is this code called? Thanks

# Answer
You could make it legal by saying

```
while(buttonBackground.toString().equals("android.graphics.drawable.BitmapDrawable@41f95548"))

```

That's apples-to-apples. But it probably won't be doing what you intend.

A better way will be to remember which *index* you chose, and then compare the index til you get a different one. Something like

```
int currentIndex = <something, the current button image>...

    ...
    int newIndex = rng.nextInt(4)
} while(newIndex != currentIndex);

```

(By the way, Do you mean != or ==? Are you choosing randomly til you get a different one?)

Hope that helps a little!
> 1 votes

---
Tags: java, 2d, android, game-design, textures
---


title: Can I embed a game in a PDF document?

text:
# Question
Title: Can I embed a game in a PDF document?
I was thinking that it could be cool to have an interactive game in a digital resume. For the sake of this question, and scope of this site, let's ignore whether or not this is a good idea.

Is it possible to embed a game or some sort of interactive window inside of a PDF document? This could be using any sort of language or framework. For example, having a small area of the PDF with a CAPTCHA in it.

# Answer
It's not easy to ignore whether or not this is a good idea, but I will do my best to suppress my need to facepalm and concentrate on the pure technical viability.

PDF has Javascript support to add interactive elements to a document. This could be used to implement simple games. But you can't just take a game you implemented in some other technology and embed it in the PDF file. No, not even a browser-based game you developed in Javascript. HTML-Javascript and PDF-Javascript use the same syntax, but have a completely different set of global objects and functions. You will have to use what the PDF API offers you and develop the game specifically for this purpose, and it's not an API intended for game development.

For more information, I recommend the Acrobat JavaScript Scripting Guide by Adobe.

Microsoft Office also has VBA macros which allow the same. There is also support for COM and ActiveX elements, which allows to interface with different technologies, so in some cases it might even be possible to get a game implemented in a different technology to play inside a .docx document. But any sane company would not allow to play macros from files with untrusted origin for security reasons: they allow to do some quite evil things.
> 24 votes

# Answer
You should be able to insert a flash .swf file from your computer or the internet into a PDF using adobe acrobat. The content can run on the PDF page or in a "floating window". Although there are different security settings from normal web based flash that may prevent your game from running. Here is an article on embedding flash content: https://blogs.adobe.com/pdfdevjunkie/the\_flash\_designers\_guide\_to\_a

You can also use javascript as Philipp said.
> 6 votes

---
Tags: cross-platform
---


# Question
Title: Synchronization between game logic thread and rendering thread
How does one separate game logic and rendering? I know there seem to already be questions on here asking exactly that but the answers are not satisfactory to me.

From what I understand so far the point of separating them into different threads is so that game logic can start running for the next tick immediately instead of waiting for the next vsync where rendering finally returns from the swapbuffer call its been blocking on.

But specifically what data structures are used to prevent race conditions between the game logic thread and the rendering thread. Presumably the rendering thread needs access to various variables to figure out what to draw, but game logic could be updating these same variables.

Is there a de facto standard technique for handling this problem. Maybe like copy the data needed by the rendering thread after every execution of the game logic. Whatever the solution is will the overhead of synchronization or whatever be less than just running everything single threaded?

# Answer
> 2 votes
What I have generally seen to handle logic/render thread communication is to triple buffer your data. This way the render thread has say bucket 0 it reads from. The logic thread uses bucket 1 as it's input source for the next frame and writes the frame data to bucket 2.

At sync points, the indices of what each of the three buckets mean are swapped so that the next frame's data is given to the render thread and the logic thread can continue forward.

But there isn't necessarily a reason to split rendering & logic into their respective threads. You can in fact keep the game loop serial and decoupling your render frame rate from the logic step using interpolation. To take advantage of multi-core processors using this kind of setup is where you would have a thread pool that operates on groups of tasks. These tasks can be simply things such as rather than iterate a list of objects from 0 to 100, you iterate the list in 5 buckets of 20 across 5 threads effectively increasing your performance but not over complicating the main loop.

# Answer
> 1 votes
Usually, the logic that deals with graphics rendering passes (and their schedule, and when they're gonna run, etc) is handled by a separate thread. However that thread is already implemented (up and running) by the platform you use to develop your game loop (and game).

So in order to obtain a game loop where the game logic updates independently of the graphics refresh schedule you don't need to make extra threads, you just tap into the already existing thread for said graphics updates.

This depends on what platform you're using. For example:

* if you're doing it in most Open GL related platforms (GLUT for C/C++, JOLG for Java, Android's OpenGL ES related Action) they will usually give you a method/function which is periodically called by the rendering thread, and which you can integrate into your game loop (without making the gameloop's iterations dependent on when that method is called). For GLUT using C, you do something like this:

glutDisplayFunc(myFunctionForGraphicsDrawing);

glutIdleFunc(myFunctionForUpdatingState);
* in JavaScript, you can use Web Workers since there's no multi-threading (that you can reach programmaticaly), you can also use the "requestAnimationFrame" mechanism to get notified when a new graphics rendering will be scheduled, and do your game state updates accordingly.

Basically what you want is a mixed step game loop: you have some code that updates the game state, and which is called inside the main thread of your game, and you also want to periodically tap into (or be called back by) the already existing graphics rendering thread for heads up as to when it's time to refresh the graphics.

# Answer
> 1 votes
I've been working on the same thing. The additional concern is that OpenGL (and to my knowledge, OpenAL), and a number of other hardware interfaces, are effectively state machines that do not get along well with being called by multiple threads. I don't think their behavior is even defined, and for LWJGL (possibly also JOGL) it often throws an exception.

What I ended up doing was creating a sequence of threads that implemented a specific interface, and loading them onto a control object's stack. When that object got a signal to shut down the game, it would run through each thread, call an implemented ceaseOperations() method, and wait for them to close before closing itself. Universal data that could be relevant to rendering sound, graphics, or any other data is kept in a sequence of objects that are volatile, or universally available to all threads but never kept in thread memory. There's a slight performance penalty there, but used properly, it has allowed me to flexibly assign audio to one thread, graphics to another, physics to yet another, and so forth without tying them into the traditional (and dreaded) "game loop."

So as a rule, all OpenGL calls go through the Graphics thread, all OpenAL through the Audio thread, all input through the Input thread, and all that the organizing control thread needs to worry about is thread management. Game state is held in the GameState class, which they can all take a look at as they need to. If I ever decide that, say, JOAL has gotten dated and I want to use the new edition of JavaSound instead, I just implement a different thread for Audio.

Hopefully you see what I'm saying, I have a few thousand lines on this project already. If you would like me to try and scrape together a sample, I'll see what I can do.

# Answer
> 0 votes
In Java there's the "synchronized" keyword, which locks variables you pass to it to make them threadsafe. In C++ you can achieve the same thing using Mutex. E.g.:

Java:

```
synchronized(a){
    //code using a
}

```

C++:

```
mutex a_mutex;

void f(){
    a_mutex.lock();
    //code using a
    a_mutex.unlock();
}

```

Locking variables makes sure they don't change while running the code following it, so variables don't get changed by your updating thread while you are rendering them (in fact they DO change, but from the standpoint of your rendering thread they don't). You have to watch out with the synchronized keyword in Java though, since it only makes sure the pointer to the variable/Object doesn't change. The attributes can still change without changing the pointer. To contemplate for this, you could copy the object yourself or call synchronized on all attributes of the object you don't want to change.

# Answer
> 0 votes
This is an old post but it still pops up so wanted to add my 2 cents here.

First list data that should be stored in UI/display thread vs logic thread. In UI thread you might include 3d mesh, textures, light info, and a copy of position/rotation/direction data.

In game logic thread you might need game object size in 3d, bounding primitives (sphere, cube), simplified 3d mesh data (for detailed collisions for example), all attributes affecting movement/behavior, like object velocity, turn ratio, etc., and also position/rotation/direction data.

If you compare two lists you can see that only copy of position/rotation/direction data needs to be passed from logic to UI thread. You might also need some kind of correlation id to determine which game object this data belongs to.

How you do it depends on what language you're working with. In Scala you can use Software Transactional Memory, in Java/C++ some kind of locking/synchronization. I like immutable data so I tend to return new immutable object for every update. This is a bit of memory waste but with modern computers it's not such a big deal. Still if you want to lock shared data structures you can do it. Check out Exchanger class in Java, using two or more buffers can speed things up.

Before you get into sharing data between threads work out how much data you actually need to pass. If you have a octree partitioning your 3d space, and you can see 5 game objects out of 10 objects total, even if your logic needs to update all 10 you need to redraw only the 5 you're seeing. For more reading check out this blog: http://gameprogrammingpatterns.com/game-loop.html This is not about synchronization but it does show how game logic is separated from display and what challenges you need to overcome (FPS). Hope this helps,

Mark

---
Tags: rendering, multithreading, logic, synchronization
---


# Question
Title: What should my team and I learn first 2D or 3D?
Hello I am willing to start making a game about adventuring and saving the dream land of goats from nightmares. I have a small team of people that go to the same school as I do and we are all at a variety of different levels in math and ELA. The team consists of about 10 people total and I was wondering how I should start. Is 2D really easier than 3D? One of the members know how to do 3D animation with blender or something like that and are willing to be the animation side of this. This will have been all of our first games (complicated game to be exact) that we made and are unsure we can do it in the first place. My and another bunch of the team have the basic storyline figured out and believe it will be about twice as long as The Legend of Zelda Ocarina of Time. We have about an hour all together then we are separated in classes but I have a ton of free time normally as I am done with everything fast for about another two hours. Anyways the real question is, Should we start 2D or 3D how much harder is 3D than 2D?

# Answer
It depends what engine you want to use for development. If you where to use something like MonoGame or a barebones framework then 3D would be considerably more difficulty. However if you use a game engine like Unity or Unreal Engine it will be a lot easier, quite a lot of the math is already done, and the engines make setting stuff up a lot easier.

That being said if you have never programmed or programmed games before it might be a better idea to first learn the language you will use, working with a barebones framework doing 2D related stuff first (MonoGame or something else) might give you a better understanding of how stuff works and how to implement it better. That's up to you to decide though.

So yes in a nutshell 2D is definitely easier than 3D.
> 1 votes

---
Tags: rendering
---


# Question
Title: Click counting and actions based off count
So I have a button that is the 'mine' for my incremental game. I would like to track the number of times that it is clicked and be able to do two things:

1. Have events happen say every 5 clicks.
2. display the total number of times that is has been clicked.

This is what I have so far:

```
function addstone(){
        //stone = (parseFloat(stone) + 0.1).toFixed(1);
        //stone = stone + 1;
        var count = 0;
        var totalcount = 0;
            $("input[type='button']").click(function(){
                count = count + 1;
                if(count == 5){
                    stone = stone + 1;}
                if(count == 5){
                    count = 0;
                    totalcount = totalcount + 1;}
                }
                document.getElementById("stone").innerHTML = stone;
    }

```

So what do I need to do from here. My button calls function "mine1Click" which in turn calls the different resource addition functions. so for "mine1Click" I have this:

```
function mine1Click(){
    addstone();
    addwood();
    }

function addstone(){
        //stone = (parseFloat(stone) + 0.1).toFixed(1);     TOO LARGE
        //stone = stone + 1;                                TOO MUCH STONE
        var count = 0;
        var totalcount = 0;
            $("input[type='button']").click(function(){
                count = count + 1;
                if(count == 5){
                    stone = stone + 1;}
                if(count == 5){
                    count = 0;
                    totalcount = totalcount + 1;}
                }
                document.getElementById("stone").innerHTML = stone;
    }

function addwood(){
    wood = wood + 1;
    document.getElementById("wood").innerHTML = wood;
}

//function addcopper(){                                     UNIMPLEMENTED

//}

```

How should I go about this?

# Answer
> 1 votes
**To do the two things that you need:**

1. Have events happen say every 5 clicks.

```
if(count % 5 == 0){
    // do event
}

```

`%` is the modulo operator. What this does is it returns the remainder of `count` divided by 5. Hence, every multiple of 5, the condition is fulfilled, and the event is triggered.
2. Display the total number of times that it has been clicked.

I think what you did is fine. `document.getElementById(id).innerHTML = count`

**Putting it together**

You can use a "global" variable

```
    var stoneCount = 0;

    function addStone(){
        stoneCount++;

        if(stoneCount % 5 == 0){
            // do event
        }

        document.getElementById("stone").innerHTML = stoneCount;
    }

```

or if you dont want to clutter the global namespace:

```
function createStoneCounter(){
    var count = 0;

    return function(){
        count++;

        if(count % 5 == 0){
            // do event
        }

        // display count
    }
}

$("<your selector>").click(createStoneCounter());

```

---
Tags: javascript, game-mechanics
---


title: Repeat a bit of code?

text:
# Question
Title: Repeat a bit of code?
I want to complete a task, which assigns the variable `randomButton` a value. At the end, I want to check the value of `randomButton` If it is something I don't like, I want to re do the task where I assign `randomButton` a value.

I want to do this task:

```
        int i = rng.nextInt(4); //Find random button from between 1-4
        randomButton = buttons.get(i);
        buttonBackground = randomButton.getBackground();
        Log.v(TAG, "In the do");

```

and if

```
buttonBackground.equals(R.drawable.redcircle)

```

I want to try and do the task again. How do I achieve this...?

I have tried:

```
do {
            int i = rng.nextInt(4); //Find random button from between 1-4
            randomButton = buttons.get(i);
            buttonBackground = randomButton.getBackground();
            Log.v(TAG, "In the do");
        }while(buttonBackground.equals(R.drawable.redcircle));

```

But, for some reason, the code in the do part still executes even if buttonBackground equals R.drawable.redcircle. Also, can I make buttonBackground a string so that I can log it?

By the way, `buttons` is an arraylist with different image button objects. I want to see if the background of that imagebutton (randomButton) is redcircle. If it is, I want to go through the code again. If it isn't, thats great, and I can continue.

# Answer
If I'm understanding you correctly, then this is my suggestion...

Create a function that returns a bool value. True if succeeded, false if not. Have that function run itself until it produces true. This is called a recursive function.

Ex in slight psudo-code:

```
bool foo()
{
    bool success = myfunction();
    if not success
        foo();
    return true;
}

```
> 3 votes

---
Tags: java
---


title: Unity's free look camera too far away

text:
# Question
Title: Unity's free look camera too far away
I've been making a game to learn unity and I have been using the free look cam that comes default but have encountered a problem that I don't know how to fix. Basically the camera rig isn't following the target very well, it follows really far behind the target and I have turned up the move speed, messed with other settings but no luck.

Help please!

# Answer
> 1 votes
Look at the "FreeLookCameraRig" object you put into your hierarchy.

When you expand it, you will notice that it has a child object "Pivot" which has a child object "MainCamera" in it. You can control the relative positions of these objects to each other. Just move the camera closer to the pivot.

Alternatively, you can reduce the field of view of the camera. This is equivalent to a "sniper scope" zoom.

---
Tags: unity, camera
---


title: Wrong texture position on camera move

text:
# Question
Title: Wrong texture position on camera move
When in my game i move my character, the camera follows it. I have no problem drawing this char when it is moving or moving another char when the camera is still. Now, when i move both of them, the texture position of the second character is wrong, you can see it here:

Under the hood i round the values before moving the viewport and drawing textures, and i had no problems except in this case. How can i fix this?

# Answer
> 1 votes
As it turned out, using round wasn't a good idea. I dont use round anymore, but i had some problems when using texture atlas (which was the main reason i used round). So rounding was a poor solution for my original mistake, which was solved thanks to this How to avoid texture bleeding in a texture atlas?.

---
Tags: opengl
---


# Question
Title: Unity - Random Spawned Enemy Is Not Moving
I want to make an enemy spawner with random rotation left and right in unity. Its an 2d platformer. The random rotation is working, but the enemy is not moving after it's spawned.

I put the rigidbody of the enemy in the value enemiesrb in the script EnemySpawn and gave it an .velocity = new Vector.

I have 2 scripts

> EnemyPatrol:

```
public float moveSpeed;
public bool moveRight;

public Transform wallCheck;
public float wallCheckRadius;
public LayerMask whatIsWall;
private bool hitWall;

public float lockPos = 0;

// Use this for initialization
void Start () {

}

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

    hitWall = Physics2D.OverlapCircle(wallCheck.position, wallCheckRadius, whatIsWall);

    if (hitWall)
    {
        moveRight = !moveRight;
    }

    if (moveRight)
    {
        transform.localScale = new Vector3(-1f, 1f, 1f);
        //GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
    }
    else
    {
        transform.localScale = new Vector3(1f, 1f, 1f);
        //GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
    }

```

> and EnemySpawn

```
public GameObject enemies;
private Rigidbody2D enemiesrb;

public float spawnTime;
public int maxEnemies;
public int lofr;

private int amount;

public float moveSpeed;
void Start()
{
    enemiesrb = enemies.GetComponent<Rigidbody2D>();
}

void Update()
{
    //enemies = GameObject.FindGameObjectsWithTag("Enemy");
    //amount = enemies.Length;

    if (amount != maxEnemies)
        InvokeRepeating("spawnEnemy", spawnTime , spawnTime);

}

void spawnEnemy()
{
    lofr = Mathf.Abs(Random.Range(0, 1));

    if (lofr == 1)
    {
        Instantiate(enemies , transform.position, Quaternion.Euler(1,180,1));
        enemiesrb.velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
    }
    else if(lofr == 0)
    {
        Instantiate(enemies , transform.position, Quaternion.Euler(1,1,1));
        enemiesrb.velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
    }
    CancelInvoke();
}

```

the *lofr* means left or right. it defined if it need to spawn left or right

# Answer
> 1 votes
This is a common misconception about how Instantiate() works in Unity.

Say my spawning script has an inspector property:

`public GameObject enemyPrefab;`

Then later I create an instance of the enemy and customize it somehow:

```
Instantiate(enemyPrefab);
enemyPrefab.GetComponent<SomeComponent>().DoSomething();

```

That second line there is acting on the enemy prefab - **not** the instance I just spawned.

Since you define enemiesrb in your spawning script's Start() it has this same problem - it's referring to the Rigidbody2D on the source enemy you assigned in the inspector, not the one you just spawned.

But Instantiate() returns a reference to the instance it just created, so we can use that (we just need to cast it because it returns a very generic type):

```
GameObject spawnedEnemy = (GameObject)Instantiate(enemyPrefab);
Rigidbody2D spawnedEnemyRB = spawnedEnemy.GetComponent<Rigidbody2D>();
...

```

This correctly points at the Rigidbody2D attached to the spawned instance, not the one read from the prefab in Start().

---

One last trick: if your spawning script requires enemies to have a Rigidbody, it can be helpful to specify that, so you can never accidentally assign an incompatible prefab in the Inspector and cause null reference exceptions at runtime when the script tries to use a component that isn't there.

So instead of defining our enemyPrefab as any old GameObject, we can say it must have a Rigidbody2D:

```
public Rigidbody2D enemyPrefab;

```

Now the inspector will only accept enemyPrefabs that have a Rigidbody2D, and Instantiate() will return a reference to the spawned Rigidbody2D directly:

```
Rigidbody2D spawnedEnemyRB = (Rigidbody2D)Instantiate(enemyPrefab);

```

This still spawns the whole enemy with all its nested structure and other components intact, it just signals "this is the important component - make sure to give me a valid reference to this" and saves you a GetComponent\<\>() step.

---
Tags: c#, game-design, unity
---


# Question
Title: Are weapon names or pictures copyrighted/licensed?
Will I get a copyright strike or something if I use a picture of a weapon and the name of it? (e.g. a shop where you can buy guns, AK-47 with the pic)

# Answer
> 15 votes
You most certainly can get into legal issues in the US. Weapons names are often trademarked and their appearance could be copyrighted (there is a difference between trademarking and copyrighting. See here http://newmediarights.org/guide/legal/Video\_Games\_law\_Copyright\_Trademark\_Intellectual\_Property). Recent debate about it has been growing recently, though.

EA had either paid or made agreements for the right to use real weapons in their games for years, until recently they decided to stop doing so, invoking the First Ammendment of the US Constitution. They have claimed that "We're telling a story and we have a point of view. A book doesn't pay for saying the word 'Colt,' for example". See full article about that here: http://kotaku.com/ea-wont-be-paying-for-real-guns-in-video-games-anymore-494940003

However, such decision followed after they were taken to court by a helicopter makerfor using their helicopter models without autorizathion. And regarding this process EA quickly settled an arrangement to stop the judicial struggle: http://kotaku.com/ea-ends-first-amendment-claim-to-use-real-world-helicop-1159651214 Which means, they gave up on part of their claim.

Of course that for the companies that make weapons, their use in a major game can bee sen actually as free advertisement. So instead of monetary compensation, sometimes agreements can be put in place. See: http://www.reuters.com/article/2013/05/07/videogames-guns-idUSL2N0CS2A220130507

So, as you can see, the common practice has been to need to be granted the right to use copyrighted and/or trademarked licenses for using real weapons in games. Therefore, before there are noticeable changes in the judicial interpretation about it in the future (if it ever happens at all), it is good to take precaution.

That is often said to be the reason why so many games only go for very generic names of weapons and the descriptions of their details.

*Disclaimer: I am not a lawyer and since here were are mostly programmers, most people here won't have the technical expertise for a fully detailed technical answer.*

# Answer
> 2 votes
I think they are, even if they are not because of they are trade marks (usually marked with TM), it may cause problems if you sell your game with these names in it.

Thus most games use names that reminds of original, like "fanas", instead of "famas".

***Disclaimer:*** *These informations are not legal advice or equivalent. You should ask a lawyer for a legal advice. I'm not responsible for any damage caused by this answer.*

---
Tags: copyright, licensing
---


# Question
Title: How can I get direction or link of file in computer
I want to import an `.obj` file in my Engine or open some files. To do that I write a link or direction of that file in my computer. Like this

```
file.open("../Engine/data/model.obj");

```

But I don't want to write a link every time. In most application if you want to import or open a file you click on `import` or `open` and it opens a window where you search that file in your computer and click `open`.
Here is a picture to see what I talking am about.

How it is done? How can I write a C++ program to get link of a file like here? Does Windows have an API for something like this?

# Answer
> 0 votes
You can do the following: (if I understand you correctly)

-E.g get the path of your applications root folder

```
std::string rootDir = "";

char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
std::string pathstr = std::string(buffer).substr(0,pos);
rootDir = pathstr.c_str(); // e.g = "C:\xx\Desktop\abc"

```

then use it like:

```
file.Open(path + "\\data\\Model.obj");

```

---

or, so you can do it more simplier for you:

```
File fileOpen(std::string filePath)
{
    return file.Open(path + filePath);
}

```

**EDIT**
If you need to know how to make a FileDialog, google it please.. There are soo much sources.

---
Tags: c++, windows, file
---


title: Efficient Per-Tile Lighting Technique

text:
# Question
Title: Efficient Per-Tile Lighting Technique
Quite a few of the 2D games that I have seen use per-tile lighting, where each tile has a set brightness (continuous scale of 0 to 1, for example).

One way of calculating the brightness of any one tile is to loop with all light sources and add a brightness value to the tile based on distance from the light source. However, with 100^2 tiles and 100 lights, that's a million iterations.

What's a CPU efficient method of calculating the light on each tile with multiple light sources?

Light sources that have objects in the way of tiles should also have a lesser impact but it doesn't matter if this doesn't resemble shadows.

The light sources change every few seconds.

# Answer
> 4 votes
Use a lightmap.

A lightmap is an array in memory which is as large as your map and represents the light level of each tile.

When you create/remove a light source, add/subtract its light intensity from the surrounding lightmap values. As long as no lightsources move, keep the lightmap as it is. No matter how many light sources you have, the overhead per render frame will be constant.

Moving lightsources can be represented by removing the source from the old position and recreating it at the new position.

When a lightsource is added or removed, only update the light values of the tiles within its light range. So when you create a lightsource with a 10x10 tile range on a 100x100 map, you only need to update the 100 tiles which can actually be affected by it.

Note that your lightmap must still store values which exceed the maximum light level. Otherwise you get inconsistent results when multiple lightsources affect a tile to above maximum intensity and then some of them are removed. Clamp the values when you read them, not when you write them.

---
Tags: 2d, performance, lighting
---


# Question
Title: How do I get into 3D Java game development?
I have learned how to make a 2D game in Java using Eclipse and processing but I am not sure how to do 3D game development. I have tried looking up examples of how to do this but I have not found any useful ones.

# Answer
> 1 votes
To create 3D graphics in java you will need to use LWJGL(OpenGL wrapper) or similar.

For getting started I recommend to look at these:

These helped me getting started, without even prior 2D experience, so I'm sure this will be easy.

If you don't want to make your own engine you can also take a look at jMonkeyEngine.

---
Tags: java, 3d
---


# Question
Title: How do I save which NPCs the player has talked to?
I have built a save system that saves the players name, x and y location, map and the direction they are looking at in JSON.

```
{
data: [
    {
        x: 400
        y: 424
        d: UP
        name: Ezia
        mapname: startmap
    }
]
}

```

Now I have dialogue in my game, but I want to progress in that as well. So for example you have "Guy 1" who I just talked to, he says some stuff, afterwards he says something else, different text. How can I save it so the game knows I have already talked to "Guy 1"? I need to do this for a lot of NPCs eventually, so it would be nice if I didn't do stuff like:

```
Guy1TalkedTo = 1
Guy2TalkedTo = 0
Guy3TalkedTo = 1

```

Etc.

# Answer
I am not familiar to the particular engine you are working with, but in most languages or cases you can use a 1xn matrix (i.e. a vector) where n is the total number of NPCs, that stores the 1-or-0 values, so the position within the vector is related to the NPC number.

For instance, in pseudo-code:

```
already_talked = {1,0,1...n}
//where n is the total number of NPCs

```

So the first value in the vector relates to NPC1, the second value relates to NPC2, and so on.

If you save that to a simple text file together to the other information you are saving, it would end up looking like a simple comma-separated entry inside the text file, like the following:

```
x = 400
y = 424
d = UP
name = Ezia
mapname = startmap
already_talked = 1,0,1

```

EDIT:

In reply to your further detailing given in the comments to my answer, I will add the following. If you want to save the "already talked" state for many different maps, you have three fine options.

1) just don't restart counting the NPC index every map. So, suppose in the first map you have 3 NPCs and in the second you have 4. The first NPC in the first map will be the number 1, the second will be the number 2, the third will be the number 3. Then, the first NPC in map 2 will be the number 4, the second in map two will be the number 5, the third will be the NPC number 6 and the fourth in map two will be the NPC number 7.

That way, you can still store everything only in one variable "already\_talked".

2) another option, if you want to re-start the NPCs indexing every map, is the following. It might look messier but is actually simpler to maintain, is to just use one storing variable per map. So, in pseudo-code:

```
already_talked_map1 = {1,0,1 ... n1}
already_talked_map2 = {0,1,1 ... n2}
//where n1 and n2 are, respectively, the total number of NPCs in maps 1 and 2

```

3) a last option, also if you want to re-start the NPCs indexing every map, is to use a mxn matrix instead of a vector, so the rows indicate the map index you are referring to and the columns indicate the NPC indexing you are referring to. But in that case the way of storing the matrix in an external file together with other non-matrix information (e.g. char name, x, y, d, etc) may vary depending on the language and engine you are using.

Personal suggestion: I myself usually go for the second option if I don't have hundreds of maps. If you do have hundreds of maps, go for options one or three (the first if you want simple implementation).
> 8 votes

---
Tags: libgdx, savegame
---


# Question
Title: Hierachical Z-Buffering for occlusion culling
I'm reading the Occlusion Culling section in *Real-Time Rendering 3rd Edition* and I couldn't understand how it works. Some questions:

1. How does having a "Z-pyramid" contribute? Why do we need multiple resolutions of the Z-buffer? In the book, it's displayed as follows (left side):
2. Is the Octree structure the same Octree that is used for general frustum culling and rendering? Or is it a specialized Octree made just for the occlusion culling technique?
3. A more general question: In a previous section (and also here), the Occlusion Query term is described as "rendering a simplified bounding-volume of an object and comparing it's depth results to the Z-buffer, returning the amount of pixels that are visible." What functions in OpenGL are associated with this Occlusion Query concept?
4. Is this technique the standard for open-world games occlusion culling?

# Answer
> How does having a "Z-pyramid" contribute? Why do we need multiple resolutions of the Z-buffer? In the book, it's displayed as follows (left side):

It's part of being a tree. If you have only the full resolution image, you must query each individual sample in the depth buffer to determine the maximum depth of an area.

The lower mip levels allow you to instead query a single sample to determine the depth of a 2x2 region of the next mip level.

You start by reading from the smallest mip level. If that fails, you know that every sample in the full mip level will also fail, so you have no reason to check further. If the check succeeds, you step into the next mip level and repeat.

Note that hierarchical Z buffers are a feature of the hardware on literally all GPUs you're going to care about these days. There's nothing special you have to do to use them. Though there are some things you might do that would disable that optimization (e.g. explicitly writing depth values in your fragment shader).

> Is the Octree structure the same Octree that is used for general frustum culling and rendering? Or is it a specialized Octree made just for the occlusion culling technique?

Both yes and no. It's just an octree, but there's already a ton of different approaches to building octrees. I'm not personally sure which is the best variant for this use case because of the items below.

> A more general question: In a previous section (and also here), the Occlusion Query term is described as "rendering a simplified bounding-volume of an object and comparing it's depth results to the Z-buffer, returning the amount of pixels that are visible." What functions in OpenGL are associated with this Occlusion Query concept?

OpenGL Query Objects are the native OpenGL way of performing these tests.

Again, these automatically work with the hardware's hierarchical Z buffer implementation. You setup a query object, draw your bounding volumes, then check the results of the query objects to see which volumes had any visible pixels.

> Is this technique the standard for open-world games occlusion culling?

It can be part of it, but it's traditionally been a bit less common than one might think for (counter-intuitively) performance reasons.

GPUs are complex beasts. Rendering does not happen instantly. Reading from a query object requires, naturally, that the rendering you're querying actually be done. If you're reading from a query object right after rendering, the CPU has to sit there and do nothing while it waits for the GPU.

Using the query objects efficiently requires a good deal more complication. You have to delay the checking of the query objects until well after you've rendering your simplified shapes in order to give the GPU time to complete its work. Furthermore, you want to queue up even more work on the GPU so the GPU isn't idle while you're processing the results of the query objects.

This ultimately works best with a multi-frame renderer (e.g., using the results of from N-1 or even N-3 while rendering frame N). Which, in turn, introduces some inaccuracy in the results of the queries, especially for objects that are moving quickly, so that also has to be accounted for.

Then there's the problem of GPU usage. As powerful as our GPUs are today, our graphics are that much better. The GPU is often taxed to the limit by actually rendering our scenes, even on beefier ultra-gamer rigs. That leaves very few spare GPU cycles for culling, physics, or other tasks. Conversely, most games are making very poor use of the multiple core that CPUs have available today and have quite a bit of spare CPU power lying around.

Thus, it is often a far better idea to keep all the culling on the CPU and focus on better parallelizing the renderer. Popular middleware like Umbra are used by virtually all games in order to provide extremely fast CPU-side culling of scenes (and sometimes also used for audio, AI, etc.).

Of course, now we're seeing a rise in a number of GPU-only rendering techniques where the CPU is hardly involved at all in any of the scene rendering. The GPU does all culling, draw call submission, and so on. I'm not personally enough of a graphics buff to really explain the trade-offs with those techniques nor go into the specifics of how the culling works. I do not believe those techniques can directly handle large open worlds without some heavy CPU-side help, however, if for no other reason than the inability of the GPU to initiate content streaming from disk.
> 7 votes

---
Tags: opengl, 3d, culling, occlusion
---