# Question
Title: How can story and gameplay be artfully merged?
Let me give some context. Three of my friends and I have a pretty good game idea cooking. It's based off of a prototype I made that's evolving into a cool game mechanic. The mechanic itself is a toy that's fun on its own, but we haven't designed any puzzles around it yet. We have a design document going, and we are answering a lot of questions about what's in the game.

It's become clear early on that everyone (including myself) likes the characters and the story a lot. Considering what our favorite games are, this is unsurprising. A story driven game makes sense to me. I like the emphasis that Paper Mario: The Thousand-Year-Door, Portal 2, and Tomb Raider place on story, and I imagine our game will have a similar feel (lots of dialogue, plot twists, lovable characters). These games, IMO, have very successfully merged gameplay and story, so I know it's possible to do this successfully.

However, one team member raised this point in the design doc:

> I am feeling like \[fleshing out the story\] is our biggest hurdle right now for making more design decisions - like more specific decisions about levels etc. Is this true?

I am uncertain about working on the story extensively before gameplay, and my uneasiness was reinforced when I read this question about story vs. gameplay.

## Main Question

My team and I want to design a puzzle-adventure game, such that (in the final version of the game) the puzzles and other gameplay sequences integrate with the story as naturally as possible (the gameplay should, of course, be fun on its own), while the story itself (including plot, characters, events, etc...) does not feel contrived. In light of this goal, in what order should the design of gameplay and story be carried out? And more importantly, what tasks can/should be completed in parallel (by different team members)? Is there anything we need to be wary of during development?

# Answer
> 5 votes
I can't say I've played all puzzle games in existence, let alone all games with puzzles in them. But I only remember one about whose puzzles one could say they were all always placed at the one and only appropriate point in the narrative and that they contributed immensely to it.

What I mean is that when the designers of most games insert puzzles (or rather, "specific gameplay sequences") at certain points in their story, their goal is to challenge the player. And that's it. Maybe because the story requires it at that specific point in the game, maybe because it gives the gameplay rhythm.

Take Half-Life 2, for example, and give me one example of a puzzle (you know, the physics ones) at some point in the game which couldn't have been replaced with another one, due to the story requiring that specific type of gameplay at that specific time. I know that in the latter half of the game, the puzzles require the Gravity Gun and can't be done without it, but the gameplay is pretty much the same: grab-\>put down, grab-\>throw.

The same applies to almost all games, where the aim of a given bit of gameplay is always either to give the player a gameplay bonus or to allow them to move on in the story or more rarely, as in Deus Ex: HR or LA: Noire, to reveal more about the depths of ths story.

On the other hand, in Braid, the gameplay and "story" are tightly interwoven. The first chapter is supposed to be "forgiving" and about innocence and so is the gameplay. The chapter with the ring is about finding comfort in the presence of someone dear, all the while knowing that their companionship is a burden (to someone as ambitious and driven as Tim), and the gameplay is a perfect translation of that. The same applies to the other levels and even to the epilogue.

Jon Blow himself said about his game design experience with Braid that it was like sitting in a gold mine and scooping nuggets of gameplay, examining them from all angles (or something along those lines, was it in Indie Game: The Movie?). That's the phase you're currently going through, it looks like.

So I what I would do if I were in your case, where you have a unique idea and you'd rather sit in the gold mine and scoop nuggets than write a story, is **do precisely that, do this job of scooping as many gameplay nuggets as you can**. Once you have something to say, a message to shout out, then you'll write a story with these two constraints: the message and the gameplay. They will be unrelated enough that the story can accommodate them both.

Take, for example, this painting (the medium) that depicts an old Middle-Eastern king killing his servants, horses and dogs, bringing his world down with him as he is losing a battle and his palace is assaulted (the story). It's about grandiose decadence and egotism (the message).

We could imagine lots of different works of art with the same message. For example, imagine a scene in a movie about a corporate CEO who in the end burns entire bags of bank notes in his condo as the tax administration/feds/IRS/what have you are after him.

You can always write a story that adapts to your medium and message of choice.

**Edit to answer the asker's comments:** So you have a gameplay you like as well as a story you like. You would like to develop both further, but doing so would mean having to make sacrifices on the gameplay end or on the story end when comes the time to merge it all into an actual game.

One solution could be to work on the story first and use it as a constraint for the gameplay, which would only serve as the medium for it and, in your creative process, would always come second. Another solution, the converse of the first, is possible, where you find as many variations on your gameplay as you can and then see what can be done with it it terms of storytelling, hoping that you can build your original story around these gameplay elements.

All this cranking of constraints into others looks painful.

What I'm suggesting is that you take a good look at your story and try to pinpoint exactly what makes you like it in the first place. What, in its substance, makes you want to tell it. Extract that substance, forget about the details of the story like the setting, the names of the characters, their looks, the duration of the story, forget that it's about human beings (it could be about animals!), forget all of this and look at its substance, its deeper message, somewhat like I did (or tried doing) for the *Death of Sardanapal* painting linked to above.

Then, I assure you that you will never have the slightest bit of worry regarding cranking the story and the gameplay together. **You will find the story that makes use of the gameplay to convey the message.** I personally believe that that is what matters the most. So scoop those gameplay nuggets.

By the way, this is not how Jon Blow thinks we should make games, because this disconnects the message from the gameplay. If, like him, you can create an experience that is contained within the gameplay and have the player extract the message himself from that experience, that's also extremely cool.

---
Tags: game-design
---


# Question
Title: How many times fragment shader is executed?
I have an OpenGL code, with 3 different shader programs. I have a simple question, I know fragment shaders are executed for every every fragment in the scene. But is there a way using which we can find how many fragments are there in the scene? Correct me if i am wrong, but the fragment shader is executed for each fragments, so

Number of fragments = number of times fragment shader executed?

# Answer
To answer your question let's look at how the typical OpenGL pipline works.

Vertex Shader -\> Geometry Shader (Optional) -\> Clipping -\> Rasterization -\> Pixel Shader ---------------\> Fragments Merge.

I want to stress the fact that one pixel is not necessarily one fragment, multiple fragment can be combined to make one pixel, other fragments are discarded due to depth test , stencil test, blending. A Fragment shader will be executed for those fragments even though they might merged/discarded later.

I don't know a way give you exact number of the fragments in a scene, maybe there is a tool for NVidia or ATI than can give you how many times a fragment shader is executed.

Regardless of the actual numbers it's important to understand that due to the parallel nature of the GPU fragment shaders are executed on parallel on multiple fragments, it is also more important to profile your application and understand if it is GPU bound and if the bottleneck is in the vertex or fragment stage. here is a good article from GPU gems that explains how the GPU works.
> 9 votes

# Answer
You can, with a suitably recent version of GL, use the query objects support. See glGenQueries and glBeginQuery for documentation on their use.

With this, you can use `GL_SAMPLES_PASSED` as the query type. Assuming you aren't doing anything to disable early-Z, this should get you close to what you're looking for, enough for performance measurements at the least.
> 5 votes

# Answer
A fragment shader is executed for each fragment once.One fragment is one pixel. so it depends on what are you rendering:

For example if it takes up the whole screen( like a post-process effect ) it is executed as many times as many pixels are there on your screen.( Resolution.x * Resolution.y ).

So basically it is called once for each pixel.

If you are interested for more exact numbers, you could use shader atomics to test specific cases.

Here are some links about the usage of shader atomic counters. They are basically counters that are consistent across shaders, their usage is more performance expensive tough.

link1, link2
> 2 votes

# Answer
You can use openGL atomic counter to increment a value inside your fragment shader. Here is a tutorial on opengl atomics: OpenGL Atomic Counters
> 1 votes

---
Tags: opengl, glsl, fragment-shader
---


title: Text resource not loading

text:
# Question
Title: Text resource not loading
I'm trying to load text from a .txt file into a `TextAsset` variable. The file is in the assets folder under `Texts/`. My problem is that `bindata` is returned as null.

```
string instructions;

void Start ()
{
    //LOAD TEXT ASSETS

    TextAsset bindata = Resources.Load ("Texts/Instructions") as TextAsset;
    instructions = bindata.text;
}

```

# Answer
> 1 votes
In order to load a resource through Resources.Load, the file itself must be located in a subfolder of `Asset/Resources`. Try to move it there and your command will work.

---
Tags: unity, software-engineering
---


# Question
Title: Node.js Lockstep Multiplayer Architecture
## Background

I'm using the lockstep model for a multiplayer Node.js/Socket.IO game in a client-server architecture. User input (mouse or keypress) is parsed into commands like `'attack'` and `'move'` on the client, which are sent to the server and scheduled to be executed on a certain tick. This is in contrast to sending state data to clients, which I don't wish to use due to bandwidth issues.

Each tick, the server will send the list of commands on that tick (possibly empty) to each client. The server and all clients will then process the commands and simulate that tick in **exactly the same way**. With Node.js this is actually quite simple due to possibility of code sharing between server and client. I'll just put the deterministic simulator in the /shared folder which can be run by both server and client. The server simulation is required so that there is an authoritative version of the simulation which clients cannot alter.

## Problem

Now, the game has many entity classes, like `Unit`, `Item`, `Tree` etc. Entities are created in the simulator. However, for each class, it has some methods that are shared and some that are client-specific. For instance, the `Unit` class has `addHp` method which is shared. It also has methods like `getSprite` (gets the image of the entity), `isVisible` (checks if unit can be seen by the client), `onDeathInClient` (does a bunch of stuff when it dies **only on the client** like adding announcements) and `isMyUnit` (quick function to check if the client owns the unit). Up till now, I have been piling all the client functions into the shared `Unit` class, and adding a `this.game.isServer()` check when necessary. For instance, when the unit dies, it will call `if (!this.game.isServer()) { this.onDeathInClient(); }`.

This approach has worked pretty fine so far, in terms of functionality. But as the codebase grew bigger, this style of coding seems a little strange. Firstly, the client code is clearly not shared, and yet is placed under the /shared folder. Secondly, client-specific variables for each entity are also instantiated on the server entity (like `unit.sprite`) and can run into problems when the server cannot instantiate the variable (it doesn't have `Image` class like on browsers).

So my question is, is there a better way to organize the client code, or is this a common way of doing things for lockstep multiplayer games? I can think of a possible workaround, but it does have its own problems.

## Possible workaround (with problems)

I could use Javascript mixins that are only added when in a browser. Thus, in the /shared/unit.js file in the /shared folder, I would have this code at the end:

```
if (typeof exports !== 'undefined') module.exports = Unit;
else mixin(Unit, LocalUnit);

```

Then I would have /client/localunit.js store an object `LocalUnit` of client-side methods for `Unit`.

Now, I already have a publish-subscribe system in place for events in the simulator. To remove the `this.game.isServer()` checks, I could publish entity-specific events whenever I want the client to do something. For instance, I would do `this.publish('Death')` in /shared/unit.js and do `this.subscribe('Death', this.onDeathInClient)` in /client/localunit.js. But this would make the simulator's event listeners list on the server and the client different. Now if I want to clear all subscribed events **only from the shared simulator**, I can't. Of course, it is possible to create **two** event subscription systems - one client-specific and one shared - but now the `publish()` method would have to do `if (!this.game.isServer()) { this.publishOnClient(event); }`.

All in all, the workaround off the top of my head seems pretty complicated for something as simple as separating the client and shared code. Thus, I wonder if there is an established and simpler method for better code organization, hopefully specific to Node.js games.

# Answer
> 1 votes
My advice would be to separate the rendering and interaction code from the simulation code. The simulation code is what is truly shared, whilst the rest is client only. As you say, the tricky part will be managing the links between the two.

In an RTS I built once this was done successfully via an event system. Important events were published by the simulator and these were used to update the UI etc. These included "UnitDestroyed", "ResourcesChanged", etc. Some things should not be done purely using events. For example, I used the "UnitCreated" event to build any renderers required for the new unit. The renderers stored a reference to the simulation unit so that they could update each tick.

---
Tags: architecture, client-server, node.js
---


# Question
Title: What kind of databases are usually used in an MMORPG?
Do people write their own DB for some reason?

# Answer
We did, hopefully Ben Z will give a better explanation of the reasons than I can since he was actually the original author of our database. The short version is that relational DBs are not very useful for games because they cannot efficiently store heavily structured hierarchical data, which makes up the vast majority of data an MMO needs for normal operation. We choose to build a custom object database and part of a distributed transaction processing system, which is now in production and powering our two live games.

As for if you should do the same? Probably not, at least not at first. I would still advocate avoiding SQL, but there are now many more options in the "NoSQL" world that didn't exist a few years ago.

That said, most MMOs do run on SQL (relational) databases. I know Eve runs on a SQL Server installation sitting on top of a few multi-TB RAMSANs (I will probably never in my life have as much money as those things cost).

EDIT: Hopefully he won't mind me posting this here, but this is a blog entry with some links and comments about the presentation we gave at GDC'08 about our database.
> 40 votes

# Answer
Okay this answer is more of an observation.

Full disclosure I haven't worked on MMORPG. I have worked at what was one of the top 10 most visited sites back in 2009, and I have worked at game engine company that thought they were making MMORPG tech (I don't know if shipped).

If you look at companies that have achieved massive scale (Google, Facebook, Twitter, etc., I know they are not game companies, but they are worth looking at in this space) there are two things that I think are important.

1. They started by grabbing whatever was cheap and easy to get themselves going
2. They ultimately had to roll a lot of their tech on their own. (And sometimes hardware)

A big mistake is to grab some expensive turnkey thing and expect it magically scale for you. It doesn't work that way. The key to scaling up is dealing with each new challenge appropriately. You need flexible easy to use solutions that you can move in and out easily.

So my advice to you would be if your starting out, just get what seems least headache to deal with.
> 36 votes

# Answer
Basically, there's a whole range of approaches, and I think they're chosen based more on the experiences of their developers as much as the properties of the database. At one end, many MMOs are using standard relational databases - eg. Dark Ages of Camelot used/uses (are they still going?) MySQL, FreeRealms use a modified Postgresql, etc.

Moving along the scale, you have Guild Wars: they use SQL Server, but they stick their data in there as a single BLOB. This means they get the benefits of their usual binary formats with some of the benefits that a database provides. Needless to say, you can probably see some disadvantages of this approach too, but for a company used to working with flat files, it's probably still a step up.

Then there are probably some places using the various formalised NoSQL approaches, although it's still early days yet. Farmville uses membase, which they made for the purpose, based on memcached apparently. This shares many features with the likes of MongoDB, CouchDB, etc. Again with these approaches you're typically rolling your own storage formats but get the benefits of distribution, caching, redundancy, etc.

Some are rolling their own NoSQL entirely: Cryptic said they did something similar but also said they weren't using it in production. (**EDIT**: but see comments below.)

And then you come to people who are using flat text or binary files - as I understand it the older games like Ultima Online, Everquest, etc all went down this route, and for a company with game development experience but little database experience this works well too.

Note also that you almost never get around writing your own database in some loose sense of the term - in games you'll always have bespoke data that you need to manage either in-memory or on-disk in ways that don't lend themselves to generic software. You can't do SQL queries every time you want some data so you will need to be mirroring a lot of your information in the code no matter what back end you use.
> 25 votes

# Answer
On Pirates of the Burning Sea, we stared off with MySQL (though honestly I would've preferred Postgres) and when it started falling down under load, we switched to Microsoft SQL Server. Honestly, though, I probably won't go that route again in the future. Most of the PotBS data is pre-serialized before it's persisted anyway, so a large portion of what's in the DB is nothing more than an overgrown key/value store. On top of that, to get better performance out of our persistence layer, and better control of how data was cached in memory, we ended up writing a caching server that sat in front of the database.

So Kylotan's very right, you're not going to get around rolling your own on some level. SQL relational database servers aren't designed for the way games use data. Instead of assuming relational DB servers were the end-all of databases, we really should have thought more about what benefits we were looking for before choosing a tool.

Next time around, I'd look more into things like BerkleyDB or some of the other NoSQL-style DBs.
> 11 votes

# Answer
One other thing to note is that if you have a (relatively) static data set, don't store it in a database! There's no really good reason to store your spell definitions, item definitions, maps, etc. in a database. You're rarely querying them except by name. I see a lot of people jump into game development storing these things right alongside persisted player data, and it's a totally different class of things.

You need a data store, like a filesystem, for these. Outside of development, you don't need ACID, you don't need CRUD, you don't need a database for that kind of data. Inside of development, you need a database, but you also need a VCS anyway, and your choice of VCS will make that choice of database for you.

(If you're working on a game where players can create custom spells or items or quests, well, then that data is the same sort as player data, and you do need a database again.)
> 11 votes

# Answer
I've used MongoDB (NoSQL), it's a very fast document store that can be accessed over TCP. Give it a try! It's awesome!

Writing your own DB is a daunting task. I suggest you first explore what's already out there and if you can't find any thing that matches your specific set of criteria, build your own. Oh, and don't forget to open source it. :)
> 6 votes

# Answer
MMORPGs are intensive apps and are a huge undertaking. If you are starting off with game development I strongly recommend you do something smaller.

That said you will need two squeeze top performance out of your setup. You are obviously going to need a server farm/hive. Because network communication is relatively expensive (and most MMORPGs are realtime) you might want to replicate your central database to each of your game servers (the equivalent of realtime low-latency replication in your database of choice).

If each of your servers are serving a specific segment of the game world (like WoW works); something like Distributed Partitioned Views. DPVs allow you to segment rows of your database across different servers; according to the the constraints on the columns at each server. Both MSSQL and Oracle are smart enough to only talk to the server that contains the data that falls within your WHERE or ON clause. I am not sure if any of the open source offerings have DPVs.

The net result of this all is that *it doesn't matter what DB you use*, just use one with a good name: MSSQL, Oracle, MySQL, PostgreSQL. Write your database in ANSI SQL and see which system works the best - that's the only way to find out.

The NoSQL route might also be a good idea because it's designed for high concurrency. Pranny's suggestion might do the trick.
> 5 votes

# Answer
I guess it depends pretty heavily on what kind of data you need stored, and under which form.

I think most people out there use "standard" SQL databases for "dynamic" data like player informations, be it SQL Server, MySQL, PostgreSQL.

However, "internal" data (state of the world, content, ....) can be stored under any form, and my guess would be that most company write at least partially custom databases systems for that part, suited for their specific needs.
> 0 votes

# Answer
Well, it actually depends on your application - that's the bottomline. I work, where we develop social RPGs and we use Google App Engine as a backend
> 0 votes

# Answer
This question is rather old but my Idea of how to handle it is as valid as it was asked as it is today.

If you're using a relational database you need to reduce the load on it so this idea should help.

Store all public info on a local DB on each client system as well as in the servers DB.

Store all tables with items on the client database. Instead of the client looking to the server when you mouse over that weapon for stats, the client just checks the local database for stats. The server has its own database for pulling stats when calculating and just forwards damage and health remaining to the clients.

Worst case with this idea is that everyone can see the stats to all weapons if they manage to get into the clients database. it doesn't matter though cause even if they change the values, the database values on the server are what does the calculating in the game.
> 0 votes

---
Tags: mmo, databases
---


# Question
Title: How to make Box2D bodies automatically return to a initial rotation
I have two long Box2D bodies, that can collide while moving one of them around with MouseJoint. I want them to try to hold their position and rotation.

1. Blue body is moved using MouseJoint (yellow) towards the Red body. Red body has another MouseJoint - Blue can push Red, but Red will try to return to the start point thanks to the MouseJoint - this works just fine.
2. Both bodies correctly rotate along the middle. This is still as I want. I change the MouseJoint to move the Blue away.
3. What I need is both bodies return to their initial rotation (green arrows)
4. Desired positions and rotations

Is there anything in Box2D that could do this automatically? The MouseJoint does that nicely for position. I need it in AndEngine (Java, Android) port, but any Box2D solution is fine.

EDIT: By automatically I mean having something I can add to the object "Paddle" without the need to change game loop. I want to encapsulate this functionality to the object itself. I already have an object Paddle that has its own UpdateHandler which is being called from the game loop. What would be much nicer is to attach some kind of "spring" joint to both left and right sides of the paddle that would automatically level the paddle. I will be exploring this option soon.

# Answer
One way would be to apply a correctional torque that is proportional to the offset angle and set a high angular damping on the body. Let me elaborate:

First of all, you need to store the desired angle (`targetAngle`) that you want to rotate to. Somewhere in your game update loop you should cycle through all the bodies that tend to snap back to their original rotations and run some code like this:

```
double relativeAngle = body->GetAngle()-targetAngle;
if(abs(relativeAngle) >= thresholdAngle)
{
    body->ApplyTorque(diffAngle*C);  //C is a multiplier that you can tune
}

```

The `thresholdAngle` is some small angle that you specify. If the magnitude of the `relativeAngle` is smaller than `thresholdAngle` then no torque is applied. This accounts for situations where the body angle is very close to the relative angle. If that `if` statement were not there, miniscule torques would be applied to the body for a very long time after it has visibly settled at the target angle, performing computations that don't really affect the final result.

You will also need to `SetAngularDamping` on the body to slow it down as it gets closer to `targetAngle`. Once this is set up I recommend just playing around with `C` and the `angularDamping`. If `C` is too large or if the `angularDamping` is too small you will reach your target angle very quickly but it will rotate past it (overshoot the angle). Depending on what you want, some overshoot may be acceptable. The other extreme is when the `angularDamping` is too large and `C` is too small. This will cause the body to slow down too much and it will take a very long time to reach the target angle. If you really want some control you can also play with the body's rotational intertia (which is proportional to the density). Changing the density will also change the linear response of your blocks, so be wary when doing that. There are ways of objectively determining the ideal combination of these three parameters, but unless you know your control systems pretty well and know exactly what response you want, it's probably just easier, faster, and more fun to play around until you get something that 'feels right'.

I hope this helps!
> 4 votes

# Answer
As mentioned by Randy Gaul in the comments, another way to accomplish this would be to employ a `b2RevoluteJoint` and activate the joint motor. This is a more box2d-ish solution than the one outlined in my other answer.

If you are using a joint then you may wonder, "What body do I join to?" Unfortunately, you will need to create a new body. I would recommend a small box, that is always completely enveloped by your main body. Take a look at my crappy drawing:

Here, the red dot is the joint location, the green line shows the angle of the main body, and the orange line is the angle of the dummy body (in this case a small box). The left image shows the body at the target angle, and the right image shows the body tipped away from the target angle, along with the restoring torque (yellow arrow) that will be applied.

Notice that, in order for this to work, the small box must not be allowed to rotate. Also, its mass should be very small, so as to minimize its effect on the main body.

The box2d User Manual addresses your issue specifically:

> You can also use joint motors to track a desired joint angle. For example:

```
... Game Loop Begin ...

float32 angleError = myJoint->GetJointAngle() - angleTarget;

float32 gain = 0.1f;

myJoint->SetMotorSpeed(-gain * angleError);

... Game Loop End ...

```

> Generally your gain parameter should not be too large. Otherwise your joint may become unstable.

You can also set the `maxMotorTorque` at every step if you so desire. Now you still have some parameters to play with: `gain`,`maxMotorTorque`, and the mass of your body.

The advantage of this solution over my other answer is that it leaves you free to choose the `angularDamping` of the body. If you set a non-zero `angularDamping` it will still affect how it snaps back, but if you want to disable this behavior at any point during the game, you can just destroy the dummy body (which will destroy the joint by extension), and your main body won't be affected.

On the flip side, box2d needs to store and update an extra dummy body and joint for every 'snappable' body you create.
> 2 votes

# Answer
The complete answer to make this fully automatic FOR ONE BODY is a combination of efforts of Byte56, NauticalMile and me. You will need:

1. Your main body (paddle)
2. 5 static bodies with no fixture.
3. 4 "soft" distance joints with frequency \> 0 and damping ratio \> 0
4. 1 "hard" distance joint

This is how to position the items:

The "hard" distance joint holds the paddle in place, it is like it's axis. The paddle can rotate along it, but can't move from it.

The four "soft" distance joints are springs (or bungy ropes...) that make the paddle go back to initial position. If you need to move the paddle, you have to move all six bodies. It works exactly as I wanted for one body. **But it doesn't work when two paddles collide,** because the paddles are fixed in place. I am still working on it, but maybe somebody will be inspired.

Simulation created in RUBE.
> 1 votes

---
Tags: android, box2d, andengine
---


# Question
Title: Making more complicated systems(entity-component-system model question)
I'm using a model where entities are collections of components and components are just data. All the logic goes into systems which operate on components. Making basic systems(for Rendering and handling collision) was easy. But how do I do more compilcated systems? For example, in a CollisionSystem I can check if entity A collides with entity B. I have this code in CollisionSystem for checking if B damages A:

```
if(collides(a, b)) {
HealthComponent* hc = a->get<HealthComponent();
hc.reduceHealth(b->get<DamageComponent>()->getDamage());

```

But I feel that this code shouldn't belong to Collision system. Where should code like this be and which additional systems should I create to make this code generic?

# Answer
Messaging is a common way of handling this. So your health system would subscribe to messages about collision, combat, etc. Then the health system is the only place where health is modified.

Messaging also allows multiple systems to subscribe to the same events. For example, when a collision happens the health system can be notified, sound system and the user notification system. Lots of options and it keeps code localized to the systems where it belongs.

See this question for some details about such systems.
> 2 votes

---
Tags: component-based, entity
---


# Question
Title: Implementing algorithms via compute shaders vs. pipeline shaders
With the availability of compute shaders for both DirectX and OpenGL it's now possible to implement many algorithms without going through the rasterization pipeline and instead use general purpose computing on the GPU to solve the problem.

For some algorithms this seems to become the intuitive canonical solution because they're inherently not rasterization based, and rasterization-based shaders seemed to be a workaround to harness GPU power (simple example: creating a noise texture. No quad needs to be rasterized here).

Given an algorithm that can be implemented both ways, are there general (potential) performance benefits over using compute shaders vs. going the normal route? Are there drawbacks that we should watch out for (for example, is there some kind of unusual overhead to switching from/to compute shaders at runtime)?

Are there perhaps other benefits or drawbacks to consider when choosing between the two?

# Answer
There is no right answer if you are going to directly benefit from the compute shadrs/ GPGPU appraoch, this is highly dependent on the type of algorithm you are implementing, compute shaders and CUDA/OpenCL are a more generalized approach to overcome some of the limitations of that old shading languages hack. the most important benefits you will get:

* **Accessing spatial info.** in the old GLSL hack (well, it was a hack!) only gives little info about neighbor fragments since it uses texture coordinates. In compute shaders/CUDA/OpenCL accessing spatial info is much more flexible, you are now able implement algorithms like Histogram equalization on the GPU with un-ordered texture/buffer access.
* Gives you thread **synchronization and atomics**.
* **Compute Space:** the old GLSL hack will hard-wire the vertex/fragment compute space to your shader. Fragment shader will run with the number of fragments, vertex shader will run with the number of vertices. In compute shader you define your own space.
* **Scalability**: your compute shader/CUDA/OpenCL can scale up to the number of GPU SMs ( Streaming Multiprocessor) available unlike your old GLSL shader that should be executed on the same SM. (Based on Nathan Reed comments he says that's not true, and shaders should scale up as good as compute shaders should. I am still not sure though I need to check the documentation).
* **Context switching**: There should be some context switching, but I would say that depends on the application so your best bet is to profile your application.

Well in *my opinion*, if you want to go the compute shaders route, even though certain algorithms may be more suitable, there are certain considerations you need to take into account:

1. **Hardware and backward compatibility**. Compute shaders are only available in newer hardware and if you are going for a commercial product (e.g. game) you need to expect that a lot of users may not be able to run your product.
2. You usually **need extra knowledge in GPU/CPU architecture**, parallel programming and multithreading(e.g. memory sharing, memory coherency, thread synchronization, atomics and it's effect on performance) that you ***usually*** don't need using *normal* shaders rounte.
3. **Learning resources**, from experience there are far less learning resource for Compute shadrs, OpenCL and CUDA (which also offer OpenGL interoperability) than the usual shaders route.
4. **Debugging tools**, with the lack of proper debugging, tools development can become much harder than most shaders, at least shaders can be debugged visually.
5. I expect compute shaders to give better performance than the same algorithm in other shaders; if they were done *right* taking into consideration things from point 2, since they were designed to avoid the extra steps for graphics rendering. *But I don't have any concrete evidence to support my claim.*
6. You should also consider CUUDA/OpenCL for GPGPU if you are going that route.

Never the less I am sure it's great for the future, and will be great learning experience. Good Luck!
> 7 votes

---
Tags: performance, gpgpu
---


# Question
Title: How to get all keys and values of the PlayerPrefs in Unity?
I'm storing player name and scores in the Unity PlayerPrefs. I'd like to list all the names and scores stored in PlayerPrefs and display a high score page:

Is it possible to display all the keys values previously stored in the PlayerPrefs? Or can someone provide me by a JavaScript to do this?

# Answer
It is not possible to get the names of the PlayerPrefs keys at runtime. Instead you could opt for serializing your highscore table, and adding it as a string value to a fixed key in PlayerPrefs.

This is untested C#, but you'll figure it out:

```
// Load highscores.
string highscoresSerialized = PlayerPrefs.GetString("highscores", "");
Dictionary<string,int> highscores = MyUnserialize(highscoresSerialized);

// Update highscores.
highscores["Xavier"] = 100;

// Show highscores.
foreach ( var entry in highscores )
{
    print(entry.Key + ": " + entry.Value);
}

// Save highscores.
string highscoresSerializedAgain = MySerialize(highscores);
PlayerPrefs.SetString("highscores", highscoresSerializedAgain);
PlayerPrefs.Save();

```

`MySerialize` is a function that should turn a `Dictionary<string,int>` into a string (e.g., `"Scott:100;Henry:200;Jean:150"`) and `MyUnserialize` should perform the reverse operation.
> 5 votes

---
Tags: unity, unityscript
---


# Question
Title: Error in destroying object in Box2D/LibGDX
I'm trying to delete an object when a collision happens. I have put the following code in the render method of the object so it would be outside of the physics calculations.

```
public void render(SpriteBatch spriteBatch) {
    // some other code...
    body.setActive(false);
    body.getWorld().destroyBody(body);

```

But I'm getting an run-time error which crashes the JVM and shows,

> AL lib: alc\_cleanup: 1 device not closed
>
> Assertion failed!
>
> Program: C:\Program Files\Java\jre6\bin\javaw.exe File: /var/lib/hudson/jobs/libgdx-git/workspace/gdx/jni/Box2D/Dynamics/b2World.cpp, Line 133
>
> Expression: m\_bodyCount \> 0

Can anyone help me here?

# Answer
> 1 votes
I was having the same problem. I had some edges that were being created and destroyed on the fly. It started crashing on me, and that lead me to this post. petervaz seemed to have the right idea. When I was destroying a body, I was not checking to see if it "existed" or not. For me, it was a simple check of a boolean value I had already set up.

```
if (on)
{
    on = false;
    world.getPhysicsWorld().destroyBody(body);
}

```

There have not been any of those crashes since I put that check in.

# Answer
> -3 votes
You **must** destroy your body after collision happened, for that override your EndContact() method.

---
Tags: box2d, libgdx
---


# Question
Title: Collision Detection Code Structure with Sloped Tiles
Im making a 2D tile based game with slopes, and I need help on the collision detection. This question is not about determining the vertical position of the player given the horizontal position when on a slope, but rather the structure of the code.

Here is my pseudocode for the collision detection:

```
void Player::handleTileCollisions()
    {
        int left = //find tile that's left of player
        int right = //find tile that's right of player
        int top = //find tile that's above player
        int bottom = //find tile that's below player

        for(int x = left; x <= right; x++)
        {
            for(int y = top; y <= bottom; y++)
            {
                switch(getTileType(x, y))
                {
                    case 1: //solid tile
                    {
                        //resolve collisions
                        break;
                    }
                    case 2: //sloped tile
                    {
                        //resolve collisions
                        break;
                    }
                    default: //air tile or whatever else
                        break;
                }
            }
        }
    }

```

When the player is on a sloped tile, he is actually inside the tile itself horizontally, that way the player doesn't look like he is floating. This creates a problem because when there is a sloped tile next to a solid square tile, the player can't move passed it because this algorithm resolves any collisions with the solid tile. Here is a gif showing this problem:

So what is a good way to structure my code so that when the player is inside a sloped tile, solid tiles get ignored?

# Answer
The most fail-proof method is to simply not do collision with the solid blocks "under" the slope. A fairly simple pass over all tiles can determine which edges are "outer" edges (a tile edge that is not butted against another solid edge) and "inner" edges (edges which correspond directly to an edge on the adjacent block).

In your example, the solid block has at least two inner edges: the top edge butts against the bottom edge of the slope above it, and the left edge butts against the right edge of the slope left of it.

You needn't ever perform collision detection against inner edges. It is impossible to "touch" an inner edge since an object would have to move through the adjacent solid block so clearly the inner edge can never collide with anything.

You can store these inner/outer edge flags as a bit mask simply left. `0x01` as Top, `0x02` as Right, `0x04` as Bottom, and `0x08` as Left works fine (you can either set them to 1 for outer or 1 for inner, whichever you prefer). When doing your detection, you can check the bitmask to see if the edge should be considered.

Note that having a solid debug line drawing facility helps with testing. I know in past student projects while in school we found it great help and even fun to be able to turn on the drawing of all outer edges and then turn off drawing of the tiles themselves, turning the world into an outline vector-like affair. Adding a little extra info for the normals of the edges also came in handy when doing more involved physics.

You can also do edge combination. For any two edges with the same normal sharing a vertex, you can combine them into a single longer edge. This allows you to continue using tiles for editing while using more geometric approaches for collision, which can also solve a few other potential problems, and can be easily combined with Box2D's edge-chain support if you want to combine your tiles with a full 2D physics engine.
> 1 votes

---
Tags: collision-detection, architecture
---


# Question
Title: WebGL CORS error loading simple texture in Chrome
Here's my code:

```
function loadTexture() {
    textureImage = new Image();

    textureImage.onload = function() {
        setupTexture();
    }

    textureImage.src = "jumper2.png";
}

function setupTexture() {
    texture = gl.createTexture();

    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);

    // this next line has the error: Uncaught SecurityError: An attempt was made to break through the security policy of the user agent.
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImage);
    gl.texParameteri(gl.TEXTURE_2D, gl.OES_TEXTURE_FLOAT_LINEAR, gl.NEAREST);

    if (!gl.isTexture(texture)) {
        alert("Error: Texture is invalid");
    }

    glProgram.samplerUniform = gl.getUniformLocation(glProgram, "uSampler");
    gl.uniform1i(glProgram.samplerUniform, 0);
}

```

I've researched it and it is a CORS error a "Cross-origin resource sharing" error, but it's a local file! I can't figure out what's wrong.

I did make the picture using gimp, and I'm not sure the coding was right on the export, but I eliminated a previous error using "gl.OES\_TEXTURE\_FLOAT\_LINEAR".

# Answer
I found the problem, it needs to be run from a web server to bypass the security policy, then it can access the local files as they are set up in the server.
> 0 votes

---
Tags: loading, webgl
---


# Question
Title: Having a problem with texturing vertices in WebGL, think parameters are off in the image?
I'm having a problem texturing a simple rectangle in my WebGL program, I have the parameters set as follows:

```
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImage);

```

I'm using this image:

On the properties of this image it says it's 32 bit depth, so that should take care of the gl.UNSIGNED\_BYTE, and I've tried both gl.RGBA and gl.RGB to see if it's not reading the transparency. It is a 32x32 pixel image, so it's power of 2. And I've tried almost all the combinations of formats and types, but I'm not sure if this is the answer or not.

I'm getting these two errors in the chrome console:

1. INVALID\_VALUE: texImage2D: invalid image (index):101
2. WebGL: drawArrays: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering or is not 'texture complete'. Or the texture is Float or Half Float type with linear filtering while OES\_float\_linear or OES\_half\_float\_linear extension is not enabled.

the drawArrays function is simply: "gl.drawArrays(gl.TRIANGLES, 0, 6);" using 6 vertices to make a rectangle.

Here's the main part of the code:

```
function loadTexture() {
    textureImage = new Image();

    textureImage.onload = function() {
        setupTexture();
    }

    textureImage.src = "jumper5.png";
}

function setupTexture() {
    texture = gl.createTexture();

    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);

    /*
    void texImage2D(GLenum target, GLint level, GLenum internalformat,
                    GLenum format, GLenum type, HTMLImageElement image);
                    // May throw DOMException
    */
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImage);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

    if (!gl.isTexture(texture)) {
        alert("Error: Texture is invalid");
    }

    glProgram.samplerUniform = gl.getUniformLocation(glProgram, "uSampler");
    gl.uniform1i(glProgram.samplerUniform, 0);

}

```

The shaders are as follows:

```
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;

varying highp vec4 vColor;
varying highp vec2 vTextureCoord;

void main(void) {
    gl_Position = vec4(aVertexPosition, 1.0);
    vTextureCoord = aVertexPosition.xy + 0.5;
}
</script>

<script id="shader-fs" type="x-shader/x-fragment">
varying highp vec2 vTextureCoord;
uniform sampler2D uSampler;

void main(void) {
    gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
}
</script>

```

Here's the code with the rectangles vertices and the draw function:

```
function setupDynamicBuffers() {
    // limit translation amount to -0.25 to 0.25
    var x_translation = Math.sin(angle)/4;

    var triangleVertices = [

     // rectangle top left triangle
    -0.5 + x_translation, -0.5,  0.0, // (-0.25, -0.25)  bottom left
     0.5 + x_translation, -0.5,  0.0, // (-0.25,  0.25)  top left
     0.5 + x_translation,  0.5,  0.0, // ( 0.25,  0.25)  top right

     // rectagle bottom right triangle
     0.5 + x_translation,  0.5,  0.0, // ( 0.25, -0.25)  bottom right
    -0.5 + x_translation,  0.5,  0.0, // (-0.25, -0.25)  bottom left
    -0.5 + x_translation, -0.5,  0.0  // ( 0.25,  0.25)  top right

     ];

     angle += 0.01;

     trianglesVerticeBuffer = gl.createBuffer();
     gl.bindBuffer(gl.ARRAY_BUFFER, trianglesVerticeBuffer);
     gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVertices), gl.DYNAMIC_DRAW);

}

function drawScene() {

    vertexPositionAttribute = gl.getAttribLocation(glProgram, "aVertexPosition");

    gl.enableVertexAttribArray(vertexPositionAttribute);
    gl.bindBuffer(gl.ARRAY_BUFFER, trianglesVerticeBuffer);
    gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);

    //vertexColorAttribute = gl.getAttribLocation(glProgram, "aVertexColor");
    //gl.enableVertexAttribArray(vertexColorAttribute);
    //gl.bindBuffer(gl.ARRAY_BUFFER, trianglesColorBuffer);
    //gl.vertexAttribPointer(vertexColorAttribute, 3, gl.FLOAT, false, 0, 0)

    gl.drawArrays(gl.TRIANGLES, 0, 6);
}

```

# Answer
> 0 votes
I found the solution to the problem, it needed to have the MIN filter activated, adding:

```
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);

```

solved the problem.

---
Tags: 2d, textures, webgl
---


title: What is w componet

text:
# Question
Title: What is w componet
What is the W component on graphics programming. I read a blog about opengl that says that w must be equal to either 0 or 1 here. But the book I am currently reading has put w component to more than 1 value. So im kinda confuse what does it really do. The book I am reading is OpenGL es a quick start guide.

# Answer
> 4 votes
This is related to the affine transformation matrix. Basically, a `0` means that you are working with a *vector* (which has no position and is not affected by the affine portion of transformation matrices) and a `1` means that you are working with a *point* (which is affected by affine transformations).

Consider this 3x3 column-major 2D affine translation matrix:

```
1 0 5
0 1 3
0 0 1

```

If you apply this to the vector `<2, 4, 0>` then when the matrix rows are multiplied we get:

```
2 0 0 = 2
0 4 0 = 4
0 0 0 = 0

```

And the result is the input vector. No affine translation applied. This is exactly what we want: you can't "move" a vector.

Now let's apply this to the *point* `(7, 8, 1)`:

```
7 0 5 = 12
0 8 3 = 11
0 0 1 = 1

```

And we get the point `(12, 11, 1)` which is the original point plus the translation portion of the matrix, which again is exactly what we want.

You will notice that the `w` component stays the same based on the input; that is, transforming a vector produces a vector and transforming a point produces a point.

There are additional benefits to this simple math. Think of the operations of adding or substracting vectors or subtracting points. Two vectors added or subtracted create a resulting vector.

```
  1 2 0
+ 5 3 0
= 6 5 0

```

Likewise, with subtraction, the math works out.

Now, let's substract two points. We know that this should result in a vector (the difference between the points) and not another point. Conveniently:

```
  5 3 1
- 1 2 1
= 4 1 0

```

Perfect. Of course, if you add two points together then you end up with a `w` of 2, but then adding points is not a legal operation (it has no meaningful result). Adding a point to a vector should result in a new point, which of course works:

```
  5 3 1
+ 4 4 0
= 9 7 1

```

Everything works out. The `w` component perfectly encodes whether we have a *point* or a *vector* and simultaneously allows the application of affine transformation matrices correctly for vectors vs points. This allows the use of a single transformation matrix for both points and vectors, which is useful when we want to apply it to both vertex positions (points) and vertex normals (vectors) or the like.

---
Tags: opengl, 3d, graphics, opengl-es2
---


# Question
Title: How do I choose the scaling factor of a 3D game world?
I am making a 3D tank game prototype with some physics simulation, am using C++. One of the decisions I need to make is the scale of the game world in relation to reality. For example, I could consider 1 in-game unit of measurement to correspond to 1 meter in reality. This feels intuitive, but I feel like I might be missing something.

I can think of the following as potential problems:

1. 3D modelling program compatibility. (?)
2. Numerical accuracy. (Does this matter?) Especially at large scales, how games like Battlefield have huge maps: How don't they lose numerical accuracy if they use 1:1 mapping with real world scale, since floating point representation tend to lose more precision with larger numbers (e.g. with ray casting, physics simulation)?
3. Gameplay. I don't want the movement of units to feel slow or fast while using almost real world values like `-9.8 m/s^2` for gravity. (This might be subjective.)
4. Is it ok to scale up/down imported assets or it's best fit with a world with its original scale?
5. Rendering performance. Are large meshes with the same vertex count slower to render?

I'm wondering if I should split this into multiple questions...

# Answer
> 3 votes
Generally you should do whatever works.

1. Since you have real life objects it makes sense to match their scale (3D modelling apps usually have measurement units setup, meters, foot, etc.), but once you move away from tanks and into trees and other scenery objects - they probably will need to be custom scaled to fit your game style (so you model a tree and have means of scaling it in the game editor to make it look good, many times you will reuse the same tree but with a different scale to add variety).
2. Do not move the camera far away from the worlds origin, but *move the world around camera* placed near worlds origin. This way you avoid a lot of precision issues that arise when GPU/physics need to precisely compare values that have poor precision. If you move tank and camera 10km from origin your precision will be in a matter of fractions of a millimeter with float32 and that can cause effects similar to Z-fighting between transformed models.
3. You will have to tweak global constants to make your game feel good. It is the same way that you change worlds relative scale to skip boring parts and pack more interesting things into a small 4x4 km area (town, river, mountain, etc.) that are far away from each other in real world.
4. If they looked better scaled - scale them. If they fit as they are - keep that. Games and movies are more of an art than about blind copying reality. So you have found a nice looking tree, that is just modeled 2m tall, of course you scale it and adapt yo your game by other means (tweak palette, texture detail, etc.)
5. I doubt there's any difference as long as they take the same amount of pixels on screen to display.

# Answer
> 8 votes
Here it goes.

1. 3D modelling programs tend to let you select the unit scale. Might be limited to Imperial or Metric, but it's just a number. Numbers can be converted/scaled/adjusted easily. It doesn't really matter what unit system you use, as long as you use that *one*. Stay consistent, so 1 meter doesn't become 1 foot.

Edit: Book: Game Coding Complete, Third Addition, Chapter 15, pg. 525, "Meters, Feet, Cubits, or Kellicams?"
2. Games with large chunks of vertices can do several thing's. For one, they can split it up into small chunk's, and then data referring to that chunk can specify an offset. Somewhat similar to using Octrees, which is a rendering optimization to avoid rendering large-portions of unseen vertices. Alternatively, a double can store 1.79769e+308, which is a pretty big, yet detailed, number. A float can store 3.40282e+038, which isn't to shabby either.

Edit: Game Coding Complete, Third Addition, Chapter 13, pg. 410, "Coordinates and Coordinate Systems" (Table added to the bottom of the post)
3. Your probably going to want to use a metric system then, or convert it to your own unit system. Worth noting, is that your probably going to tweak that value a bit. Sure, your tweaked value won't be physically accurate. But it might *feel* more accurate at, say, `-9.3 m/s^2`.
4. You *can* do it either way. Though I would say to scale the asset. If you scale the world, you'll have to go through and change gravity, velocity calculations, and all sort's of other things. When importing assets into Unity3D I normally have to adjust the model scale in the import setting's, so I assume Unity scales it. If you wanted something more along those lines.
5. Large or small, the size of the polygons/mesh doesn't matter NEARLY as much as how many polygons there are. I suppose there might be a slight performance change depending on how many pixels the model takes up, but that's it. Aside from that, a number being 10 or 100 doesn't change anything on the computer's end. It's still the same number of bits to process, it's just that different bit's are 0.

Edit: The fallowing table assumes a 32-bit IEEE floating-point number.

```
Game Coding Complete, Third Addition, Table 13.2, pg. 411
Smallest unit         Smallest Representable object  Upper Range    Description of
                      (As a textured polygon)                       largest area

100m                  A group of redwood trees       1.67x10^9      Earth/Moon System
1m                    A Human Being                  1.67x10^7      North and South America
1cm                   A coin                         1.67x10^6      California
1mm                   A flea                         1.67x10^5      San Francisco Bay Area
100 micrometer        A grain of pollen              1.67x10^4      Downtown San Francisco

```

All this information, and more, in Game-Coding Complete. Written by Mike McShaffry. An Industry professional working on games ranging from Black Jack, to Thief: Deadly Shadows.

---
Tags: 3d, level-design
---


# Question
Title: Is it possible to calculate or mathematically prove if a game is balanced / fair?
This question is not focussed on video games but games in general. I went to a boardgame trade fair yesterday and asked myself if there is a way to calculate the fairness of a game. Sure, some of them require a good portion of luck, but it might be possible to calculate if some character is overpowered. Especially in role-playing games and trading card games. How, for example, can the creators of "Magic: The Gathering" make sure that there isn't the "one card that beats them all", given the impressive number of available cards?

# Answer
> 34 votes
Yes, it's *theoretically* possible - that's a good part of the game theory which deals with this subject.

However, it's only rarely *practical*, and even then mostly just for games which don't involve a randomiser (Chess, Reversi, Go and so on). Combinatorial explosion ensures that the theoretical time needed for such proofs for more complex games like Magic the Gathering can easily be several orders of magnitude longer than the current age of the universe.

In the end, for any non-trivial game you'll likely have to abandon the notion of *proving* balance or fairness of a game and instead go with a combination of common sense, designer instincts, game system reuse and throughout testing.

# Answer
> 6 votes
Short answer: Any game with a finite, even if undefined, number of available moves thus has a finite number of possible games. Any game with a finite "game tree complexity" can theoretically have all possible games analyzed to determine if the number of games in which each player would win is equal.

Simply put: if Player 1 wins exactly half of all possible plays of a game, the game is balanced. If this is not true, the game is biased towards one player or the other.

However, this simple rule can be quite infeasible to put in practice. Go, for instance, has a game-tree-complexity on the order of 10^170 possible games, more than the number of atoms thought to exist in the known universe. It is thought to be impossible to compile an exhaustive game tree. However, the library of games played and recorded is in the millions, and suggest that the game has a "first-move advantage" (which is typically mitigated with 1.5 points of "komi" given to White).

Contrasting that, even given large overall game-tree-complexities, all M,N,K games (a grid board of M width, N height, in which the object is for a player to create a row of K pieces by placing and never moving/removing them) are solved, because there is a shortcut; entire "branches" of the game tree can be identified as always causing one player or the other to lose. The remaining branches follow a pattern that can be identified. Tic-Tac-Toe is the obvious example; in addition to having only 300,000-ish possible games, there are only 16 in which one player or the other doesn't make a move that will obviously let the other player win on the next move. So, the game-tree starts small and gets smaller when you consider the games the players are actually likely to make.

In games with an element of luck, the game-tree complexity is inflated beyond the number of decisions available to each player. Because the game is no longer played with "perfect information", as it is in chess, checkers, Go, Othello, etc, it is possible for a player who has played perfectly given the known information at the time to still lose to the game's random element. These games have no "solution"; however, there is usually still a finite game tree and so theoretically games could still be analyzed exhaustively. This is still usually not feasible; instead games involving probability are analyzed probabilistically to identify the "best-bet" strategies, and if these strategies are shown to favor the player that uses them, regardless of the strategy used by any other player (including the same strategy), the game can be shown to have bias.

In general, the following rule applies: if the design of the game inherently leads to inequality in one or more of the following, the game has a bias:

* Number of total moves for each player
* Number of moves available at any given time that will allow at least one more move for that player
* Starting strength of players' forces
* Access to finite resources or areas of identified strategic significance

Now, the game's design may introduce one inequality but attempt to compensate with another. Or, the game's design may allow for randomness in areas that may produce bias, meaning one game might be biased while another is fairer (games with random starting boards can exhibit this). In these cases only empirical analysis of games between players of roughly equal strength over the long-term can demonstrate any bias.

For more discussion of bias in board games, try the forums of http://www.geekdo.com; there have been several discussions of demonstrated bias in games, and how to avoid said bias in game development in general.

# Answer
> 3 votes
I guess there is no pre-made mathematical formula to evaluate how fair a game is because of how every game is so different and complex.

You can't really compare different game parameters and make up some sort of *power score* of how good a character is (unless your game is very simple) because they all affect your gameplay differently and depend on how they are implemented (e.g. how can you evaluate how strength relates to vitality? How do you give a numerical value to a character's special attack?).

You have to test your game. *A lot*. Play your game by yourself and make others play it and store the battle/game results in a file in order to make statistics and evaluate how often certain characters win, under what circumstances, etc. Then, make sure you implement some way to check replays or analyse gameplay in order to see why such a character is overpowered and apply the changes accordingly.

Really, you have no other option than testing. That's one of the reasons why betas exist (e.g. Starcraft2 as a beta gave Blizzard the opportunity to balance the 3 races based on the game results).

To sum up, play your game, and make others play it (starting a beta is an option). See why the game is unbalanced through replays or automated analysis and change what needs to be changed accordingly. That's the only way you'll approach fairness.

# Answer
> 3 votes
To be able to prove a game was balanced or fair, you'd have to define what balanced or fair means first. These are rather vague terms that can encompass a range of things, for example game 'balance' is often taken to mean:

* each of several different sides has the same chance to win
* progression through the game gets consistently more challenging
* decisions made within the game offer identical cost/payoff ratios in some/most/all cases

And so on.

In general I am a fan of mathematically proving things like this, but to prove anything through logic or testing you first need to define it clearly. Some aspects of balance are easy to test through mathematics if you're able to understand your game rules properly. Others are much harder to judge without simply conducting empirical tests. The main problem is that most game designers don't truly understand the mechanics of their game, since they usually end up merging game rules into a surrounding simulation, and the latter is very hard to model accurately.

# Answer
> 1 votes
Theoreticaly it is possible, but for most games it is extremely difficult so it can be considered impossible.

One approach: Convert game into normal form. Game in normal form is Set of strategies for each player and function that says how good result is when for given combination of choices. Random factor can be modeled as another player.

Then we can look for dominant/dominated strategies (things to ALWAYS do and things to NEVER do). Game is at lest somehow interesting, if it does not contain dominant strategies.

Then we can look at what each player can guarantee for himself. for each of "MY" choice, look at worst possible outcome and take choice that have this best.

If it differs a lot between players, there is somthing rotten in game.

There are other things to look at (dominant mixed strategy (choosing each choice with some probublity), nash equilibriums (combinations that once all players know others will do, are localy best for everyone)).

But the first step is so extremely complicated for most games, so it's usualy not so usefull. But it can be used if you can absract complicated details away/ replace strategies with recognizable sets of strategies (eg. initial build orders) and result with some statistical aproximation from actualy played games and it can tell you something about problems in game. I guess that something like this blizard does with SC.

Another form of game is game where players takes turns and know everything others do (chess). There you can try to search for dominat strategy by searching state tree of game (and it usualy is HUGE, so again, too complicated to use). And lot of games are without total knowladge and it complicates things a lot.

Another approach, look at things in game and try to compare them.

Another approach: For team combat (esp. with large ammounts participants) you can try to use force on force simulation (I never used it, and it requires high math (diferential equations) and hard work to convert game into aproprite model).

So my conclusion, lot of things can be done to balance subsystems of game, and when game is out (and during betatest), lot can be done by analyzing results, but unless you make everything same, its almost imposible to prove game is balanced.

PS: You can mask sameness by replacing one attribute by multiple that together can be used to compute initial attribute, and by making everything much more random, so players don't see that sameness (

Beware its easy to make mistake in doing so (eg fast small attacks vs big slow attacks), beacuse 18 throws by d6 -18 gives results 0-90, 10 throws by d10-10 gives results 0-90 1 throw by d91-1 gives results 0-90 but all of them have different distributions.

PS2: One wise man said, that actual balance is not important, Percieved balance is.

# Answer
> 1 votes
A lot of good answers about getting a mathematically correct answer, but I'll try a different angle: if your code allows for it, you could simulate a very large number of games and then check if there is a strategy (or strategies) that win too often.

You might be familiar with Monte-Carlo simulations or genetic algorithms. The idea here related. You need an AI to play the game and some key measurement. You let the AI go at each other in a large tournament, often enough, with different starting variables and you measure the results.

I've always wanted to try an approach like that to balances classes/weapons, it would be a ton of fun.

# Answer
> 1 votes
From a theory of computation perspective, it sounds like answering this is not possible *in general*. It's asking a question about a property of a program and Rice's Theorem may apply. My assumption is that *game* refers to a program written in a Turing Complete language like c++. I'm also assuming that to *calculate or prove whether a game is fair* means there exists a c++ program that reads a c++ program (the game program) and terminates in a finite amount of time *for all possible inputs*, with only two outputs, fair or unfair.

A quick search shows it is possible to have a deterministic yet undecidable game, see slide 7 here and from the International Journal of Game Theory: Some undecidable determined games:

"Computing machines using algorithms play games and even learn to play games. However, the inherent finiteness properties of algorithms impose limitations on the game playing abilities of machines. M. Rabin illustrated this limitation in 1957 by constructing a two-person win-lose game with decidable rules but no computable winning strategies."

The human brain is apparently more "powerful" than computers because we can gain and apply past knowledge and sometimes appear to contradict results like the Halting problem by finding infinite loops in programs. But how we do this is not well known and can't be written precisely and unambiguously in an algorithm.

# Answer
> 0 votes
I really wanted to comment on Martin Sojka's answer, but I don't have the reputation. He is correct that Game Theory includes calculating the fairness of a game (for example, it's an open question if in a chess game where both white and black played perfectly whether it would be a tie).

For MtG it could very well be that it's completely infeasible to calculate whether it's fair, but no one has proven mathematically that the computation would be infeasible.

It might be trivially possible to prove it's fair - if it's random who goes first and everyone plays by the same rules then it's fair. It might be that whoever goes first always wins, but if who goes first is decided fairly then the game is fair.

# Answer
> -2 votes
What is meant by "fair" is vague, let me explain :

Consider the game Rock-paper-cissors (http://en.wikipedia.org/wiki/Rock-paper-scissors) : according to you it is fair, I suppose (according to me as well).

Now, let's consider the game : Rock-paper-cissors-well where the well beats the rock and the paper and the well loses against the paper. Unbalanced, right ? The well seems pretty overpowered : it beats two weapons and loses against one.

But one could say that it is not overpowered at all : because if you know that your opponent is more likely to use the well because it beats two weapons, you can just act by picking the paper more often.

So there is an answer to the potential overpowered well : just choose more often the paper. But then you know that your opponent may know that and may use the paper quite often, so you think you should use the cissors more often. Etc. Not really overpowered, just a different game with different rules.

I would recommend reading about game theory and especially games with imperfect information (http://en.wikipedia.org/wiki/Game\_theory).

---
Tags: game-design, game-mechanics, balance
---


title: Slerping rotation mirrors

text:
# Question
Title: Slerping rotation mirrors
I rotate my game character to watch at the target using the following code:

```
        transform.rotation = Quaternion.Slerp(startQuaternion, lookQuaternion, turningNormalizer*turningSpeed/10f)

```

startQuaternion is the character's current rotation when a new target is given.

lookQuaternion is the direction the character should look at and it's set like this:

```
    destinationVector = currentWaypoint.transform.position - transform.position;
    lookQuaternion = Quaternion.LookRotation(destinationVector, Vector3.up);

```

turningNormalizer is just `Time.deltaTime` incremented and `turningSpeed` is a static value given in the editor.

The problem is that while the character turns as it should most of the time, it has problems when it has to do close to 180 degrees. Then it at times jitters and mirrors the rotation:

In this poorly drawn image the character(on the right) starts to turn towards the circle on the left. Instead of just turning either through left or right it starts this "mirror dance":

1. It starts to rotate towards the new facing
2. Then it suddenly snaps to the same angle but on other side and keeps rotating

It does this "mirroring" so long until it looks at the target. Is this a thing with quaternions, slerping/lerping or something else?

**EDIT1:** Apparently the issue does not arise from the rotating itself. The more likely issue is that the character moves toward the facing while it rotates. As limiting the angle, between facing and target, when the character is allowed to move reduces and at times eliminates the jittering/mirroring rotation.

This of course raises more questions, why cannot the character move and rotate at the same time without issues? Code used for the movement:

```
transform.Translate(Vector3.forward * runningSpeed/10f * Time.deltaTime);

```

# Answer
> 5 votes
Each orientation in 3D space can be represented by 2 distinct unit quaternions, `q` and `-q` (component-wise negated `q`). For instance the orientation represented by the 3x3 identity matrix `I` can be represented by 2 quaternions:

```
 q:  { 0,  0,  0},  1
-q:  {-0, -0, -0}, -1

```

Both represent the same orientation in 3D space, their dot product is exactly `-1`, each of them lying in the other hemisphere, exactly on the opposite sides of the hypersphere.

The result you observe when the slerp takes the longer arc to rotate, is when slerping between 2 quaternions that do not lie in the same hemisphere. If that happens, just negate one of them before slerping them, then the slerp will take the shorter arc.

The dot product is an easy tool to find out whether that happens. If the dot product of both quaternions is less than `0`, then they do not lie in the same hemisphere. So if the dot product of both of them is less than `0`, just component-wise negate the other quaternion before slerping them.

# Answer
> 1 votes
Well your problem is because those two vectors that form your quaternions make 180 degrees, so the question that should be asked when interpolating which arc is it supposed to take? the upper arc or the lower one ??

This is what basically causing the mirroring, each time you are interpolating it's taking the other way around while still maintaining the angle.

According to this link.

> When theta is 180 degrees the result is undefined because there is no shortest direction to rotate, I don't think this situation is handled correctly yet, it would be better if we choose some arbitrary axis that is normal to qa or qb, I would appreciate any ideas for the best way to do this.

What you need to do is interpolating your starting quaternion with an intermediate quaternion (to determine which arc to take) and when reached use the intermediate quaternion to continue to the actual target quaternion.

# Answer
> 1 votes
The issue I suspect you're seeing has nothing to do with your code, but rather is a fundamental issue with interpolation along the surface of a sphere (in this case, for the viewDirection). Between (almost) any two points on a sphere there's a single great circle - for instance, arbitrarily fixing our 'start' point at the north pole, the great circle would be the meridian that the end point lies on. Interpolation from one point to the other moves along this great circle.

Now, for most points on a sphere, nearby points correspond to nearby great circles; for instance, the meridians that Los Angeles and Phoenix lie on are fairly close to each other. But when the destination point is the *antipode* of the original point — the south pole to the start point's north pole — there's no longer a single great circle through them both, but instead *all* the great circles through one go through the other. What's worse, this means that points near the south pole aren't 'most points'; two points near each other and both near the south pole can have wildly divergent meridians.

I suspect that what you're seeing is a manifestation of this instability in the meridian - or in other words, the interpolation arc. When the look target is directly behind the character, then things like the first-order inaccuracy in your 'Euler integration' of the character's position, and the way that changes the look direction frame-to-frame, are going to lead to these wildly different interpolation arcs from one frame to the next, and this will likely lead to the 'stagger' that you're seeing.

As far as what to do with it, the best thing that springs to mind is to not recompute the 'target' look direction every frame; instead, use the same one for a span of several frames, then compute a new one and use that for several frames, etc. If need be, you can even interpolate from one target to the next over the span of a few frames so that the direction of motion doesn't change too abruptly.

---
Tags: c#, unity, mathematics, rotation, quaternion
---


# Question
Title: Railgun Ruby - is there a documentation?
I finally found Railgun Ruby on the web and installed it.

But I cannot find any documentations.

Does anyone have played around with it? Does anyone still have a good documentation about it?

I'd like to have a look at what it can do.

Thanks.

Yours, Joern.

# Answer
> 2 votes
Doesn't look like it. The project appears dead -- links to it's homepage on Rubyforge go nowhere, and there's only a few casual mentions of it around the internet (usually with associated chatter about Rubygame and some naysayers asserting that Ruby isn't suitable for game development -- YMMV).

I wouldn't recommend using a library in this state. Rubygame looks, at least superficially, like a much more viable product than Railgun.

# Answer
> 2 votes
You may checkout ruby Game libraries at ruby-toolbox. https://www.ruby-toolbox.com/categories/game\_libraries (13 projects)

There is list of languages bindings: http://freegamedev.net/wiki/index.php/Free,\_cross-platform,\_real-time\_3D\_engines#Native\_and\_binded\_languages\_support

also you may search "3D Game engine with Ruby binding ?" at ruby-forum.com/topic/92822 and "Velocity Reviews \> Newsgroups \> Programming \> Ruby \> Ruby 3D" at velocityreviews dot c0m

sorry, some information not so fresh

---
Tags: ruby
---


title: How do I use unpackHalf2x16?

text:
# Question
Title: How do I use unpackHalf2x16?
I'm trying to use (un)packHalf2x16, without success so far. I'm drawing with:

```
glVertexAttribIPointer(0, 2, GL_UNSIGNED_INT, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glDrawArrays(GL_POINTS, 0, n_points);
glDisableVertexAttribArray(0);

```

and on the shader

```
#version 330 core
#extension GL_ARB_shading_language_packing : require
in uvec2 A0;
// (...)
vec4 t = vec4(unpackHalf2x16(A0.x), unpackHalf2x16(A0.y));

```

But nothing gets drawn. I'm pretty sure buffer's content is right, and if I use *vec4 t = vec4(0);* I can see it's working properly. How is this packing / unpacking thing supposed to work? I can't find any example.

# Answer
> 1 votes
I think you may have to bind your array buffer before calling glVertexAttribIPointer. But other than that the code looks correct. But why not just use half float vertex attributes and avoid the shader work?

```
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4,  GL_HALF_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_POINTS, 0, n_points);
glDisableVertexAttribArray(0);

```

and

```
#version 330 core
in vec4 t;
// (...)

```

---
Tags: opengl, shaders, vertex-buffer
---


title: Multiple texture coordinates per mesh?

text:
# Question
Title: Multiple texture coordinates per mesh?
So far I've used the same texture coordinate for both the normal and diffuse textures on a mesh, yet when reading the Assimp documentation (http://assimp.sourceforge.net/lib\_html/structai\_mesh.html#details) on a Mesh, it implies that there can be more than one texture coordinate sets per mesh.

My question is, in general what scenario would these be present and what is their purpose?

# Answer
> Multiple texture coordinates per mesh what is their purpose?

Multiple texture coordinates set can be used to achieve different texture mapping per mesh, this helps achieve different visual effects that are otherwise hard to accomplish and may require multi-pass rendering.

> What scenario would these be present?

For example Reflection mapping usually uses different texture coordinate set other than the one used for applying the basic diffuse texture, this is needed to achieve the illusion of reflection, since perfect reflection isn't usually feasible in real time renderings and may not even add much to the rendering quality. Note that texture coordinates that are used for reflection mapping might be calculated at runtime based on normals, in other cases they can be precomuputed.

Other examples for the use of multi-texture coordinates may include light mapping and alpha mapping.
> 7 votes

---
Tags: opengl, c++, textures, assets, assimp
---


title: 2D fighting bounding boxes

text:
# Question
Title: 2D fighting bounding boxes
I'm prototyping a 2D platformer/brawler game for uni and I'm having some trouble with creating collision/bounding boxes. This is most likely going to end up on a Vita so I do have some library constraints as well as performance implications.

None of this has yet been implemented but is all theory.

My idea was to have the artist create a sprite sheet for the character animation and then a second identical sprite sheet with the corresponding collisions in a solid colour (e.g green for where the character can be hit and red for dealing damage, near the foot if kicking etc.)

With this, I would then parse the collision sheet and generate the various collisions required storing them in the character model. This is the point I feel would be most inefficient.

While I think this is a possible solution, I was wondering if there was a more standard way of doing this or a more efficient way as I feel this would have severe performance problems.

# Answer
You should go for a set of bounding boxes (BB) per sprite. This way you can separate your points of interest in the sprite and automatically knows which parts of the sprites participate in a collision. For example, you could have BBs for the arms, heads, legs, etc. The price for that is that you also must animate them and you will have more collision entities in your game. You should also use Oriented Bounding Boxes, since they have more culling efficiency than other boxes. If you want more detail and can afford the performance penalty, go for K-dops.
> 2 votes

---
Tags: 2d, collision-detection, sprites
---


# Question
Title: Do I need "cube subclasses" to represent the blocks in a Minecraft-like world?
I would like to try to develop a very simple game like Minecraft for my own education.

My main problem at the moment is figuring out how to model classes that represent the world, which will be made of blocks of various types (such as dirt, stone and sand).

I am thinking of creating the following class structure:

* Cube (with proprerties like color, strength, flammable, gravity) with subclasses:
    + Dirt
    + Stone
    + Sand
    + et cetera

My question is, do I need the Cube subclasses or a single class `Cube` sufficient?

# Answer
In your case, I'd model both the block and the block type as objects. The Cube object should be very lightweight, because you're likely going to have a lot of those instantiated to represent your world. To start with, the Cube object can contain only a pointer to a CubeType (or an appropriately-sized integer that refers to a cube type, if you are even more space-conscious).

The CubeType object itself is where you'd store all the properties of particular types (such as dirt). This allows you to avoid the overhead of duplicating the repeated properties (all dirt blocks being the same color, after all) into every single block.

I see no reason to use inheritance at all for the problem scenario you have described.
> 4 votes

# Answer
Inheritance is used when **there is common base functionality that needs to be shared**.

The type-nature of a block (whether its dirt, stone, or lava - you can only be *one* type of block!) would best be implemented by an `enum`

```
enum BlockType { Dirt, Stone, Water, Lava } ;

```

A base object of type `Block` would then be:

```
class Block
{
     BlockType blockType ;
}

```

Based on `blockType` you could then specify properties for that blocktype in any number of ways. One *simple* way would be to write member functions that return results based on the value of `BlockType`.

```
class Block
{
     BlockType blockType ;
     bool isFlammable() {
         return blockType == Lava ;
     }
     bool isStone() {
         return blockType == Stone ;
     }
     bool isSolid() {
         return blockType!=Lava && blockType!=Water ; // only nonsolid types
     }
}

```

This is flexible and would actually allow blocktypes to change *type* at runtime, which would completely change how they behave instantly.

You could also store a `map<BlockType,BlockProperties>`, where each `BlockType` has a `BlockProperties` object (that lists all its properties).

```
class BlockProperties
{
    bool isFlammable, isSolid ; //etc.
} ;

map< BlockType, BlockProperties > blockProps;

// once at startup,
blockProps[ Dirt ].isSolid = 1 ;
blockProps[ Dirt ].isFlammable = 0 ;
// ...

```

This would be like storing a "prototype" of each base object. Per-block customizable properties would go directly in `class Block` (such as an HP member). Class-level properties per-block (such as `maxHp`, or `damageResistance`) would go in `BlockProperties`.
> 3 votes

# Answer
I think your line of reason is good for the moment. A very good rule of thumb when designing classes is to avoid adding stuff that are not needed **yet**. What I mean is that if you think about a feature that might be needed in the future, perhaps you should leave it to be included in the model later on, when it is really needed and (perhaps) you will have a better understanding of what is required. By experience, this avoids clamping the solution.

For instance, in your case one could think about having an intermediate inheritance between Cube and the children Dirt and Sand, since they are smaller (than Stone, for instance) and might share dust-like properties. If that is not a current need, forget about it and keep it simple.

I would not go with the solution of having just a type ID. First of all, because in that way you will not be able to rely on the benefits from the object orientation.

Also, I have this feeling that as your game gets developed you will eventually/possibly identify the need to have shared properties or behaviours in a fashion that resembles the Bridge Design Pattern. If you don't known the pattern yet, it is definitely worthwhile reading about it (some references here and here). :)

EDIT: I do think the answer given by @bobobobo is very good indeed. And one suggestion to properly address the points correctly noted could be the use of a bridge pattern like the following:

In that way, the map suggested in one of the commentaries would allow to configure a very comprehensive range of block types with different properties. For instance, a block could be breakable and flammable by having instances of the two corresponding property classes, children from BlockProperty. The maintenance shall be easy (need a new type? just create a new child from BlockProperty) and updating blocks in the game/prototype is just a matter of iterating through the map (as @bobobobo already mentioned).
> 2 votes

---
Tags: software-engineering, data-structure
---


# Question
Title: "exception at 0x53C227FF (msvcr110d.dll)" with SOIL library
I'm creating a game in C++ using OpenGL, and decided to go with the SOIL library for image loading, as I have used it in the past to great effect. The problem is, in my newest game, trying to load an image with SOIL throws the following runtime error:

This error points to this part:

```
// SOIL.c
int query_NPOT_capability( void )
{
/*  check for the capability    */
if( has_NPOT_capability == SOIL_CAPABILITY_UNKNOWN )
{
    /*  we haven't yet checked for the capability, do so    */
    if(
        (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
            "GL_ARB_texture_non_power_of_two" ) )
        ) //############ it points here ############//
    {
        /*  not there, flag the failure */
        has_NPOT_capability = SOIL_CAPABILITY_NONE;
    } else
    {
        /*  it's there! */
        has_NPOT_capability = SOIL_CAPABILITY_PRESENT;
    }
}
/*  let the user know if we can do non-power-of-two textures or not */
return has_NPOT_capability;
}

```

Since it points to the line where SOIL tries to access the OpenGL extensions, I think that for some reason SOIL is trying to load the texture before an OpenGL context is created. The problem is, I've gone through the entire solution, and there is only one place where SOIL has to load a texture, and it happens **long** after the OpenGL context is created.

This is the part where it loads the texture...

```
   //Init glfw
if (!glfwInit())
{
    fprintf(stderr, "GLFW Initialization has failed!\n");
    exit(EXIT_FAILURE);
}
printf("GLFW Initialized.\n");

//Process the command line arguments
processCmdArgs(argc, argv);

//Create the window
glfwWindowHint(GLFW_SAMPLES, g_aaSamples);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
g_mainWindow = glfwCreateWindow(g_screenWidth, g_screenHeight, "Voxel Shipyard", g_fullScreen ? glfwGetPrimaryMonitor() : nullptr, nullptr);
if (!g_mainWindow)
{
    fprintf(stderr, "Could not create GLFW window!\n");
    closeOGL();
    exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(g_mainWindow);
printf("Window and OpenGL rendering context created.\n");

//Create the internal rendering components
prepareScreen();

//Init glew
glewExperimental = GL_TRUE;
int err = glewInit();
if (err != GLEW_OK)
{
    fprintf(stderr, "GLEW initialization failed!\n");
    fprintf(stderr, "%s\n", glewGetErrorString(err));
    closeOGL();
    exit(EXIT_FAILURE);
}
printf("GLEW initialized.\n"); <-- Sucessfully creates an OpenGL context

//Initialize the app
g_app = new App();
g_app->PreInit();
g_app->Init();
g_app->PostInit(); <-- Loads the texture (after the context is created)

```

...and debug printing to the console CONFIRMS that the OpenGL context was created before the texture loading was attempted.

So my question is if anyone is familiar with this specific error, or knows if there is a specific instance as to why SOIL would think OpenGL isn't initialized yet.

# Answer
```
if(
    (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
        "GL_ARB_texture_non_power_of_two" ) )
    ) //############ it points here ############//

```

You are creating an OpenGL 3.2 context. `glGetString(GL_EXTENSIONS)` returns `NULL` because it has been deprecated in 3.0 and removed in 3.1. It was replaced by `glGetStringi(GL_EXTENSIONS, i)`.

See also here.

A quick fix would be to request a no higher than 3.0 context. But if you need \> 3.0 functionality you will have to patch the SOIL library to use the correct method to test for extensions as described in the link above. This would have to be done everywhere `glGetString(GL_EXTENSIONS)` is called.
> 6 votes

---
Tags: c++, opengl, textures, loading, texture-atlas
---


# Question
Title: Coordinate and positioning problem on iOS with cocos2d-x
I'm using cocos2d-x alongside with Marmalade and running some tests and tutorials before starting an actual project with them. So far things are working reasonably well on the windows simulator, Android and even on Blackberry's Playbook, but on iOS devices (iPhone and iPad) the positioning seems to be off.

To make things clearer, I put together a scene that just draws an image in the middle of the screen. It worked as expected on everything else, but this is the result I got on an iPhone:

To get the coordinates for the center of the screen I'm using the VisibleRect class from the TestCpp sample. It just uses sharedOpenGLView to get the visible size and visible origin, and calculate the center from that.

```
CCSprite* test = CCSprite::create("Ball.png", CCRectMake(0, 0, 80, 80) );
test->setPosition( ccp(VisibleRect::center().x, VisibleRect::center().y) );

this->addChild(test);

```

Also I have a noBorder policy set on AppDelegate:

```
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(designSize.width, designSize.height, kResolutionNoBorder);

```

One funny thing is that I tried to deploy the TestCpp sample project to some iOS devices and it worked reasonably well on the iPhone, but on the iPad the application was only being drawn on a small portion of the screen - just like what happened on the iPhone when I tried using the ShowAll policy.

# Answer
Alright, after more digging I finally came across a more definitive solution. I posted the solution in my forum post on the issue on cocos2d-x's forum, but I'll post it here too just in case.

So the real issue is that on iOS devices, device orientation isn't reported correctly, and on Landscape mode, the screen coordinates will have the width and height values swapped. To fix that, I basically used the solution described by Tim Closs in this forum post for rotating the projection matrix, with minor tweaks:

New method in AppDelegate:

```
    /**
     * Update the projection, based on an input angle, and store back the new w, h
     *
     * @param angle 0, 90, 180 or 270
     * @param w the new width of the virtual display
     * @param h the new height of the virtual display
     */
    virtual void updateProjection(float angle, float& w, float& h);

```

Method implementation:

```
void AppDelegate::updateProjection(float angle, float& w, float& h) {
    if (IwGLGetInt(IW_GL_VIRTUAL_WIDTH) >= 0) {
        w = (float)IwGLGetInt(IW_GL_VIRTUAL_WIDTH);
        h = (float)IwGLGetInt(IW_GL_VIRTUAL_HEIGHT);
    }
    else {
        w = (float)s3eSurfaceGetInt(S3E_SURFACE_WIDTH);
        h = (float)s3eSurfaceGetInt(S3E_SURFACE_HEIGHT);
    }

    if ((angle == 90.0f) || (angle == 270.0f)) {
        // Swap w and h
        float oh = h;
        h = w;
        w = oh;
    }

    CCEGLView::sharedOpenGLView()->setFrameSize(w, h);
    kmGLMatrixMode(KM_GL_PROJECTION);
    kmGLLoadIdentity();
    kmGLRotatef((float)angle, 0, 0, 1);
    kmMat4 orthoMatrix;
    kmMat4OrthographicProjection(&orthoMatrix, 0, w, 0, h, -1024, 1024 );
    kmGLMultMatrix(&orthoMatrix);
    kmGLMatrixMode(KM_GL_MODELVIEW);
    kmGLLoadIdentity();
}

```

Call to AppDelegate::updateProjection in AppDelegate::applicationDidFinishLaunching:

```
bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
    pDirector->setProjection(kCCDirectorProjection2D);

    // Set projection
    float w, h;
    float angle = s3eSurfaceGetInt(S3E_SURFACE_DEVICE_BLIT_DIRECTION) * 90.0f;

    // Workaround for ios devices, force rotation
    int os = s3eDeviceGetInt(S3E_DEVICE_OS);
    if (os == S3E_OS_ID_IPHONE || os == S3E_OS_ID_OSX)
        angle = 90;

    updateProjection(angle, w, h);

    // Rest of method ...
}

```

The original solution also defined the virtual dimensions on marmalade's icf file, thus overriding cocos2d-x's scaling system, but I chose to stick with what cocos2d-x provides and it works just as well. The biggest difference was explicitely setting the angle to 90 for all iOS devices, since the original problem is that landscape orientation wasn't being detected in the first place.

Also it should be noted that after implementing this solution, all my other workarounds for this issue became unnecessary, thus had to be removed for the correct behavior to take place.

Hope this can be of help to someone!
> 0 votes

# Answer
Try this:

```
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSprite* test = CCSprite::create("Ball.png", CCRectMake(0, 0, 80, 80) );
test->setPosition( ccp(winSize.width * 0.5, winSize.height * 0.5) );

this->addChild(test);

```

It works for me.

also try using this sizes:

```
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

```

You will get the visible size and the origin, so you can calculate the real size of the screen, I hope it helps.
> 2 votes

---
Tags: ios, cocos2d-x, marmalade
---