# Question
Title: Finding Z given X & Y coordinates on terrain?
I need to know the most efficient way of finding Z given X & Y coordinates on terrain. My terrain is set up as a grid, each grid block consisting of two triangles which may be flipped in any direction. I want to move game objects smoothly along the floor of the terrain without "stepping." I'm currently using the following method with unexpected results:

```
double mapClass::getZ(double x, double y)
{
    int vertexIndex = ((floor(y))*width*2)+((floor(x))*2);

    vec3ray ray = {glm::vec3(x, y, 2), glm::vec3(x, y, 0)};

    vec3triangle tri1 = {   glmFrom(vertices[vertexIndex].v1),
                            glmFrom(vertices[vertexIndex].v2),
                            glmFrom(vertices[vertexIndex].v3)   };

    vec3triangle tri2 = {   glmFrom(vertices[vertexIndex+1].v1),
                            glmFrom(vertices[vertexIndex+1].v2),
                            glmFrom(vertices[vertexIndex+1].v3) };

    glm::vec3 intersect;

    if (!intersectRayTriangle(tri1, ray, intersect))
    {
        intersectRayTriangle(tri2, ray, intersect);
    }

    return intersect.z;
}

```

`intersectRayTriangle()` and `glmFrom()` are as follows:

```
bool intersectRayTriangle(vec3triangle tri, vec3ray ray, glm::vec3 &worldIntersect)
{
    glm::vec3 barycentricIntersect;

    if (glm::intersectLineTriangle(ray.origin, ray.direction, tri.p0, tri.p1, tri.p2, barycentricIntersect))
    {
         // Convert barycentric to world coordinates
        double u, v, w;
        u = barycentricIntersect.x;
        v = barycentricIntersect.y;
        w = 1 - (u+v);

        worldIntersect.x = (u * tri.p0.x + v * tri.p1.x + w * tri.p2.x);
        worldIntersect.y = (u * tri.p0.y + v * tri.p1.y + w * tri.p2.y);
        worldIntersect.z = (u * tri.p0.z + v * tri.p1.z + w * tri.p2.z);
        return true;
    }
    else
    {
        return false;
    }
}

glm::vec3 glmFrom(s_point3f point)
{
    return glm::vec3(point.x, point.y, point.z);
}

```

My convenience structures are defined as:

```
struct s_point3f { GLfloat x, y, z; };
struct s_triangle3f { s_point3f v1, v2, v3; };
struct vec3ray { glm::vec3 origin, direction; };
struct vec3triangle { glm::vec3 p0, p1, p2; };

```

`vertices` is defined as:

```
std::vector<s_triangle3f> vertices;

```

Basically, I'm trying to get the intersect of a ray (which is positioned at the x, and y coordinates specified facing pointing downwards toward the terrain) and one of the two triangles on the grid. `getZ()` rarely returns anything but 0. Other times, the numbers it generates seem to be completely off. Am I taking the wrong approach? Can anyone see a problem with my code? Any help or critique is appreciated!

---

**EDIT:** After considering what David Cummins has suggested, I can confirm that the ray and the triangle should *always* be intersecting. I added some debugging code to visualize the data. The area shaded red contains the two triangles, and the blue line is the line/ray being checked for intersection. Depth has been disabled when drawing the line.

Here is an example of data being passed to `glm::intersectLineTriangle()`:

```
triangle #1:
v1={x=19.0000000 y=34.0000000 z=2.70000005},
v2={x=19.0000000 y=33.0000000 z=2.70000005},
v3={x=18.0000000 y=33.0000000 z=2.70000005}

triangle #2:
v1={x=18.0000000 y=33.0000000 z=2.70000005},
v2={x=18.0000000 y=34.0000000 z=2.70000005},
v3={x=19.0000000 y=34.0000000 z=2.70000005}

ray origin:
{x=18.5000000 y=33.1871414 z=10.0000000}

ray direction:
{x=18.5000000 y=33.1871414 z=-10.0000000}

```

Despite passing seemingly reasonable arguments, it always returns false. Leaving `barycentricIntersect` as `{x=0.0 y=0.0 z=0.0}`. Am I misusing the function? Are the values I am passing invalid, and I'm just blind to it?

**EDIT 2:** I've written a quick SSCCE. I would be *extremely* grateful if someone could help me debug this issue.

# Answer
There are two things to take care of:

1. Direction of a ray vector in accordance to triangle windings
2. Actual representation of a ray vector

ad. 1)

Seems like `gml::intersectLineTriangle()` function needs a ray vector to point to a front face of a CCW triangle to work.

This is not the case in Your code and You can do two things to fix it: originate a ray vector "below" floor triangles in Your scene (pointing up) or slightly change order of vertices when preparing data for `gml::intersectLineTriangle()` function.

As for the second solution, swapping any two vertice coordinates when preparing data for Your `intersectRayTriangle()` function should do the trick, something like this:

```
vec3triangle tri1 = {   glmFrom(vertices[vertexIndex].v1),
                        glmFrom(vertices[vertexIndex].v3),
                        glmFrom(vertices[vertexIndex].v2)   };

vec3triangle tri2 = {   glmFrom(vertices[vertexIndex+1].v1),
                        glmFrom(vertices[vertexIndex+1].v3),
                        glmFrom(vertices[vertexIndex+1].v2) };

```

ad. 2)

Ray direction vector should be a vector originating in (0, 0, 0) as we're interested in actual direction information. I'm not sure if it should be normalized or not, but tests I've conducted over a normalized version yelded valid results.

When constructing parameters for a ray, try this:

```
vec3ray ray = {glm::vec3(x, y, 10), glm::vec3(0, 0, -1)};

```

(applied along with a second solution to ad. 1) or this:

```
vec3ray ray = {glm::vec3(x, y, 0), glm::vec3(0, 0, 1)};

```

(when not).
> 1 votes

---
Tags: c++, collision-detection, terrain, intersection
---


title: How to slide a non-kinematic rigidbody?

text:
# Question
Title: How to slide a non-kinematic rigidbody?
*I'm studying Unity3d, coming from a 2d background, and I'm a bit confused how some things work.*

I'd like to slide a non-kinematic rigidbody, i.e. "just move it forward", like if it was hovering over the terrain. Applying a force makes a ball rotate forward, while I wanted it to slide forward without rotating, also unless that force is huge, a cube just won't move (for the same reason).

I understand there are kinematic objects which are "easier" to "just move", but I both think I might really need non-kinematic ones, and I think I need to understand them anyway.

edit: I did try to use some "rotation constraints/freeze", but they just prevented the sphere from moving at all.

# Answer
Thought I would post it as an Answer.

When wanting to manipulate a **RigidBody**, You need to take into account the given Physics when **Not-Kinematic**.

Many time in Games Dev there are **2 ways** to Code Physics, Either follow the **laws** and implement them OR, **fake the effect**.

A lot of things that go wrong in Unity is when Realistic Physics **meets**, Fake mimic. Both work, Both are fine to use, but **not really together**.

In your case, I suspect your following the **Real Physics** root.

In this case you need:

* **Freeze the rotation** on The Axis In question (provided by the Rigid-body Properties)
* **(TEST!)** As the rotation is now effectively clamped, Any force applied Will have to compete with the Surface area Friction, one way to quick test is to set **friction to practically nothing**.
* once confirmed Your force is being applied and the objects Velocity is Accelerating, You can then start Changing friction back to norm, whilst **Adding more force** to counteract the friction.
* Alternative ways can also be **Material of your surface**, such as Ice etc.
* Also Please **note** don't forget to **manage your force**, and use clamps, As soon as your object for what ever reason is not encountering friction your massive force will still be applied (pew pew woosh!)

Hopefully This has steered you in the right direction.

TL-DR: Your right! just need to remember to increase or decrease friction!
> 3 votes

---
Tags: unity, rigid-body-dynamics
---


# Question
Title: Clearing an SFML scene with a partially transparent color
Is there way to clear a scene with a transparency (alpha) value, in pure SFML?

I'm trying to clear with `rgba(0,0,0,128)` so the previous frame still partially shows through, which would create a motion blur effect.

I tried `window->clear(Color(0,0,0,128));` but with no result

# Answer
> 0 votes
"Clearing the scene" will not produce this motion blur, you want to draw your frames into a RenderTexture, then draw this texture onto the main screen with your Alpha Blending enabled. Never clear the screen except on window resize.

---
Tags: 2d, sfml, transparency, scene
---


# Question
Title: Unity3D Drag Object with Mouse Gives Invalid Position
I am trying to implement a simple script to drag a GameObject with the mouse in Unity. However, when the position of the object is updated with the following script, I get an error saying:

```
transform.position assign attempt for 'purpie_5' is not valid. Input position is { Infinity, 51351759646418134000000000000000.000000, -143589927261340110000000000000000000000.000000 }.
UnityEngine.Transform:set_position(Vector3)

```

I am not sure what I am doing wrong. This is the code I am using:

```
public class MouseInputInterface : MonoBehaviour {

#region PUBLIC MEMBERS
public Transform heldObject;
#endregion //PUBLIC MEMBERS

#region PRIVATE MEMBERS
private GameObject currTarget;
private Vector3 touchOffset;
private bool dragging = false;
#endregion //PRIVATE MEMBERS

// Use this for initialization
void Start ()
{

}

    void Update()
    {
    if(Input.GetMouseButton(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(ray,out rHit))
        {

            currTarget = rHit.transform.gameObject;

            if(currTarget != null)
            {
                if(!dragging && currTarget.transform.tag == "Moveable")
                {
                    dragging = true;
                    heldObject = currTarget.transform;
                }

            }

        }

        if(heldObject != null)
        {
            /*calculate offset*/
            Vector3 screenPoint = Camera.main.WorldToScreenPoint(heldObject.position);

            /*calculate offset from camera*/
            Vector3 offset = heldObject.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

            //form the current position
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(screenPoint) + offset;

            heldObject.transform.position = curPosition;
        }
    }
    else if(Input.GetMouseButtonUp(0))
    {
        //clear held object
        heldObject = null;
        //clear flag
        dragging = false;
    }

    }
}

```

Thanks for the help.

# Answer
In the line where you get the world position of the mouse:

```
Camera.main.ScreenToWorldPoint(
    new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

```

The z value should be the difference from the camera to the object. For example, with a camera looking "down" the Y axis:

```
public Vector3 GetMousePositionInWorld(Transform heldObject) {
    Vector3 clickPos = Input.mousePosition;
    clickPos.z = Camera.main.transform.position.y - heldObject.position.y;
    Vector3 mousePositionInWorld = Camera.mainCamera.ScreenToWorldPoint(clickPos);

    //You may want to set the position again to clean up floating point errors
    mousePositionInWorld.y = heldObject.position.y;

    return mousePositionInWorld;
}

```
> 2 votes

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


# Question
Title: Balancing game difficulty against player progression
It seems that the current climate of games seems to cater to an obvious progression of player power, whether that means getting a bigger, more explosive gun in Halo, leveling up in an RPG, or unlocking new options in Command and Conquer 4.

Yet this concept is not exclusive to video or computer games -- even in Dungeons and Dragons players can strive to acquire a +2 sword to replace the +1 weapon they've been using.

Yet as a systems designer, the concept of player progression is giving me headache after headache. Should I balance around the players exact capabilities and give up on a simple linear progression? (I think ESIV:Oblivion is a good example of this) Is it better to throw the players into an "arms race" with their opponents, where if the players *don't* progress in an orderly manner, it is only a matter of time until gameplay is unbearably difficult? (4th Edition DnD strikes me as a good example of this) Perhaps it would make most sense to untether the core gameplay mechanics from progression at all -- give them flashier, more interesting (but not more powerful!) ways to grow?

# Answer
This seems like more of a philosophical question with no single "right" answer.

A lot of players enjoy feeling like they're progressing and getting stronger, so removing progression from your game is not an automatic solution. For games in genres built on progression mechanics (like RPGs), removing that core would make for a relatively unique game... but one that you'd have to be careful about since you'd be treading in unfamiliar territory.

Having enemies scale (as with Oblivion) is one way to prevent the game from getting too easy; the danger here is that sometimes players can feel as if they can never get ahead: the enemies level up with you, so it doesn't feel like progression.

The more traditional way around this is simply to divide enemies into areas, where moving to the next area means harder enemies, and it's up to the player whether to move forward now, or grind for a bit in the previous area to "level up" to make the next area easier.

An important thing to realize here is that the player's perceived difficulty is going to be a function of both their power level, and that of the enemies. If you give the player a huge power boost but give the enemies an even greater boost, the game will get harder in spite of the player's power increase. So it's a matter of what you want the difficulty curve to look like in your game. Do you want it to get progressively harder, or easier? Do you want to time the hardest points in the game to coincide with the most dramatic parts of your story arc? You can do it any which way and there's no "right" or "wrong" answer here, it comes down to your design goals and then finding the best difficulty progression to give the player the play experience you're after.

See also my blog post on progression mechanics: http://gamebalanceconcepts.wordpress.com/2010/08/18/level-7-advancement-progression-and-pacing/
> 3 votes

# Answer
I think it heavily depends on the kind of experience you want to give to the player.

As a player, I didn't like the way Oblivion handled it. One of the positive feelings as a player gaining power and abilities is the fact that you can now dominate what used to be difficult. With Oblivion and it's constantly tuned-to-your-level difficulty system, you lost the feeling that certain areas were safe and other areas were dangerous. Sure, you were fighting harder monsters, but why they showed up felt unnatural.

Personally I prefer the more traditional mechanisms. Areas have predefined difficulties, and as the player progressed areas that were previously impossible now opened up. And areas that used to be hard are now a cakewalk. It gives you a better sense of progression.

That's not to say that all dynamic difficulty systems are bad. I just think that they need to be more subtle. On Sin Episodes we did a very complicated system that didn't turn out too terrible. The gist of it was that there were a lot of little factors that played into what knobs would be adjusted as the player goes through the game. If the player got a lot of headshots, more enemies would spawn with helmets (which meant you had to shoot them in the head twice). If you were proceeding through the game quicker than our par time, the difficulty knobs got turned up. If your average health was lower than what we would like health packs would drop more often.

Unfortunately the curve wasn't linear. One of the switches we implemented was to level up the kind of guys we would spawn for difficulty. The last jump (assault rifle to machine gun) was a lot more of a jump than some of the earlier ones (pistol to assault rifle), and you could get into a situation where the designers would place two assault rifle guys and the game could spawn three machine gun guys (which is a much, much more difficult kind of fight). But compared to Oblivion, it felt like there was still progress through the course of the game as the designers were mostly in control. The dynamic difficulty system itself accounted for only adjusting it up or down a certain amount based off player performance.
> 8 votes

# Answer
I concur with Tetrad; On the one hand I am a huge fan of JRPGs and I can be a total stat whole - collecting all the best equipment making sure my uber spells are totally uber etc.. but that is a grind and the grind has to be fun. FF series does a good job at making grinding and leveling fun because they pace the level progression with the storyline very well.

However some other game types really do make it a grind and it becomes extra boring. Then there is the problem which happens constantly in FPS shooters is that unless you give the bots auto-aim headshots the game is a breeze. The player is usually way over powered - has much too much ammo - and a gigantic assortment of heavy weaponry.

One of my fav games is Guild Wars, you can only get so powerful and that's the end; but what makes it really fun is the skills system - you can only take 10 skills with you into battle - so picking out the best combination is very entertaining and testing skills builds is very fun as well. So even though there is a level cap you still have tuns to explore and new skills to unlock. The Player is never over powering and the only grind comes finding those special skills or looking for collectables and appearance oriented content.
> 1 votes

# Answer
I'd start with reading this series on balance by Sirlin, so we know what we're talking about when we say that a game is "balanced". Go ahead, i'll wait!

Done? good! if you didn't, then at least read part 1, that has the bare minimum you need.

```
A multiplayer game is balanced if a reasonably large number of options available to the player are viable--especially, but not limited to, during high-level play by expert players.

--Sirlin, December 2001

A multiplayer game is deep if it is still strategically interesting to play after expert players have studied and practiced it for years, decades, or centuries.

--Sirlin, January 2002

```

CCed here for those that TL,DRed still. While that says multiplayer games, it largely applies to single-player ones as well.

I think i'd set up a system to track player metrics; for instance, in an overhead shmup, what weapon the player favors, the types of ships he's best at killing, how much health he's lost lately, etc. and mix it up so that the players that are doing well get more tough enemies and less powerups, while players that are struggling get enemies that they can fight and better tools to do so.

I'm designing such a shmup (shameless plug: the blog for it), and i plan to do that. In short, the player will have to hunt enemy ships and peril the dangers of space to gain enough energy to fight the bosses, as well as look for upgrades for their ship. The thing to remember is that players will naturally want to progress through your game, so you can use that to drive your game forward.

The advantage of a dynamic difficulty system is that all a player has to do to get the "lower-level" areas back is that they just need to play poorly; the game will think they're having trouble and give them an easier time.

I wouldn't throw the player into an arms race by any means, but if it's a campaign type game (like a stealth shooter or something) then just sitting around while you have things to do should definitely ratchet up the pressure.
> 1 votes

# Answer
One thing you might think about here is looking at more strategy-oriented games like Civ, Starcraft and roguelikes such as Nethack and Crawl. In these games, game difficulty and player progression are not simple single-variable functions. The gameplay evolves over the course of the game.

In the early-game the goal of the player is to simply survive, progress, increase in level, get the next equipment with a +1 bonus, etc. Generally everything the player finds is better than what they currently have - whether that's a new fishing spot in Civ, or a new sword in Nethack.

The mid-game often features the player exploring the environment for gameplay options. Now, maybe they're setting up strategic forts, or collecting equipment with special effects that have situational uses, but still simply trying to survive to accumulate more stuff.

The late-game forces the player into a showdown, usually with the toughest opponents, but also with the most options at their disposal. More experienced at playing the game, now not only must the player survive, but also exploit the effective weaknesses of their opponents with the tools they've discovered and refined from mid-game forward.

You can see the same progression in Final Fantasy games - in the early game, most enemies can be killed with a simple attack, and maybe a couple healing spells as needed. Mid-game enemies begin to appear that are more difficult, but with obvious elemental or status weaknesses to exploit. Late in the game, the enemies might be practically unbeatable except for clear well-thought-out strategies based on less obvious weaknesses or AI script.

* Early game: Survival. Resource collection.
* Mid-game: Exploring the environment. Strategy building.
* Late-game: Strategy execution. Exploiting resource options.

It doesn't HAVE to be this way, but I've seen the pattern in many games from console RPGs to PC strategy games, and even handheld tower defense games.

In a game like Oblivion, the difficulty is that the player has to make choices in the strategy building in the early- and mid-game by choosing how to level up that can have drastic consequences late-game because there's no option to change that strategy later. It's how you've built your character. The same is true in Diablo 2, and many other games that allow you to select skills for your character without the ability to change them later on. A skill-based character advancement thus takes a bit more fore-thought into how individual skills can be used to build a cohesive strategy. In Diablo 2 you can see how the developers struggled with it by looking at how often they tweaked the skills over the lifetime of the game. It's easy for an inexperienced player to reach a point where their permanent strategy choices are no longer effective against the opponents they're facing. That doesn't necessarily make the game unbalanced - it simply turns the skill progression choices into part of the player's strategy, and may require several playthroughs to develop an optimal strategy.
> 0 votes

---
Tags: game-design, game-mechanics, progression
---


title: Flashing candle light

text:
# Question
Title: Flashing candle light
What is a simple way to simulate flashing candle / torch / fire light? I'm not asking about animating the flames, I'm only interested in the light surrounding the fire, similar to what this device does: https://www.youtube.com/watch?v=dPsVr4pU8Tg

# Answer
```
double nexLightIntensity(lastIntensity)
    return clamp(0,1, lastIntensity+(rand()-.3)/100)

```

adjust parameters as needed
> 2 votes

---
Tags: animation, lighting
---


# Question
Title: Pre-render bump mapped/normal mapped textures?
I saw Direct3D supports rendering bump map textures. But why is this necessary? Can't I just pre-render the already "bumped" textures and use the exported file?

The resulting image is still simple 2D, so why not go this way and avoid rendering the bump map through the game itself?

It's not just about Direct3D, just an example.

I'm very confused and would be glad if you could explain that.

# Answer
The key here would be whether the object you are bump-mapping is static or dynamic, and whether you want it to appear differently under dynamic lighting.

Exporting an already bumped texture means that lighting will be baked in, under the assumption that the light - its type, color, and direction - is static. If you then place the object with this baked lighting under a light of different properties, perhaps one that can move, it won't look quite right.

Utilizing the bump maps at runtime gives you the advantage of the perturbed normals affecting your lighting calculations in real-time. This also means that variations of bump mapping will be properly rendered depending on the viewing position.
> 2 votes

---
Tags: textures
---


title: Making specific Enemy Classes

text:
# Question
Title: Making specific Enemy Classes
So I was just looking through an old game I had made for android, and was second guessing how I was sub-classing enemy for each particular enemy in my game. My enemy class had all kinds of properties, like sprite speed size and different bools that related to the state of the enemy...etc. But then for each enemy in the game I created a sub-class from enemy, and all I did was set all those properties to a specific value. Something like this:

```
public class Ninja extends Enemy
{
     public Ninja(Vector2 pos)
     {
         super(pos);
         this.speed = 10;
         this.sprite = Content.Ninja;
         this.size = spriteSize.Medium;
         this.hitPoints = 200;
         //..etc
     }
}

```

That was basically the whole class. Looking back it seems like a waste of making a class at all, it left me with nothing else to change about that enemy, but just a convenient way to declare them. Is this common practice? I suppose it is nice to have all these stats grouped into 1 place, but it seems like a small amount of information to have for a whole class, maybe I'm just over-thinking this. Does anyone else ever do similar things in their games? Maybe it would be better to just make a static method somewhere that generates a Enemy with these stats called like `CreateNinja`, and save myself the clutter of having a whole class for it. What do you guys think?

# Answer
> 2 votes
Your idea of using a static method is probably the way to go. Give Enemy a constructor with all the values as parameters, then use static methods to make it easy to call it.

Generally, you extend a class so you can override its methods. Suppose Enemy has a `goToPoint` method that moves the object in a straight line at a constant speed. You want a Ninja to disappear from its current position and reappear at the appropriate point. *In this case* you want to override this method, and creating a Ninja class that extends Enemy makes sense.

Another point: it might be a good idea to have an Enemy object *contain* a Ninja object. The Enemy class would be written to use the Ninja (it would have to extend or implement something else, maybe a "Person" interface) to handle a lot of its methods (movement, taking damage, *doing* damage, etc.). This lets your Enemy object change it's essential nature without the rest of your program having to worry about it. Your ninja is killed? Replace the Ninja object with the DeadBody object. Your ninja finds a full suit of Medieval Eurpopean armor? (And likes it?) Replace the Ninja object with the Knight object. And you could have a Friend class that also holds a "Person" instance, so you could stuff a Ninja, Knight, or DeadBody into that as and when needed.

OOP can do an awful lot for you, but there's a big problem: it's counterintuitive. Use inheritance in the obvious way and it will tie you into knots. Put a little twist on it and it can dramatically simplify your code and put all the code that does one job in one place where it neither troubles nor is troubled by the rest of your program.

---
Tags: design-patterns, gameobject, inheritance
---


title: Batching elements

text:
# Question
Title: Batching elements
I don't understand exactly how batching works.

**What I have understood:** Batching is useful to regroup similar elements together and draw them in one draw call (performance++), currently drawing an element is 90% of the time in my application.

**How I do that:** I need to regroup elements with the same Material (Shader, Texture, …) and with his type (static or dynamic geometry).

Here is my rendering structure:

```
// Get Visibles spacials.
SpacialSet* spacials        = this->scene;
SpacialSet* visibleSpacials = this->culler->execute(spacials, this->scene->camera);

// Render the scene (this method call "draw", for each spacial)
this->renderer->render(visibleSpacials, this->scene->camera);

```

How I draw an element:

```
void Renderer::draw( Spacial* spacial )
{
    this->setGeometry(spacial->geometry);  // Bind buffers
    this->setMaterial(spacial->material);  // Send data to shader/bind textures.
    this->drawPrimitive( material->drawingMode, geometry->indicesCount);
}

```

**How I think I will do it:**

I should create a smart "Batch" class, his goal would be to create a new mesh (large VBO, pointer to textures, material) who will be a merge of all Spacials with the same apparence.

* Look current mesh and search a good batch or create a new if not found
* Merge it with previous elements
* Hide current mesh/ignore drawing
* Draw the batch/big mesh.

**My questions:**

* Does my approach look good?
* How do I manage positions per mesh?
* Do I need to update my batch each frame?
* How does it work with culling? If I have a static batch with all my sprites and 70% of sprites in this batch are out of screen, should I draw this batch ?
* Do I need to do batching before or after culling?

# Answer
I agree with petterson, but if you want to reduce amount of draw calls as well you need to use instancing.

> Does my approach look good?

If you create it once and will not move a lot of stuff around each frame, there is nothing bad in it. It all depends on you usage.

> How do I manage positions per mesh?

For this you need to identity what mesh is currently being processed. If you need to draw many same meshes (say a lot of stones, or grass) you should look into Instancing (e.g.Efficiently Drawing Multiple Instances of Geometry) there you basically have one stream which has mesh data similar to all objects(vertices, tex coords etc.) and another which **has per instance data** (like object positions in the world).

Both OpenGL and DX have support for instancing.

OpenGL (since 4.3) also has very cool function glMultiDrawIndirect (or chapter 1.3 here) which allows to do what, I think, you want - draw several **different** objects using only **one** draw call. This is "more advanced" instancing, you pass array of structures describing how many instances to draw and where to get data for them in your buffers. See the description it is quite clear.

However, you need to use same shader for all of the objects because you cannot pass "shaderid" in your per instance buffer. But you may write a generic shader and based on gl\_DrawID (passed to your shader by OpenGL, has unique value for each instance) do stuff that you want. E.g., you may construct uniform array and index it based on gl\_DrawID. You can do the same if you need different textures per instance. In this case you can create texture array and index it (note that in this case all textures have to have same size and format). You also may try to use bindless textures (OpenGL 4.4 :P).

> Do I need to update my batch each frame?

Depend on what have changed.

> How does it work with culling? If I have a static batch with all my sprites and 70% of sprites in this batch are out of screen, should I draw this batch ?

In case of simple instancing (many same objects) you will need to update per instance data and amount of instances to be drawn according to results of your occlusion test.

In case of glMultiDrawIndirect, however, you may update "count" parameter (set it to = 0 if object is not visible), but driver will, most probably, still issue an empty draw call. But you may as well update the whole array of structures containing the draw parameters.

You might be interested in GPU based occlusion, like one described here starting at slide 35.

> Do I need to do batching before or after culling?

Probably after, you need this information to construct per instance data buffers. But there is no need to modify mesh data.

I hope this was clear.
> 4 votes

# Answer
first I wouldn't copy VBO's etc at runtime. Merging meshes to larger buffers sounds like something for a offline preprocess. But you can always group your drawable meshes to minimize shader and renderstate changes. So when preparing for drawing, collect your visible meshes (i.e. after culling) and sort them by shader / material and renderstate. In your example: after culler-\>execute, sort your visibleSpacials and call the render method. If you only have a handful of differnent materials, you could create "buckets", one for each material and sort your spatials. Then the renderer only has to set material/shader once for each bucket.

hope that helps a bit to get you started
> 2 votes

---
Tags: opengl, rendering, performance, spritebatch, instancing
---


# Question
Title: Algorithm for securing a retro password system
For a game I am working on, one of the build targets is the Unity Webplayer, which does not support saving file I/O **at all**. However, as it's an action/adventure game based on *Zelda 2: The Adventure of Link*, I would like to provide my players the capability to save their game somehow.

In light of the webplayer limitations, I was going to circumvent it by creating a password system that the user could simply enter to resume where they left off. Said password would convey various things about game state, such as event flags, and picked up item flags (true to the game this is based off of, loading a game restarts the player in a pre-determined location.) This is also convenient for other modes, because the save system would be merely responsible for storing this password, as the password is a compressed version of the game's state.

My understanding is ideally, said setup would just entail creating a series of bits, represented by a complex character (such as, a digit or hexadecimal character) which could be stored in some larger value, then unpacked when entered by the user.

Of course, there's a problem, and that's security. I have to assume some less-honest player *knows* the sequence of flags and how to recreate them. From what I understand, a way to get around that is to append some sort of checksum to the bit sequence. If that checksum fails, then the system knows that the code is bogus, and to do nothing at all. Of course, I would also assume that the attacker would be aware of said checksum's existence.

**Question**: what are some good ways I would go about securing a save-state password as described above to make it less-able to be gamed by cheaters?

# Answer
> 3 votes
first get the bitstring for the standard way you described then just *encrypt it with some symmetric cypher* and chosen key

then you pack that into the password string into something the user can enter

# Answer
> 3 votes
In a little game I'm making using Unity, one of my build targets is the Web Player. I had the situation where I wanted to remember the configuration of the last launched ship, and allow the player to save various configurations by name.

As you say, standard file I/O isn't supported. However, Unity provides the Player Prefs class for storing data in both Web and native environments. This is a form of restricted file I/O as it writes to a file saved the in the users local appdata. The size of the file is limited to 1mb, but that's more than enough for the data I needed and likely plenty for the data you need too.

**I think that having the user remember a complex string of random characters to access their save data is a bad idea.** (Especially since it's likely that many of the characters are non-standard and not easily typed).

Security is still a concern, and, in this case, it's not possible to completely prevent the cheaters from modifying their data to suit. You'll always be unable to trust the client.

Further steps to secure these "save games" is to move them to a database. Users would access their saved progress with a username and password.

# Answer
> 3 votes
You can invent your own algorithm, as simple or fancy as you like. It'll be horribly broken, but it will have to suffice. You're asking for good ways to secure save-state passwords. There are none. At best, you can try to frustrate the player until he gives up.

The reason these methods don't work is that they fundamentally try to do something out of their control. Assume I'm a dishonest player. If you tell the game not to do something (e.g. start in a different state) and I say otherwise, I win. My pc does what I tell it to do. To put it a different way, you can't trust the client.

Perhaps more importantly, as long as my cheats don't harm the experience for other players, any effort you put into securing your password system goes straight to making the game less enjoyable. After all, if I didn't want to manipulate my saves, I wouldn't do it. In conclusion, unless you have a multiplayer mode to protect, this is a lost battle for a bad cause; I advise you not to fight it.

---
Tags: unity, security, savegame
---


# Question
Title: Console vulnerabilities in javascript-based game
Been toying around with a basic browser-based game for a while now, and getting deep into the vulnerabilities of client-side script. I know enough to understand that no client-side script is ever safe. Ever. But I don't fully understand to what degree.

Using, say, Chrome's developer tools, I know I can set variables at will - even `Object.freeze` and `Object.seal` can be overcome. I also know I can put in breakpoints at key points and use the console to read variable values. Now, let's say I have a function `checkStep()` that fires each time the player moves on the grid. It sends a blank ajax request, and the server returns only a boolean to signify if a random battle has started or not. If a user is able to rewrite/disable this `checkStep()`, they can effectively eliminate random battles. Is there a way to redefine or disable functions from the console command line? If you were bent on preventing this function from firing, how would you do it? Could you even do it?

---

**EDIT** Clearly I worded this poorly. Going to accept the current answer and re-post.

# Answer
You can modify any variable from the console. It's entirely possible to overwrite `checkStep` with a function that always returns false or does nothing. Even variables stored in closures can be modified, provided that you put a breakpoint in the right place.

The easiest way to prevent this is to use a minifier, but that's not going to stop people who decide to spend more than 5 minutes on trying to break the game. If you're worried about players exploiting the client vulnerabilities, you should implement an authoritative server. There's enough resources on the subject, so i don't see a point in delving deeper into it here.
> 1 votes

---
Tags: javascript, security
---


title: Animation play in turn based rpg

text:
# Question
Title: Animation play in turn based rpg
I am writing a turn based rpg game, the fighting process is sent by server which can not change by player. The data of fighting process is an array of round info. Each round info contain what happens in this round in order such as unit A attack unit B.

When client get fighting process data, it needs play animation according to this data. I am try use "action sequence"(a concept in cocos2d, which put all actions in an array, so actions will be executed in their order in that array) to implement this, for example, I make a action let unit move to a point, add it to array, then make a action of target unit be attack, add it to array... after the sequence construct complete, run it. But I found generate the action sequence code is too complex and hard to maintain.

So I want ask is there better way to do this? I also consider add timer in each unit, but it seems hard to calculate the time point of each animation playing.

# Answer
> 1 votes
You could try to segment your work to make it easier to understand and manage. Like make a RoundAction interface that holds an action and then have a RoundData class that holds all your round actions .

then simply execute an action clientside and RoundData.add(new RoundAction(){unit b attack unit a}) and then have it put it in a list in the order that you want and send that baby through. and then have the receiving client decipher the data and play it out accordingly.

---
Tags: animation, turn-based
---


# Question
Title: Calculate Distance Using Lifetime, Speed, and Time Between Ticks
I am trying to draw a line from the player to where he is facing, with the line being the distance his rockets will travel. I have ShipMissile.Speed, which is the number of pixels to move per tick, LastTick, the number of milliseconds between each call to Update(), and ShipMissile.Lifetime, which is the number of 10 ms ticks that the missile should be alive for. My current code is as follows:

```
Distance = (int)((ShipMissile.Speed * ((ShipMissile.Lifetime * 10) / LastTick)) * scale);

```

`LastTick` is generally 16.6667 (I have never seen it vary from this value during testing), and for this particular missile type `Lifetime = 200`, which is 2000 ms, `Speed = 7`, and `scale = 1` ('native' game resolution).

The missile moves by using its rotation to generate a normalized vector, then multiplies by `Speed` and `scale` each game tick.

**EDIT**: Like this:

```
Missile.Position += direction * speed * scale;

```

I am finding that the line is too short, and am wondering where the flaw in my code is (and please do not mention that I shouldn't be so dependent on frame rate or not be updating Lifetime outside of Update)? Is it even possible with my current (non optimal) setup? Thanks!

**EDIT**: I know this is kind of late, but here is a picture of what I mean (ignore the other stuff like the enemy and the score, etc):

# Answer
How short is it compared to the real length?

Does it happen if the ship is stationary?

You're casting to int. Maybe you're accumulating rounding errors in the missile moving code, especially if you do it incrementally?

Also, `direction * scale * speed` is missing `lastTick`, assuming the speed is not expressed as "distance per tick" but in terms of an actual time unit (distance per second). Which it should.

I believe this is too high level to be concerned about scale. Compute everything in "world coordinates" and worry about the scale only when you draw.
> 1 votes

---
Tags: xna, c#, fixed-timestep
---


# Question
Title: what is order of implementation of matrix transforms?
What is the meaning of Tr\*Sh\*Ro\*Sc =M ?

1. How is matrix `M` written to form the graphic transformation : 1st Sc=Scale, 2nd: R=Rotate, 3rd : Sh=Shear 4th: T=Translate ?
2. Is the matrix M above written properly in a "post multiplcative" format" T\*Sh\*R\*Sc , but executed Scale, Rotate, Shear , finaly Translate ?

# Answer
> 1 votes
The Graphics Programming community generally uses *row vectors*, that *pre-multiply* the transformation matrix as:

> v * ( T * Sh * R * Sc).

The Mathematics and Physics communities generally uses *column vectors* that *post-multiply* the transformation matrix as:

> ( T * Sh * R * Sc) * v

Both approaches are equivalent, but of course they cannot be mixed. Choose one and stick with it in order to stay out of trouble.

**Update**:

Sean Middletech's blog link above is excellent; well-written and clear, both mathematically sound and accessible by the programmer with weaker math skills. I reproduce it here in case the comment disappears at some point in the future.

# Answer
> 1 votes
You need to add imaginary parentheses to understand what's going on.

If `M = Tr*Sh*Ro*Sc` and `P' = M*P`, scale happens first because

`P' = Tr*Sh*Ro*Sc*P = Tr*Sh*Ro*(Sc*P)`

In fact,

`P' = Tr*Sh*Ro*Sc*P = Tr*Sh*Ro*(Sc*P) = Tr*Sh*(Ro*(Sc*P)) = Tr*(Sh*(Ro*(Sc*P)))`

You're composing transforms here. The result of one transform is fed into the next. Yet another way to think about it:

`P1 = Sc*P`

`P2 = Ro*P1`

`P3 = Sh*P2`

`P' = Tr*P3`

---
Tags: graphics, matrix
---


# Question
Title: How do I separate model positions from view positions in MVC?
Using MVC in games (as opposed to web apps) always confuses me when it comes to the view. How am I supposed to keep the model agnostic of how the view is presenting things?

I always end up giving the Model a `position` that holds `x` and `y` but invariably, these values end up being in units of pixels and that *feels* wrong. I can see the advantage\* of avoiding that but how am I supposed to?

This idea was suggested:

> Don't think of it in units of pixels, think of them in arbitrary distance units that just happen map to pixels at a 1:1 ratio. Oh, the resolution is half of what it was? We are now taking the x/y coordinates at 50% value for screen display, and your spells casting range is still 300 units long, which now is 150 pixels.

But those numbers conveniently work out. What do I do if the numbers divide in such a way that I get decimal places? Floating points are unsafe. I think allowing decimal places would eventually cause really weird bugs in my game.

\*It'd let me write the model once and write different views depending on the device.

# Answer
The suggestion of using arbitrary distance units is a very good one, and once it really clicks, you'll see that floating point vs fixed point is only a matter of how you represent your numbers. Using only fixed point is of course the most accurate solution, but floating point inaccuracies start to show mainly when you, for instance, exchange floats between two games that run on different hardware. Performance-wise floating point calculations are very well supported by modern CPUs and GPUs, you don't need to worry about optimisation.

Think of your view as a camera that can be pointing at any direction and zoom in and out. What the camera sees is just the model represented by some xy(z) values that map the model's position in the world. You might see terms like "world coordinates" or "world space" used in this context.

When you want to take a picture with your camera, in other words render your frame, you take the model's world position and calculate what would the position be in the current view (which always starts from 0, 0 and ends with your screen resolution's x and y components, eg. 800, 480). Let's pretend there is no rotation or zooming applied to the camera, for simplicity's and example's sake, so it boils down to knowing your camera's position in the world (using world space coordinates) and knowing the size of one unit of world distance in pixels. Then you can find out how many distance units your camera covers and which models are currently in view so that you can draw them.

Here's my artistic take on what I'm rambling about. The camera renders a portion of the world, world is 500 units wide and 500 units tall, camera instead uses pixels to draw but it maps what it sees from world units to pixels.

```
    +-----------WORLD------------(500,500)
    |                                |
    |                                |
    |                                |
    |       =====           ===      |
    |                                |
    |                                |
    |      +--CAMERA---(800,480)     |
    |      |             |           |
    |      |      @      |     ===== |
    |      |    ====     |           |
    |    (0,0)-----------+           |
  (0,0)------------------------------+

```
> 2 votes

# Answer
Surely the numbers might start out as nicely divisible but if you're doing any kind of trignonmetry, or accelleration, etc, they end up as floating point anyway quite quickly?

Thinking of distance measurements in pixels is convenient, but if you wanted to break away from that why not invent your own measurement, say 100 units = 1 pixel ? Or some other multiplication. There wouldn't be any programmatical advantage but no disdvantage either (assuming you always have to do some sort of conversion for the window size anyway). Psychologically it might help you break away from the notion that aspects of the view are infiltrating the model, and would stop you accidentally plotting using Model values as they'd immediately be seen as huge.

Incidentally assuming you do do some kind of units conversion from distances in your game to 'something' in pixels according to the screen size, then the original distance is your model unit and the 'something' is the view unit, so that's the point where you're separating the concerns.
> 0 votes

---
Tags: architecture, mvc
---


# Question
Title: Need to produce an animated texture of Water where each image tiles in all directions
I need to produce a 2D 'animated' texture of "water" for a game in which each image *tiles* in 'all' directions, much like those produced by the Caustics Generator, but with the power and flexibility of something the likes of Blender.

The final result from Caustics Generator is 32 images that are actually animated such that when the full 32 images are played in a loop they will seamlessly loop forever. They will not only loop in time, but each image also tile in all directions. This is nice, but it comes in only one flavor so to speak.

I'd like to accomplish the same thing with a Blender type tool, and I have actually gotten to the point where I generate the X number of images, but they do *not* tile in 'all' directions, nor are they slightly animated. I've tried Blender texture animations using offsets but with only limited success.

Does anyone know of how to (or of a tool) which will animate textures such that they tile in all (4) directions?

Many thanks in advance ....

# Answer
This may not be an answer, but rather an explanation.
Graphic assets like 'tile-able' tiles are usually not automatically generated, but created by an artist.
For creating them by hand (digitally painting them) there are numerous ways and none is really simple to explain and apply. They also differ greatly based on what style of graphic you want (for a game etc.).

One tutorial for creating seamless tiles (pulled off Google) for your idea, using PhotoShop: http://www.game-artist.net/forums/spotlight-articles/892-tutorial-create-tileable-texutres.html

I am not saying that there is no tool for generating (some) seamless tiles with various textures (maybe including water), but they are not widely used and one reason for it is the quality of result is rarely usable. (I'm sorry but I don't know any I can recommend.)

So one advice would be to hire an artist to make them.
Or you can use some from free galleries on web (there are some, but obviously not very good quality and not a big choice of styles) or even 'borrow' them from some old games.
> 1 votes

# Answer
I disagree with the first answer. It is possible to procedurally generate seamless images, it is described in Michael Goodfellow's blog post Part 84: Seamless Textures.

Although the article shows an example for an animated lava texture, the technique can of course be adapted for water easily.

> I ran into something on the net which said "just do it in four dimensions." You can get a seamless texture in x by sampling a circle in two dimensions, and do the same for y using the other two dimensions. So the noise is sampled with a code like
>
> ```
> for (i = 0; i < height; i++) {
>     y = 2*PI*i/height;
>     for (j = 0; j < width; j++)
>     {
>         x = 2*PI*j/width;
>         texture[i*width+j] = simplexNoise(sin(x), cos(x), sin(y), cos(y));
>     }
> }
>
> ```
> 1 votes

---
Tags: animation, textures, tiles, blender
---


# Question
Title: What's the rationale for different coordinates systems?
Could someone explain to me why Blender and other 3D modeling apps switch axes?

If I export model with Blender, then exporters do following things for the same model:

The *3DS format* applies this transform matrix:

```
     [ 1.0, 0.0, 0.0, 0.0 ],
     [ 0.0, 0.0, -1.0, 0.0 ],
     [ 0.0, 1.0, 0.0, 0.0 ],
     [ 0.0, 0.0, 0.0, 1.0 ]

```

The *Collada format* applies this transform matrix:

```
     [ 1.0, 0.0, 0.0, 0.0 ],
     [ 0.0, 0.0, -1.0, 0.0 ],
     [ 0.0, 1.0, 0.0, 0.0 ],
     [ 0.0, 0.0, 0.0, 1.0 ]

```

The *OBJ format (default)* transforms axes just like a transform matrix was applied, but *OBJ format (Forward Y, Up Z)* gives the original values that I see in Blender. The *PLY format* also does nothing and I get same values I see in Blender.

**PS**

Question was edited. I do not ask why there are different coordinate systems. I understand that.

I do not understand why Blender and other switch axis silently when model is exported.

People in comments say:

* It is easy to fix model after export
* There are people who needs that.

Actually I never seen these people and if it easy to fix then it is more easy to switch axis for those who really need that switch.

I would love to hear someone who say that axis switch is important and he/she needs in real work (not in theory)

# Answer
> 4 votes
There isn't really a universally standard coordinate system. I have worked on games and with tools, across all of them, have used almost every possible combination of systems. I think the only ones I have no worked with in practice are "+X is up" and "-X is up."

* In some cases it's easier to handle or visualize the data in a different coordinate system, and so exporters are written to transform into that system so that the end consuming product is more efficient.
* In other cases, file formats dictate a particular transformation due to various assumptions (though I don't think any of the ones you listed explicitly make such dictations).
* In yet more cases, the author of exporter just prefers data that way.

It's pretty much impossible to say *why* a particular exporter for a particular format for a particular tool operates in the way it does other than to ask the author, since it comes down to that author's preference.

I would say it's a bit odd that the importers for a particular modeling tool like Blender don't all default to exporting in Blender's coordinate system, *but* it is true that most of Blender's exporters were community-sourced (last time I used it), and so there was not necessarily a lot of design oversight on the functionality of each importer and their relative behavior.

Adjusting the transformation is generally as simple as applying your own corrective transformation on import (or writing your own exporter), so once you know it's there, it's not hard to work with.

# Answer
> 3 votes
Z going up is a standard co-ordinate system for modelling packages since the early days when 3D Studio Max was the de-facto tool used by everyone, and was an originator of this standard. It's still present and documented in modern versions, e.g.: http://docs.autodesk.com/3DSMAX/15/ENU/3ds-Max-Help/index.html?url=files/GUID-99C4C2C1-0971-48E2-8266-B911A3315554.htm,topicNumber=d30e55885

> For example, in the World coordinate system, as seen from the Front view, the X axis runs horizontally from left to right, the Y axis runs from back to front, and the Z axis runs vertically, from bottom to top.

The transforms you give in your question just convert the co-ordinate system from that used in 3D APIs (Y up, Z depth) to that used by 3D Studio Max.

There's actually no well-defined Cartesian co-ordinate system for 3D; you just get to pick which direction each of the 3 axes represents according to the requirements of your own use case. So neither standard should be seen as correct or incorrect.

So we have a situation here where in one case - 3D modelling programs - one standard was chosen, but in another - 3D APIs - a different standard was chosen, and that's just the way things evolved historically. 3D modelling programs would have evolved from plotting out a floorplan on a sheet of paper, where Z is naturally up; the designers of 3D APIs just chose differently.

It's worth adding that there is at least one modelling program that uses a Y-up system, and that this program is documented as causing confusion for users of other programs: SolidWorks.

> Users wonder why the Y-axis is pointing up and X-Z represents the top plane or table top when looking down from the top, while in some other CAD or CAM systems they may have used, the Z-axis is pointing up and X-Y represents the top plane or table top. Well, unfortunately, there are at least two defacto "standards" in the modeling industry for the orientation of the global coordinate system. I call them the Y-up and Z-up coordinate system standards. Both of these coordinate systems are right hand rule coordinate systems, they just happen to be rotated differently. So, neither of these systems is "wrong" and as they say, that is the great thing about standards...so many to choose from.

So in summary:

* There is actually no single universal standard for this.
* Different programs and use cases choose their own standard for historical reasons more than practical ones.
* Deviating from the standard that was expected to be chosen can cause confusion for the primary target audience of a program.
* In order to successfully use the output from a program in your own work, you need to know which standard it used and how to convert it to the one you're using.

That's an unfortunate state of affairs, but it's inevitable when technology from different sources evolves over an extended period of time and with no "watchdog" body to enforce conformity.

---
Tags: blender, coordinates, export
---


# Question
Title: How to generate AABB, OBB & Sphere from polygon soup
How can I generate AABB, OOBB and Sphere from a polygon soup, where the bounding volumes are defined as follows:

* AABB should be specified by min(x,y,z) max(x,y,z)
* OOBB should be specified by min(x,y,z) max(x,y,z) and a quaternion for rotation
* Sphere is specified as position(x,y,z) and radius

# Answer
Iterate through your soup and collect the following information:

* Per vertex:
    + Maximum and Minimum x, y and z values

Something like:

```
for each polygon in soup
    for each vertex in polygon
        if vertex.x > maxX
           maxX = vertex.x
        if vertex.x < minX
           minX = vertex.x

        // and so on for y and z

sphereCenter = minX + (maxX-minX)/2, minY + (maxY-minY)/2, minZ + (maxZ-minZ)/2
sphereRadius = max((maxX-minX)/2,(maxY-minY)/2,(maxZ-minZ)/2)
boundMin = minX, minY, minZ
boundMax = maxX, maxY, maxZ

```

That gives you both the bounding sphere and the AABB bounding box.

In order to get an OOBB you'll need some kind of orientation information for the soup. Then you'll have to find the center of the soup, negate the orientation information by rotating all the vertices in the soup around the common center. Now you have an axis aligned soup. You can perform the same steps as above, then rotate everything (including the eight corners of the axis aligned bounding box) back around the common center.
> 3 votes

---
Tags: 3d-meshes, geometry, optimization, data-structure
---


# Question
Title: Does HLSL implement Shader Model LOD instruction?
The DX Shader Model 5.0 has a `lod` instruction. It returns "the LOD (level of detail) that would be used for texture filtering".

Does HLSL have a built-in intrinsic that can do the same? I know I could evaluate the LOD *manually*, but I'm wondering if there's a better way.

# Answer
> 2 votes
Finally found it! It's Object.CalculateLevelOfDetail. It's not listed under Shader Model 5 Reference, but under 4.

---
Tags: directx, hlsl, level-of-detail, assembly
---


title: rendering method?

text:
# Question
Title: rendering method?
I have several questions regarding game rendering.

* What are the main rendering methods in game programming?
* Let's say we want to make a 2D game, and it should render 30 frame per second, does it mean program render whole screen every (1000/30) ms ?
* Consider Super Mario game, at the beginning, Mario is moving, but +90% of objects are static, my question is, should I render the whole screen, or only the objects that have changed or moved? isn't it illogical to render everything?

# Answer
It really depends on the platform you are targetting your renderer. On older computers (C64, NES, etc.) the computing power limited what you could do and you had to optimize everything for the best performance if you wanted to create complex games. For these older platforms it really was not always wise to just draw the whole screen every frame, only the parts that were updated.

Nowdays it's really different. With simplest 2D games, you could easily achieve hundreds if not thousands FPS, as the processing power of current hardware is not the limitation.

The most common rendering method nowdays is to draw textured polygons with OpenGL or DirectX on the screen, and it is the fastest. Another way is to blit sprites on the screen, which can be done with SDL or allegro.
> 0 votes

---
Tags: rendering
---


# Question
Title: What is the most serious limitation of Unity?
Having read this heated question about Unity vs. UDK vs. ID something, I'm curious to know: what the **repeatedly-hit, most crippling limitation(s) of Unity?**

In order to keep this question non-subjective, again, I'm talking about the top repeated offender(s) of Unity are. This is something that, as a Unity user, you really wish someone had told you about before you started using it.

I have heard from someone that Unity does not deal well with version control, since it generates a lot of binary files (which are un-diffable). This, to me, is not really crippling as I work alone.

Thoughts?

# Answer
Let me preface this that the Unity guys have been pretty good about hearing the major qualms that their community faces and eventually gets around to promising to improve things. There are also a lot of issues that only come up on certain platforms or are a matter of personal preference or specific issues of the game you're working on.

That being said:

1) Poor source control integration and large team tools. As you mentioned, lots of non-diffable binary files. The editor ignores the read only flag for scene files. The actual files you have to check in isn't immediately obvious. Some of this is being rectified in 3.5 with SVN and P4 integration. There is also promises of text based scene formats. UPDATE: The text-based scene format is now available in the Pro version of Unity. See here.

2) Slow, programmer centric UI tools. Each widget is its own draw call, which has a lot of overhead on mobile platforms. There isn't the concept of things like panels with animations and all that other fancy stuff that makes a UI feel good without rolling it yourself. There is a promise of a new UI system on the roadmap (3.6?). There are some third party tools but they're not great.

3) Really rudimentary particle editing. They're promising a new curve-based system in 3.5, though. UPDATE: This curve-based system, called Shuriken, is now available. See here.

4) You can't nest prefabs. A small issue but when you're used to working with the prefab system and all the power it provides you, it can get frustrating. This has been promised but no specific date. UPDATE: You now can nest prefabs.

5) Next to impossible to get an iOS game under the over the air limit. The binary alone is like 8 megs in a best case scenario. This isn't something that's easily fixable.

6) Null reference exceptions crash platforms that don't allow JIT compiled code. On standalone or web versions, NREs are caught. It's still an uncaught exception, but at least the application will try to continue running. On iOS, it crashes the device. You can put it in debug mode and catch some types of exceptions, but performance suffers.

7) When working on a multiplatform game, whenever you switch build targets you have to reimport everything and that takes a long time. I've worked around this by actually just having multiple copies of the project on disk. Apparently there's an imported asset server coming in 3.5.
> 33 votes

# Answer
When me and a friend evalutad Unity for a bigger project we found that one of the bigger problems was the performance with their software skinning. If I remember correcly we had something like 10 animated objects with about 1000 verts each and I got 20fps while using a midend computer... Not very good...
> 6 votes

# Answer
My number one problem *was* re version control. The solution? Just use DropBox for Unity projects. Provided you set it up correctly (i.e. pay for their "PackRat" service), it maintains revision history. It's also much easier to collaborate with designers, this way, who don't want to know about traditional version control, DropBox gives them a transparent solution. The downside is branching / merging aren't really supported in the way they are in eg. git, SVN.

For those who doubt...

> While Dropbox functions as a storage service, its focus is on synchronization and sharing. It supports revision history, so files deleted from the Dropbox folder may be recovered from any of the synced computers.\[33\]\[34\] Dropbox's version control also helps users know the history of a file they may be currently working on, enabling more than one person to edit and re-post files without complications of losing its previous form.\[35\] The version history is limited to 30 days. A paid option for unlimited version history called "Pack-Rat" is available.

See here for a solid reference from the Unity forums.

Other than that, the only thing I found annoying about Unity is that it doesn't have an application entry point in the way that C does (main()) or AS3 does (document class). But you just put your app init on an empty GameObject, not a big deal. The code flow is a bit different around this inherent structure, too, but again, nothing too hard to get to grips with.

As for the license, most people don't realise (and I am particularly referring to small indie operations and hobbyists who may not have the money to pay for a pro license and the asset manager addon) that you can do just about everything you could ever want with the basic/free edition. Really, it is not some huge barrier, the Unity team have been very generous.
> 6 votes

# Answer
I thought of another major limitation that is annoying me on a daily basis so I'll post this separately.

Unity3D wants you to edit your scripts in MonoDevelop, specifically an old version of MonoDevelop that they distribute. The "Find In Files" functionality of this version is broken, in that using it usually causes the IDE to hang, rendering it useless.

This would be a big irritation with any engine, but it is a massive irritation with Unity because it encourages a very decentralised system of separate components acting on the various game objects. But how can you find out which components access which properties if you can't even search across the various components?

EDIT: This answer was posted in 2011: the Find In Files bug was fixed some time ago, thankfully. And as commenters say, you can edit your code in other editors (though your choice is limited if you want to be able to run in the debugger).
> 6 votes

# Answer
For me the most serious limitation is in the EULA:

*"Gambling Restrictions You may not distribute or publish any Licensee Content in connection with any Gambling Activities without a separate license from Unity."*

This means that since v4.0, you cannot use Unity for games involving cash / chance, unless you or your clients are prepared to pay an additional license fee which is negotiated on a case by case basis. I.e. they see how much you are worth and tax you accordingly, with 6 figures being quoted.

More disturbing is that who knows what they will add to v5 EULA. Perhaps all social games? Perhaps all multi-player games?

Any developer using Unity is at risk of being held to ransom in a future release.
> 5 votes

# Answer
Good question. For me, the biggest problem is the GUI. I don't mind it being programmer-centric, but I do mind the awful way in which GUI objects are functions rather than an object, and that GUI handling is all stuffed into one function call which is used for rendering and for event handling, and that there's no integration with the input system (meaning clicks on GUI elements can be interpreted as clicks in the world), etc.

A secondary problem is the lack of adequate version control support (mostly because the system uses the directory layout as the project layout, which confuses the VCS when you move or rename things), but this can be worked around and isn't a problem for everybody.
> 4 votes

---
Tags: unity
---


# Question
Title: How to load and draw this *.obj correctly?
I have a loader class for `*.obj` files (called `GLModel`) which has 2 main methods -

```
public GLModel(BufferedReader ref, boolean centerit, GL gl,Texture texture)

```

which use for `*.obj` load , and

```
public void opengldraw(GL gl)

```

which use for draw it on the `gl` .

so far I succeed to load and draw objects which has single `*.obj` and a texture (such `*.png` , `*jpg` etc) .

But how could I draw an object which has multiple textures ?

For example - this object contains multiple texture , I tried to draw it with the suitable `*.obj` and one of the texture and got the same shape as the above link but its texture not exactly the same .

Can you supply me an example how to works it correctly ?

**Edit:**

I made that model available for download from here with no register .

The drawing I got so far is -

(front) -

(back) -

The loader class I talk about is -

```
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.media.opengl.GL;
import com.sun.opengl.util.texture.Texture;

// This class reads Wavefront .obj files
public class GLModel {

    private ArrayList<float[]> vertexsets;
    private ArrayList<float[]> vertexsetsnorms;
    private ArrayList<float[]> vertexsetstexs;
    private ArrayList<int[]> faces;
    private ArrayList<int[]> facestexs;
    private ArrayList<int[]> facesnorms;
    private int objectlist;
    private int numpolys;
    public float toppoint;
    public float bottompoint;
    public float leftpoint;
    public float rightpoint;
    public float farpoint;
    public float nearpoint;
    Texture texture;

    public GLModel(BufferedReader ref, boolean centerit, GL gl,
            Texture texture){

        this.texture=texture;
        vertexsets = new ArrayList<float[]>();
        vertexsetsnorms = new ArrayList<float[]>();
        vertexsetstexs = new ArrayList<float[]>();
        faces = new ArrayList<int[]>();
        facestexs = new ArrayList<int[]>();
        facesnorms = new ArrayList<int[]>();
        numpolys = 0;
        toppoint = 0.0F;
        bottompoint = 0.0F;
        leftpoint = 0.0F;
        rightpoint = 0.0F;
        farpoint = 0.0F;
        nearpoint = 0.0F;
        loadobject(ref);
        if(centerit)
            centerit();
        opengldrawtolist(gl);
        numpolys = faces.size();
        cleanup();
    }

    public GLModel(BufferedReader ref, boolean centerit, GL gl){

        vertexsets = new ArrayList<float[]>();
        vertexsetsnorms = new ArrayList<float[]>();
        vertexsetstexs = new ArrayList<float[]>();
        faces = new ArrayList<int[]>();
        facestexs = new ArrayList<int[]>();
        facesnorms = new ArrayList<int[]>();
        numpolys = 0;
        toppoint = 0.0F;
        bottompoint = 0.0F;
        leftpoint = 0.0F;
        rightpoint = 0.0F;
        farpoint = 0.0F;
        nearpoint = 0.0F;
        loadobject(ref);
        if(centerit)
            centerit();
        numpolys = faces.size();
        cleanup();
    }

    private void cleanup(){
        vertexsets.clear();
        vertexsetsnorms.clear();
        vertexsetstexs.clear();
        faces.clear();
        facestexs.clear();
        facesnorms.clear();
    }

    @SuppressWarnings("unused")
    private void loadobject(BufferedReader br){
        int linecounter = 0;
        int facecounter = 0;
        try{
            boolean firstpass = true;
            String newline;
            while((newline = br.readLine()) != null){
                linecounter++;
                if(newline.length() > 0){
                    newline = newline.trim();

                    //LOADS VERTEX COORDINATES
                    if(newline.startsWith("v ")){
                        float coords[] = new float[4];
                        newline = newline.substring(2, newline.length());
                        StringTokenizer st = new StringTokenizer(newline, " ");
                        for(int i = 0; st.hasMoreTokens(); i++)
                            coords[i] = Float.parseFloat(st.nextToken());

                        if(firstpass){
                            rightpoint = coords[0];
                            leftpoint = coords[0];
                            toppoint = coords[1];
                            bottompoint = coords[1];
                            nearpoint = coords[2];
                            farpoint = coords[2];
                            firstpass = false;
                        }
                        if(coords[0] > rightpoint)
                            rightpoint = coords[0];
                        if(coords[0] < leftpoint)
                            leftpoint = coords[0];
                        if(coords[1] > toppoint)
                            toppoint = coords[1];
                        if(coords[1] < bottompoint)
                            bottompoint = coords[1];
                        if(coords[2] > nearpoint)
                            nearpoint = coords[2];
                        if(coords[2] < farpoint)
                            farpoint = coords[2];
                        vertexsets.add(coords);
                    }
                    else

                    //LOADS VERTEX TEXTURE COORDINATES
                    if(newline.startsWith("vt")){
                        float coords[] = new float[4];
                        newline = newline.substring(3, newline.length());
                        StringTokenizer st = new StringTokenizer(newline, " ");
                        for(int i = 0; st.hasMoreTokens(); i++)
                            coords[i] = Float.parseFloat(st.nextToken());

                        vertexsetstexs.add(coords);
                    }
                    else

                    //LOADS VERTEX NORMALS COORDINATES
                    if(newline.startsWith("vn")){
                        float coords[] = new float[4];
                        newline = newline.substring(3, newline.length());
                        StringTokenizer st = new StringTokenizer(newline, " ");
                        for(int i = 0; st.hasMoreTokens(); i++)
                            coords[i] = Float.parseFloat(st.nextToken());

                        vertexsetsnorms.add(coords);
                    }
                    else

                    //LOADS FACES COORDINATES
                    if(newline.startsWith("f ")){
                        facecounter++;
                        newline = newline.substring(2, newline.length());
                        StringTokenizer st = new StringTokenizer(newline, " ");
                        int count = st.countTokens();
                        int v[] = new int[count];
                        int vt[] = new int[count];
                        int vn[] = new int[count];
                        for(int i = 0; i < count; i++){
                            char chars[] = st.nextToken().toCharArray();
                            StringBuffer sb = new StringBuffer();
                            char lc = 'x';
                            for(int k = 0; k < chars.length; k++){
                                if(chars[k] == '/' && lc == '/')
                                    sb.append('0');
                                lc = chars[k];
                                sb.append(lc);
                            }

                            StringTokenizer st2 = new StringTokenizer
                            (sb.toString(), "/");
                            int num = st2.countTokens();
                            v[i] = Integer.parseInt(st2.nextToken());
                            if(num > 1)
                                vt[i] = Integer.parseInt(st2.nextToken());
                            else
                                vt[i] = 0;
                            if(num > 2)
                                vn[i] = Integer.parseInt(st2.nextToken());
                            else
                                vn[i] = 0;
                        }

                        faces.add(v);
                        facestexs.add(vt);
                        facesnorms.add(vn);
                    }
                    else
                        //LOADS MATERIALS
                        if (newline.charAt(0) == 'm' && newline.charAt(1) == 't' && newline.charAt(2) == 'l' && newline.charAt(3) == 'l' && newline.charAt(4) == 'i' && newline.charAt(5) == 'b') {}
                        else
                            //USES MATERIALS
                            if (newline.charAt(0) == 'u' && newline.charAt(1) == 's' && newline.charAt(2) == 'e' && newline.charAt(3) == 'm' && newline.charAt(4) == 't' && newline.charAt(5) == 'l') {}
                }
            }
        }
        catch(IOException e){
            System.out.println("Failed to read file: " + br.toString());
        }
        catch(NumberFormatException e){
            System.out.println("Malformed OBJ file: " + br.toString() + "\r \r"+ e.getMessage());
        }
    }

    private void centerit(){
        float xshift = (rightpoint - leftpoint) / 2.0F;
        float yshift = (toppoint - bottompoint) / 2.0F;
        float zshift = (nearpoint - farpoint) / 2.0F;
        for(int i = 0; i < vertexsets.size(); i++){
            float coords[] = new float[4];
            coords[0] = ((float[])vertexsets.get(i))[0] - leftpoint - xshift;
            coords[1] = ((float[])vertexsets.get(i))[1] - bottompoint - yshift;
            coords[2] = ((float[])vertexsets.get(i))[2] - farpoint - zshift;
            vertexsets.set(i, coords);
        }
    }

    public float getXWidth(){
        float returnval = 0.0F;
        returnval = rightpoint - leftpoint;
        return returnval;
    }

    public float getYHeight(){
        float returnval = 0.0F;
        returnval = toppoint - bottompoint;
        return returnval;
    }

    public float getZDepth(){
        float returnval = 0.0F;
        returnval = nearpoint - farpoint;
        return returnval;
    }

    public int numpolygons(){
        return numpolys;
    }

    public void opengldrawtolist(GL gl){
        // retrieving object list
        this.objectlist = gl.glGenLists(1);

        gl.glNewList(objectlist, GL.GL_COMPILE);
        texture.enable();
        texture.bind();
        gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);
        gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
        gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
        gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);

        for (int i=0;i<faces.size();i++) {

            int[] tempfaces = (int[])(faces.get(i));
            int[] tempfacesnorms = (int[])(facesnorms.get(i));
            int[] tempfacestexs = (int[])(facestexs.get(i));

            //// Quad Begin Header ////
            int polytype;
            if (tempfaces.length == 3) {
                    polytype = GL.GL_TRIANGLES;
            } else if (tempfaces.length == 4) {
                    polytype = GL.GL_QUADS;
            } else {
                    polytype = GL.GL_POLYGON;
            }
            gl.glBegin(polytype);

            for (int w=0;w<tempfaces.length;w++) {
                if (tempfacesnorms[w] != 0) {
                    float normtempx = ((float[])vertexsetsnorms.get(tempfacesnorms[w] - 1))[0];
                    float normtempy = ((float[])vertexsetsnorms.get(tempfacesnorms[w] - 1))[1];
                    float normtempz = ((float[])vertexsetsnorms.get(tempfacesnorms[w] - 1))[2];
                    gl.glNormal3f(normtempx, normtempy, normtempz);
                }

                if (tempfacestexs[w] != 0) {
                    float textempx = ((float[])vertexsetstexs.get(tempfacestexs[w] - 1))[0];
                    float textempy = ((float[])vertexsetstexs.get(tempfacestexs[w] - 1))[1];
                    float textempz = ((float[])vertexsetstexs.get(tempfacestexs[w] - 1))[2];
                    gl.glTexCoord3f(textempx,1f-textempy,textempz);
                }

                float tempx = ((float[])vertexsets.get(tempfaces[w] - 1))[0];
                float tempy = ((float[])vertexsets.get(tempfaces[w] - 1))[1];
                float tempz = ((float[])vertexsets.get(tempfaces[w] - 1))[2];
                gl.glVertex3f(tempx,tempy,tempz);
            }
            // Quad End

            gl.glEnd();
        }

        gl.glEndList();
    }

    public void opengldraw(GL gl) {
        gl.glCallList(objectlist);
    }

    public boolean collision(float[] position) {
            return false;
    }

    public void setTexature(Texture tex) {
            this.texture = tex;
    }
}

```

The `*.obj` I used it is - `Zero.obj` (after convert it to `BufferedReader`) , the image I used it is - `AssassinBody_Dif.jpg` (after convert it to `Texture`) .

**What I looking for is - how to get completely drawing of that model using the attached `GLModel` class ?**

# Answer
> 3 votes
Wavefront obj files usually are combined with material files (.mat) which define the textures used. The meshes of a model are divided in different material groups. Each material tells you which textures to use and other information of the mesh.

In your case, there are separate meshes on the model. These meshes are head, body and hands. They all have their own textures, which you will need to apply to the correct meshes for it to look right. The meshes are most likely separated in the .obj file in mesh groups, material groups or lighting groups. You need to read them in separate mesh instances to be able to render them with different textures.

You also have encountered something called normal mapping, which is in essence saving some of the high-poly model's mesh data in textures for use with low-poly model.

---
Tags: opengl, textures, objects, jogl
---


# Question
Title: What does the identity matrix really do?
I understand that multiplying by the identity matrix is like multiplying by 1. Why would you multiply a matrix that will only contain the same result?

Also, I'm experimenting with some OpenGL code and found some very interesting things. Like for example:

When you use `setIdentity()`, the image rotates slower:

```
Matrix.setIdentityM(mProjectionMatrix, 0);
Matrix.rotateM(mProjectionMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);

```

But if you try to remove the `setIdentity()`, the image will rotate so fast... first it will rotate clockwise so fast, and then it will become slower until it stops and then it will begin to rotate counter clockwise, and then will stop again, then rotate clockwise.

I really don't understand how the identity matrix affects them despite multiplying by 1.

Can someone explain to me what's going on?

Here is the tutorial I am following.

# Answer
**TL; DR: If you multiply stuff together, you need to start with a 1**

Forget about matrices for a second, let's talk about numbers. Suppose to rotate by 90, you multiply by 90. So

`P' = 90*P`

Now you do other transforms - a rotation `R`, a translation `T`, a scale `S` and so on. So

`P' = T*R*S*P`

Since you will apply all these transforms to a lot of points, you want to precompute them into a single transform so you can apply it many times.

`M = T*R*S`

`P1' = P1*M`

`P2' = P2*M`

and so on.

Now OpenGL has the concept of the "current transform" `M`. The way you construct `M` is by multiplying stuff into it, something like this

`M = S`

`M = R*M`

`M = T*M`

So there are two operations you can do on the current transform: set it to something (`M = S`) or multiply it by something (`M = R*M`). So you'd need several sets of functions, like `setScale` and `multiplyByScale`, `setRotation` and `multiplyByRotation`, and so on.

OR you can have a single `setIdentity` that sets `M = 1`, and then you only need the functions that multiply the other transforms over it:

`M = 1`

`M = S*M`

`M = R*M`

`M = T*M`

So let's go back to your example.

```
Matrix.setIdentityM(mProjectionMatrix, 0);

```

This *sets* the current transform to identity (1)...

```
Matrix.rotateM(mProjectionMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);

```

...and this *multiplies* the current transform by a rotation matrix.

Why do things rotate "faster" if you don't reset the matrix to identity? Because you're adding a rotation on top of the rotation you already had!

First frame:

`M = 1`

`M *= 10` \<--- M is a 10 degree rotation

Second frame:

`M *= 10` \<--- M is now a 20 degree rotation, because you started from 10, not from 1!
> 13 votes

# Answer
Identity matrix does nothing. It looks like this:

```
1,0,0,0
0,1,0,0
0,0,1,0
0,0,0,1

```

And that just multiplies everything by 1 if applied to other matrices or vectors.

Read more about matrices

An identity matrix could be used as a starting point for some calculations, or if your object is at the origo of the world with no rotations, then you would apply identity world matrix to it.

The setIdentity method might be resetting your matrix back to identity matrix, and if your matrix is not declared inside the method you use it in, it is needed to be reset back to identity. Otherwise more and more rotations are applied on the matrix which results in the fast spinning.
> 5 votes

---
Tags: opengl, opengl-es, matrix
---


title: NPOT texture and video memory usage

text:
# Question
Title: NPOT texture and video memory usage
I read in this QA that NPOT will take memory as much as next POT sized texture. It means it doesn't give any benefit than POT texture with proper management. (maybe even worse because NPOT should be slower!)

Is this true? Does NPOT texture take and waste same memory like POT texture? I am considering NPOT texture for post-processing, so if it doesn't give memory space benefit, using of NPOT texture is meaningless to me.

Maybe answer can be different for each platforms. I am targeting mobile devices. Such as iPhone or Androids. Does NPOT texture takes same amount of memory on mobile GPUs?

# Answer
> 1 votes
Render targets are one of the few areas where NPOT textures don't usually have problems, because it's very unusual for a screen resolution to be a power of two.

That other article is talking mainly about non-render-target textures. I also suspect the wasted space claim isn't entirely accurate - it will depend on how clever the driver is.

For post processing it's common to have render targets that are screen sized and half screen sized as another answer to that other question says. I'd be very surprised if that was different in performance from a POT sized render target.

The difference in render target memory usage between NPOT and POT is probably not worth worrying too much about. However, if you aren't making a screen sized one then a POT size might be a good choice (e.g. for shadow maps).

If you need to save memory I'd suggest looking at textures instead of render targets. There's lots of different formats available there with different quality vs size choices.

# Answer
> 0 votes
This is not a factual answer, just some speculations.

In older days (2005 or so) when you uploaded NPOT texture to memory you could see how much VRAM it takes (as much as next POT) and mipmapping was wrong because of border colors being sampled from padding areas.

If you Google you can see there are questions from recent years about XNA and iOS6 describing these issues are still existing.

From what I know the standard describes NPOT interface, but implementations (and flaws) are vendor-specific. The balance in question is between speed and usability. Implementing proper NPOT textures will make them much slower (sampling, scaling, tiling, mipmaps, VRAM allocation, etc).

Maybe you can make an experiment yourself and see the situation now.

---
Tags: textures, opengl-es2, memory-efficiency
---


# Question
Title: LWJGL font not rendering, even with depth test and texture_2D
I'm running into an odd little problem here. I'm attempting to render a basic console over my LWJGL-based application, which should be easy enough through a decorator pattern of renderers (as in, one for the environment, and another chained to it for the text drawn on top of it). I thought that I could just use UnicodeFont (or even TrueTypeFont) for this, but I cannot seem to get it to render in the context of a 3D scene. I'm not sure what I'm missing. Here's the totality of the class (pardon the lack of cleanup):

```
static final Vector3f DRAW_COLOR = new Vector3f(1.0f, 0.2f, 0.2f);

    //CameraController is a class that manages the orientation of the camera, but not necessarily the player. For the moment, we're using FirstPersonCameraController;
    //later on, for the sake of sprite testing, it should probably be something like "ThirdPersonCameraController".
    static CameraController cameraController = new FirstPersonCameraController();

    static private UnicodeFont f = framework.util.UnicodeFontGenerator.generateUnicodeFont("Times New Roman", Font.BOLD, 24);

    @Override
    public void configure() {
        glEnable(GL_DEPTH_TEST);
        glEnable(GL_DITHER);
        glShadeModel(GL_SMOOTH);

        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        // default draw color
        glColor3f(DRAW_COLOR.getX(), DRAW_COLOR.getY(), DRAW_COLOR.getZ());

    }

    @Override
    public void setup() {
    }

    @Override
    public void renderGraphics() {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        {
            movePlayer();
            drawShapes();
            drawText();
        }
        glPopMatrix();

    }

    public static CameraController getCameraController() {
        return FirstPersonRenderingLayer.cameraController;
    }

    /**
     * Apply any overhead operations and move the player through the applicable CameraController.
     */
    private void movePlayer() {
        cameraController.lookThrough();
    }

    private void drawText() {
        glEnable(GL_TEXTURE_2D);
        GL11.glDisable(GL11.GL_DEPTH_TEST);
        f.drawString(100, 200, "Text!!! TEXT!!!!!");
        GL11.glEnable(GL_DEPTH_TEST);
        glDisable(GL_TEXTURE_2D);
    }

    private void drawShapes() {
        glColor3f(DRAW_COLOR.getX(), DRAW_COLOR.getY(), DRAW_COLOR.getZ());
        glTranslatef(0.0f, 0.0f, -2.0f);
        GLUT.glutSolidCube(0.5f);

        glColor3f(0.2f, 1.0f, 0.2f);
        glTranslatef(0.0f, 0.0f, 4.0f);
        GLUT.glutSolidTeapot(0.5f);

        glColor3f(0.2f, 0.2f, 1.0f);
        glTranslatef(2.0f, 0.0f, -2.0f);
        GLUT.glutSolidTorus(0.15, 0.50, 24, 24);

        glColor3f(0.8f, 0.8f, 0.2f);
        glTranslatef(-4.0f, 0.0f, 0.0f);
        GLUT.glutSolidSphere(0.50, 24, 24);

        glTranslatef(2.0f, 0.0f, 0.0f);

    }

    @Override
    public void terminate() {
        // TODO Auto-generated method stub

    }

```

My generateUnicodeFont() function is as follows:

```
public static UnicodeFont generateUnicodeFont(String fontName, int style, int size) {

        UnicodeFont ufont = new UnicodeFont(new java.awt.Font(fontName, style, size));
        ufont.addAsciiGlyphs();
        ColorEffect e = new ColorEffect();
        e.setColor(defaultColor);
        ufont.getEffects().add(e);
        try {
            ufont.loadGlyphs();
        } catch (SlickException ex) {
            ex.printStackTrace();
        }

        return ufont;
    }

```

As of yet, I've gotten nothing but four solid-color perfectly rendered shapes. I'm not new to Java or programming, but I am new to LWJGL, Slick, and (relatively) OpenGL. What am I missing?

# Answer
I have tried to make this work with your code, but I'm afraid I would need everything to see what else you're doing to configure OpenGL.

I've had some problems of my own with displaying text onto my 3D scene, but I think I've isolated the problem.

Once I remove the following code from my initialisation, the text was displayed correctly:

```
GLU.gluPerspective(DEFAULT_FOV, ((float) width / (float) height), 0.3f, 1000.0f); //calculate perspective

```

I don't know what this code does besides calculating a field of view and changing perspectives, but my text gets displayed without this line, and disappears when I add it again. Someone with more knowledge on this subject should be able to explain why.

If you have that function in your code, try removing it and see if it fixes it. Then we can see how we can add field of view AND display text :-)
> 0 votes

---
Tags: opengl, java, lwjgl, slick, text
---


# Question
Title: Finding tileX and tileY based on x and y (and vice versa) in isometric 2D view
I'm working on 2d Isometric game in ruby and gosu, although my problem is probably universal. My map is saved in 2d array:

```
@map_tiles[layer][y][x] = tile_id

```

Each tile is displayed on coordinates:

```
isoX = (x * @tile_width/2) - (y * @tile_height)
isoY = ((x * @tile_width/2) + (y * @tile_height)) / 2

```

So it's displayed in "diamond" like way. But I'm having a problem with calculating two things. \- Entity's tile\_x and tile\_y (on which tile is the entity positioned) when given x and y, and; \- Entity's x and y when I'm sending it's tile\_x and tile\_y.

One method is pretty much the other one reversed. I tried various methods I found over internet, but either I'm doing something wrong, or I don't understand the instructions correctly. The closest I got is:

```
@x = (tile_x * 32) - (tile_y*32)
@y = ((tile_x * 32) + (tile_y * 32) / 2)

```

for finding @x and @y based on tiles (player "teleportation" method), and

```
@tile_x = ((@x / 32) + (@y / 32)) / 2
@tile_y = ((@y / 16) - (@x / 32)) / 2

```

But they kinda don't work correctly.
\- When I send player to tile position (4, 3), he is displayed at (5, 4), and after recalculating it's tile\_x/y position, printing says it is at tiles (3,5)
\- When I send player to tile position (3, 4), he is displayed at (4, 5), and after recalculating it's tile\_x/y position, printing says it is at tiles (2,5)
\- When I send player to tile position (4, 2), he is displayed at (5, 3), and after recalculating it's tile\_x/y position, printing says it is at tiles (2,5)

So you can clearly see that something's not right here.

That's pretty much it, thanks in advance. I can post the code on github if it's neccessary, but I reckon the problem lies in what I posted.

# Answer
> 3 votes
We need to find a linear transformation between two bases of a linear space: a base for a screen coordinates and a base for game grid coordinates.

Let's define our base vectors for both cases:

Larger version

* **x** and **y** vectors are basis for screen coordinates (define pixel coordinates)
* **a** and **b** vectors are basis for game grid coordinates (define tile coordinates)
* additional **t** vector define offset of grid space origin point relative to screen space origin point in screen space coordinates.

We can describe our **x**, **y**, **a**, **b** and **t** vectors in screen space coordinates as:

```
x = [ x0, x1 ] = [  1,   0   ]
y = [ y0, y1 ] = [  0,   1   ]
a = [ a0, a1 ] = [  w/2, h/2 ]
b = [ b0, b1 ] = [ -w/2, h/2 ]
t = [ t0, t1 ]

```

We can define our screen space base to grid space base transition matrix as:

```
    | a0 b0 |   | w/2  -w/2 |
P = |       | = |           |
    | a1 b1 |   | h/2   h/2 |

```

To get screen space coordinates from grid space coordinates all we need is to multiply transition matrix P by transposed grid space vector, like so:

```
             |       gx      |
             |               |
             |       gy      |
------------------------------
| w/2  -w/2  | gx*w/2 - gy*w/2
|            |
| h/2   h/2  | gx*h/2 + gy*h/2

```

Taking into accout the base offset vector, the final screen space coordinates are:

```
s = [ sx, sy ] = [ (gx-gy) * w/2 + t0,  (gx+gy) * h/2 + t1 ]

```

To get grid space vector coordinates from screen space vector coordinates we need to find inversed P matrix ...

```
    | p00 p10 |
P = |         |
    | p01 p11 |

         1      |  p11  -p10 |
Pinv = ------ * |            |
       det(P)   | -p01   p00 |

det(P) = p00 * p11 - p10 * p01 = w/2 * h/2 + w/2 * h/2 = w * h/2

         2     |  h/2  w/2 |   |  1/w  1/h |
Pinv = ----- * |           | = |           |
        w*h    | -h/2  w/2 |   | -1/w  1/h |

```

... and multiply it by transposed screen space vector:

```
             |       sx     |
             |              |
             |       sy     |
-----------------------------
|  1/w   1/h |  sx/w + sy/h |
|            |              |
| -1/w   1/h | -sx/w + sy/h |

```

So, the final grid space vector is given as:

```
g = [ gx, gy ] = [ (sx - t0)/w + (sy - t1)/h, -(sx - t0)/w + (sy - t1)/h ]

```

There's a short c++ program to test defined transformations (exact parameters are taken from a screenshot in my post):

```
#include <iostream>
using namespace std;

const float w = 64.0f;
const float h = 32.0f;

const float t0 = 800.0f;
const float t1 = 123.0f;

void gridToScreenSpace( float gx, float gy )
{
    cout << "Grid space [" << gx << ", " << gy << "] in screen space: [";
    cout << ( gx - gy ) * w / 2.0f + t0;
    cout << ", ";
    cout << ( gx + gy ) * h / 2.0 + t1;
    cout << "]" << endl;
}

void screenToGridSpace( float sx, float sy )
{
   cout << "Screen space [" << sx << ", " << sy << "] in grid space: [";
   cout << ( sx - t0 ) / w + ( sy - t1 ) / h;
   cout << ", ";
   cout << -1.0f * ( sx - t0 ) / w + ( sy - t1 ) / h;
   cout << "]" << endl;
}

int main( )
{
    screenToGridSpace( 798, 360 );
    gridToScreenSpace( 7, 7 );

    return 0;
}

```

... and the results:

```
Screen space [798, 360] in grid space: [7.375, 7.4375]
Grid space [7, 7] in screen space: [800, 347]

```

# Answer
> 1 votes
```
isoX = (x * width/2) - (y * height)
isoY = ((x * width/2) + (y * height)) / 2

```

if that's your World coordinates of tile\[x,y\] then you have to solve system for x,y and you get tile indices like this

```
x=(2*isoY + isoX) / width
y=(2*isoY - isoX) / (2*height)

```

but those are real values so you have to floor them to get indices

---
Tags: 2d, ruby, libgosu
---