# Question
Title: Best practice for setting Effect parameters in XNA
I want to ask if there is a best practice for setting `Effect` parameters in XNA. Or in other words, what exactly happens when I call `pass.Apply()`. I can imagine multiple scenarios:

1. Each time `Apply` is called, all effect parameters are transferred to the GPU and therefor it has no real influence how often I set a parameter.
2. Each time `Apply` is called, only the parameters that got reset are transferred. So caching Set-operations that don't actually set a new value should be avoided.
3. Each time `Apply` is called, only the parameters that got changed are transferred. So caching Set-operations is useless.
4. This whole questions is bootless because no one of the mentions ways has any noteworthy impact on game performance.

So the final question: Is it useful to implement some caching of set operation like:

```
private Matrix _world;
public Matrix World
{
    get{ return _world; }
    set
    {
        if (value == world) return;
        _effect.Parameters["xWorld"].SetValue(value);
        _world = value;
    }
}

```

Thanking you in anticipation.

# Answer
> 8 votes
This all happens on the CPU side, so if caching were a useful feature, then I would *speculate* that the graphics driver would implement it itself. **Adding your own caching layer is unnecessary.**

My understanding is that whenever you set a parameter, and whenever you call `Apply`, these calls are passed to DirectX largely as-is, and in turn passed to the user-mode GPU driver as-is. The user-mode driver can then do *whatever the hell it wants*. All three of your scenarios are possible.

(Because scenario #2 is a possibility, it's probably best not to run around *deliberately* re-setting parameters that don't change.)

To be honest, I'm not really sure what a typical driver does. Mostly because it's never really come up as an issue. I've never heard of anyone having effect-parameter setting as a bottleneck. Maybe it could be, in theory. But there are so many more common things to worry about.

Certainly don't start implementing optimisations like this without measuring your performance and understanding what's going on.

Also, comparing a `Matrix` with `==` is bad voodoo. A `Matrix` is made up of `float`s, and floating-point equality comparisons are prone to failure in many cases.

And, generally speaking, the pattern `if(x != y) x = y;` is slower than simply `x = y`.

# Answer
> 4 votes
One interesting thing I found about this topic.

From msdn:

> You can use the Parameters indexed property on Effect to access any effect parameter, but this is slower than using EffectParameters. For this reason, you should create an EffectParameter for each effect parameter that changes frequently.

*and*

> Creating and assigning a EffectParameter instance for each technique in your Effect is **significantly faster** than using the Parameters indexed property on Effect.

That means that `_effect.Parameters["xWorld"].SetValue(value);` is noticeably slower than `wordlParam.SetValue(value);`

So you should probably cache parameters like this:

```
public EffectParameter wordlParam;
wordlParam = _effect.Parameters["xWorld"];

```

But I haven't found any actual benchmarks.

Sources:

http://msdn.microsoft.com/en-us/library/Microsoft.Xna.Framework.Graphics.EffectParameter%28v=xnagamestudio.40%29.aspx http://msdn.microsoft.com/en-us/library/bb976060%28v=xnagamestudio.31%29.aspx

---
Tags: xna, directx, effect
---


# Question
Title: AS3: Using a SharedObject for showing/hiding a Tutorial
Basically, I am either having trouble understanding how to use SharedObjects correctly, or I am not properly referencing a variable (from a seperate class from which it is defined) within a SharedObject, and I think the latter is my problem, although I’m not sure.

When my character dies, my game goes to a game over screen, where I create 2 variables within a SharedObject: the bestScore (user’s all-time best score in the game) and then a tutorialBoolean (which will determine if the tutorial shows up or does not in future game play). My bestScore works 100% fine, so I set that up correctly. Now the problem is, in a different class, I want to make an if statement, so that if my tutorialBoolean does not exist or is true, the tutorial runs, and if it is false, the tutorial does not run.

When I try to say

```
if (sharedObject.data.tutorialBoolean) {runTutorial()}

```

I get TypeError: Error #1009: Cannot access a property or method of a null object reference. And I am sure that it's having trouble with the sharedObject because I have created a tutorialBoolean without using SharedObjects and it works just fine. So all in all, I just want to be able to make an if statement in separate class than where my sharedObject variable is defined. I will probably have to use

```
if (sharedObject.data.tutorialBoolean == null)...

```

or

```
if (sharedObject.data.tutorialBoolean == "undefined")...

```

although I'm not really sure which one to use....neither is working at the moment. Shouldn't one of these work no matter what?...I mean if my variable is non existent surely one of these would work...

GameOver Class

```
package  {

    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.ui.Mouse;
    import flash.net.SharedObject;

    public class GameOver extends MovieClip {

        public static var sharedObject:SharedObject;
        public var finalScore:TextField;
        public var bestScore:TextField;

        public function GameOver() {

            sharedObject = SharedObject.getLocal( "smgScores" );
            sharedObject.data.tutorial1BooleanShared = false;
            sharedObject.flush();
        }

        public function onClickRestart(mouseEvent:MouseEvent):void
        {
            dispatchEvent( new NavigationEvent( NavigationEvent.RESTART ) );
        }

        public function onClickMainMenu(mouseEvent:MouseEvent):void
        {
            dispatchEvent( new NavigationEvent(NavigationEvent.MAINMENU));
        }

        public function setFinalScore( scoreValue:Number ):void
        {
            trace(sharedObject.data.bestScore);
            try
            {
                finalScore.text = scoreValue.toString();
                if ( sharedObject.data.bestScore == null )
                {
                    sharedObject.data.bestScore = scoreValue;
                }
                if ( scoreValue > sharedObject.data.bestScore )
                {
                    sharedObject.data.bestScore = scoreValue;
                }
                bestScore.text = sharedObject.data.bestScore.toString();
                sharedObject.flush();
            }
            catch( sharedObjectError:Error )
            {
                trace( "Caught this error:", sharedObjectError.name, sharedObjectError.message );
                bestScore.text = "change flash storage options";
            }
        }

}

```

and in my playScreen class I basically just want to be able to say

```
if (GameOver.sharedObject.data.tutorial1BooleanShared)
{
    runTutorial1();
}

```

But I get the error as I said above. I'm not sure if it's worth reconstructing my classes a bit and using sharedObjects in different places, or if there is a simple fix. I like the structure I have at the moment, so the latter is preferable. Thanks!

# Answer
There are several things off with your code:

Don't access the shared object from your `GameOver` screen, unless you can ensure that the object will be instantiated whenever you run `PlayScreen`. And most likely, this isn't the case.

A clean solution would be to implement a getter that instantiates the object on demand. Eg.

```
private static var _sharedObject:SharedObject;
public static function get sharedObject():SharedObject {
    if(!_sharedObject){
        _sharedObject = SharedObject.getLocal( "smgScores" );
    }
    return _sharedObject;
}

```

Then you can do:

```
GameOver.sharedObject.data.tutorial1BooleanShared = false;
GameOver.sharedObject.flush();

```

Or in your Play-screen:

```
if (GameOver.sharedObject.data.tutorial1BooleanShared){
    // do something
}

```

I doubt that the `sharedObject` getter really *belongs* to the GameOver class, but that's an architectural decision you have to make. Alternatively, you could simply discard the whole getter/accessing via another class and just do the following in your Play-screen:

```
var so:SharedObject = SharedObject.getLocal( "smgScores" );
if(so && so.data.tutorial1BooleanShared){
    // do something
}

```

Some general advice when dealing with SharedObjects: Make sure to wrap your calls dealing with the `SharedObject` in `try/catch` blocks (especially `flush` and maybe even `getLocal()`. Some people disable writing of `SharedObjects` alltogether (in the flash player preferences) and your application might crash on their system if you don't catch the error.
> 1 votes

---
Tags: actionscript-3
---


# Question
Title: The math behind Variance Shadow Maps - moments
I am not asking how to implement them (that's not particularly difficult), but I'm having a bit of trouble understanding *why* the moments used in Chebyshev's inequality (indirectly) are equal to the *depth* value and the *depth* squared respectively.

To grasp why things are like this, I tried to understand what the random variable one computes the moments for is, and what is its density (the `p(x)` in those integrals used to compute the moments). Now that one can equate the moments to the depth and depth^2 is the *magic* behind this approach, hence the key of justifying it mathematically. Can anyone please explain what `p(x)` is, and why is the first moment equal to the `depth` value? I can probably pick up from there and easily understand the second moment.

# Answer
> 2 votes
p(x) there is the blur kernel, usually a Gaussian, with which you convolve the depth and depth^2 buffers. (Or if you don't do a Gaussian blur on the VSM, then it's just the bilinear filtering kernel.) The random variable is, correspondingly, the depth of a random point in the shadow map chosen with a Gaussian distribution around the point whose shadow you're evaluating.

I think the notation in the article is misleading because it makes it appear the integrals are one-dimensional, but in fact they are two-dimensional, done over the blur kernel's support in the shadow map's UV space.

---
Tags: mathematics, shaders, rendering, shadows, shadow-mapping
---


# Question
Title: Why is it difficult to port games from consoles to PC?
PC ports of console games often come out a month or two later. Why is this?

Games are written in languages that compile on PCs too, so the game logic should compile without issue. What's holding them back then? Is it rendering code or what?

# Answer
There are a number of reasons why a PC port can take a while. (I apologize if I seem to be repeating myself somewhere; this is sort of written on the fly.)

### Adapting controls and gameplay

When you're playing on a console, this alone puts certain limitations on what you can do, since all the user has is a gamepad.

Just creating 1:1 mappings between keyboard keys and controller inputs is not always a good idea - if even possible - so sometimes it takes longer to figure out a good solution.

### Hardware abstraction/Fragmentation

When you develop for e.g. a Wii U, you know exactly how a Wii U behaves, because all Wii Us are identical. This is not true for PCs; you have many different graphics cards and CPUs, and sometimes something won't work on some of them. It takes a lot of testing to uncover these bugs, and fixing them also takes time.

If you've *never* used your engine to make a PC version, you also need to code your hardware abstraction accordingly. Some games want to support multiple DirectX versions *and* OpenGL for Linux/Mac, and all of that takes time to write if it hasn't been done before.

### Resource contention

On consoles, the game doesn't have to compete with an OS for resources, etc. - not a whole lot of stuff goes on in the background.

On a PC, you have the OS running, you have a plethora of background programs, and this all means you won't get as large a share as you were hoping for. This means you sometimes need to perform additional optimizations, especially for players on lower end systems

### Improving assets

With a console, you have a fixed target, so you write shaders, etc. to match that target.

On a PC, some graphics cards support more advanced features, and maybe you want to use a better shader for those. Well, that means you'll have to write that shader.

### Platform-specific stuff

Console SDKs may have a lot of convenient features that don't map over easily to a PC - for example, it might provide access to hardware timers or a good sound API.

Those things aren't usually available on PCs; you need to use other ways of accomplishing those things and maybe that changes how you have to abstract the platform differences.
> 47 votes

# Answer
A simple reason is that a console has a single set of hardware that is the same per console.

Your XBox, PS3 and Wii all have the same hardware as your neighbours XBox, PS3 and Wii. However your computer has a different CPU, different graphics card, different amount of RAM, in fact the whole configuration and Operating system settings, installed drivers could all be a completely unique permutation that no other person in the world has.

This is what makes it difficult to port to a PC. You need to account for every possible piece of hardware within your minimum system requirements and above. That is a tricky and difficult process to program and debug. It is very hard for developers to know every configuration to program for and near impossible to run tests on these configurations.

Once they develop it for PC there is extensive testing done in house by the devs but it also can be reliant on beta testing from users for upwards of a couple of weeks to a few months. This outsourcing of tests with beta players before the port to PC is officially released is typically why you see the gap on release dates between Consoles and PC.
> 6 votes

# Answer
Porting code to a new platform takes time. Creating a nanosecond timer for Xbox 360 (I've never developed in XNA) is going to need a different implementation than the same nanosecond timer in Linux, Mac, or Windows. Now imagine you have hundreds of these types of functions that need porting, thousands if the engine is massive enough.

It can easily take a month or two of coding to add in these different implementations for the new platforms. On top of this, you can't always use the same libraries on Xbox 360 as you can on Windows, Playstation 3, or some other platform. This means you potentially have to use a whole new library to do the same thing you did on the Xbox 360 version.

Overall, these kind of things add up into a large amount of time. Porting to a new platform is rarely easy for large AAA titles.
> 5 votes

# Answer
It has almost nothing to do with being *hard* in many cases.

It just isn't a priority. They're cranking to just barely get out the door in time. Every minute difference takes time to account for. If you can release on a few consoles or the PC by a deadline, do that first, then wrap up the ports. Release early, make more money. Generally the consoles have done better for boxed games this last generation, though it has started to shift- the new consoles might turn that around.

Also, in some case, console makers give benefits to exclusive releases, so the publisher gets a discount or some such if they release on a particular console first and other platforms later. Nothing technical about it.
> 3 votes

# Answer
Initially, games are harder to make on a console than on PC. On top of it, consoles have very different specs and different hardware between nintendo, sony and microsoft, which not only result in different performance, but also means different bottlenecking issues.

Usually, game will just tweak their engine to maximize quality and performance on each console.

When adapting to PC, there are other problems. Consoles are homogenous, meaning all consoles have the same hardware (all PS3 have the same hardware performance). When you make your game for PC, you target a minimum spec, but you also allow the user to increase quality for more powerful PCs. Games targeted for PCs are less optimized, but are easier to make for programmers.

Programming on console have one advantage, it allows programmers to maximize performance, so any console game will always perform nicely.

On a PC, it's worse, because there are many hardware out there, but granted, it's more freedom, the best resulting looking game will always be on PC, because PC is always at the bleeding edge, at a cost.

Porting a game from console to PC can be tricky, because console are designed for game performance, while PC are not, but overall, it's far easier to port a game from console to PC than the opposite, because console have very much less memory, something like 2 or 4 times less.

Changing the code to adapt to this memory restriction will mostly always mean a complete re programming.

I don't think it's hard to port a game from console to PC, it's just a matter of API. Companies and programmers who work only with consoles will have a hard time porting to PC, because they're not used to it, but also because they constantly adapt to console API, so that means their code will often answers the console compiler restriction, and not necessarily care for PC apis.

Of course, engines can be programmed to run on all consoles and PCs, once it's done it's easier, it's better than telling your programmers to port the engine to PC after they've been told it was never planned for 3 or 4 years.

TL;DR consoles are homogenous and last one console generation, PC are heterogenous, and hardware and API constantly evolves. Costs are spread between programming and hardware building, which are compromises.

One good thing would be to allow all hardware to run everything, but console prices are compensated because game companies pays console manufacturers a license, so they lock their hardware to run only game companies who pay. It's messy.
> 1 votes

---
Tags: console, pc, porting
---


# Question
Title: How to make an image bounce off the edges of the screen in Pygame?
I'm making a simple game where I bounce and image off the sides of the screen (a bit like the ball bounces in Pong) but I can't seem to the the bouncing part to work. Instead of bouncing of the edges of the screen it is going right through it. The related code is below:

```
while (mainloop):

    milliseconds = clock.tick(FPS)
    seconds = 1 / float(milliseconds)

    square.loc_x += 35 * seconds
    square.loc_y += 35 * seconds

    # I'm guessing the problem lies in the code below but I can't seem to spot it
    if square.loc_y >= 440 or square.loc_y <= 1:
        print square.loc_y >= 440 or square.loc_y <= 1
        square.loc_change_y = square.loc_change_y * -1 * seconds
    elif square.loc_x >= 600 or square.loc_x <= 1:
        print square.loc_y >= 440 or square.loc_y <= 1
    square.loc_change_x = square.loc_change_x * -1 * seconds

    square.loc_x += square.loc_change_x * seconds
    square.loc_y += square.loc_change_y * seconds

```

# Answer
You're adding positive constants (+35) to your square's location:

```
square.loc_x += 35 * seconds
square.loc_y += 35 * seconds

```

You should only be adding your square's velocity to its position, like you do in the last two lines:

```
square.loc_x += square.loc_change_x * seconds
square.loc_y += square.loc_change_y * seconds

```

That should fix your immediate issue, but I have a couple more notes:

Since it looks like you're using a variable timestep, you might find that your ball will leave the screen with enough force that it won't be able to come back into the play area in a single tick. So you will end up reversing its direction, moving back toward the play area, then since it's still out of bounds, you will re-reverse its direction and move it further out of bounds. This will cause your ball to go back and forth along the edge of the screen. To prevent this, simply split your left/right and top/bottom bound checking in to 4 statements instead of 2. If the ball goes off the top, make sure it's vertical speed is pointing down into the play area, don't just assume the ball is moving up.

And a quick thing. When you are trying to reverse the direction of the ball, you are multiplying my -1, and by the number of seconds passed (also known as delta time):

```
square.loc_change_x * -1 * seconds

```

You shouldn't need to multiply by the number of seconds that have passed. You're simply trying to reverse the ball's direction. Later on, you will apply the ball's current speed to the position using the delta time.
> 1 votes

---
Tags: pygame
---


title: Recreating this flat-shaded look

text:
# Question
Title: Recreating this flat-shaded look
I'll keep it short. How does one achieve the effect depicted in the image below? Is it feasible to do in realtime? It looks deceptively simple, but it probably isn't. Are there any keywords I can search for to get more information about programming the shaders to achieve this look? Thanks.

# Answer
> 18 votes
That does *not* appear to be using any kind of specific flat-shading approach, at all. The shading is smooth, though the projected shadows are hard-edged, and the objects are not rounded.

The specific lighting effect appears to be a combination of ambient occlusion (probably SSAO, "screen space ambient occlusion") which is what gives it that soft shadowing in crevices and regular ol' hard-edged shadow mapping and a plain lighting model (probably just Phong lighting).

An orthographic projection is being used. The only light appears to be a directional light which combined with all the objects being squared and flat is why each face has a mostly uniform shade (not any kind of special flat-shading technique).

# Answer
> 7 votes
That looks like occlusion map (corresponds to physically correct diffuse material under uniform white light) combined with directional light (going from top, creates sharp shadows).

Occlusion maps are usually made using ray-tracing techniques. They can not be generated in realtime with sufficient quality on current home computers.

Those maps are usually pre-rendered into texture. That texture can be later rendered using classic GPU rasterization techniques.

# Answer
> 4 votes
This looks like:

* All white, diffuse materials
* A strong white directional light from the upper left, with high-quality shadow filtering (the shadows are not overly soft, but they are free of aliasing)
* A blue sky (hemispherical) light, with high-quality occlusion - even in the shadows, areas more open to the sky are brighter
* There may also be global illumination (bounce lighting). It is difficult to diagnose whether there is actual GI or "simply" high-quality AO as, absent obvious color bleeding, the effects are quite subtle. But if GI is present it may still contribute subconciously to the overall impression of the image's realism, the brightness of the sunlight, etc.
* It's also worth noting that this image is perfectly antialiased, which implies lots of samples and a high quality (e.g. Gaussian) resolve filter.

In short, one could probably come close to this level of image quality in real time, using for instance high-quality PCF shadow filtering, a high-end AO technique such as HBAO or Scalable AO, and a custom MSAA resolve. It would be a lot of work and you'd need a fairly powerful GPU.

---
Tags: shaders, graphics, graphics-programming
---


title: Rotating sprite 180 deg

text:
# Question
Title: Rotating sprite 180 deg
I should say first, that I have the rotation down. Its just that I want my square to rotate exactly 180 degrees. Currently, it will rotate but it will rotate but by less each jump. So after several jumps it will be moving on one of its side. There's not much code to show but I'll show you how I'm rotating:

```
if (jumped)
        {
            roation += 0.1f;
            playerVel.Y += gravity;
        }

```

I haven't initialized rotation to anything. I've also tried using some Math functions but I just get the same result.

# Answer
> 0 votes
You need to keep track of the total rotation for each rotation. A few other variables will help you out as well. The reason you're likely getting some angle when landing is because your `5.8` degrees per update isn't exactly right, or your timestep isn't a fixed update. You can manage that with something like the following:

```
float degreesPerSecond = 180f;
float jumpRotation = 0f;

//inside update

if(jumped) {
    float rotationThisFrame = degreesPerSecond * deltaTimeInSeconds;
    jumpRotation += rotationThisFrame;
    if(jumpRotation > 180) { //check if we're done
        rotationThisFrame -= 180 - jumpRotation; //remove the extra rotation
        jumpRotation = 0; //reset total for next time
        jumped = false;
    }
    roation += rotationThisFrame;
}

```

That should make an entire jump rotation last 1 second. (untested).

# Answer
> 0 votes
Your rounding error is accumulating and overwhelming your calculation, which will **always** happen when you perform the calculations incrementally like this; that is the nature of floating point.

In order to eliminate rounding error accumulation, you must either:

* use fixed-point arithmetic; or
* recalculate the net value on each cycle instead of incrementing/decrementing an accumulator.

This is done by counting the cycle-number **cycle** and setting:

```
if (jumped) {
   cycle++;
   rotation = cycle * deltaRotation;
   playerVel.Y = cycle * gravity;
}

```

---
Tags: xna, c#, mathematics
---


# Question
Title: How do I use warble to package libgdx and ruby?
My ruby code is as follows

```
include Java

Dir[File.expand_path "#{File.dirname(__FILE__)}/../libs/\*.jar"].each { |x| require x; puts "go"}

module LibGDX
        include_package "com.badlogic.gdx"
        include_package "com.badlogic.gdx.backends.lwjgl"
        include_package "com.badlogic.gdx.graphics"
end

class Game
        include LibGDX::ApplicationListener

        @LOG = Game.java.simple_name

        def create
                LibGDX::Gdx.app.log(@LOG, "Is a thing")
        end

        def resize width, height
                LibGDX::Gdx.app.log(@LOG, "Resizing game to #{width} by #{height}")
        end

        def render
                LibGDX::Gdx.gl.glClearColor(0, 0, 0, 0)
                LibGDX::Gdx.gl.glClear(LibGDX::GL20.GL_COLOR_BUFFER_BIT)
        end

        def pause
                LibGDX::Gdx.app.log(@LOG, "Pausing")
        end

        def resume
                LibGDX::Gdx.app.log(@LOG, "resuming")
        end

    def dispose
            LibGDX::Gdx.app.log(@LOG, "disposing")
    end
end

listener = Game.new

width = 800
height = 600

useOpenglES2 = false;

game = LibGDX::LwjglApplication.new(listener, "Game", width, height, useOpenglES2)

```

If I run this through jruby it works just fine but if I package it up with warble it skips all of the Game class's initialization and tells "AL lib: alc\_cleanup: 1 device not closed" and stops.

Does anyone know the proper way to build a libGDX project with jruby and warble?

P.S. I know this seems like a very localized problem but I'm asking how to use jruby and libgdx with warble using my program as an example so... I think it's more broad then it seems... still getting used to stackexchange.

# Answer
I found out that libGDX runs on a separate thread than the one warble uses to call the jruby interpreter. All I needed to do was add an infinite while loop to the main Ruby file and it works. Even closes at the right time somehow.

If anyone knows a better way to keep a thread open until all threads are done please let me know.
> 1 votes

---
Tags: java, libgdx, ruby
---


# Question
Title: How to set tranparency for one image only in openGL ES in Android?
I code game on Android where I have several sprites.

My goal is to set `gl.glColor4f(1f, 1f, 1f, 0.2f)` a.e. transparency only for specific image. (I don't like Photoshop).

In my case its image that represents a "number" and moves up and begin to be transparent till disappear at all.

However, when I use it, I see that all sprite images are transparent or not what I want.

What I do wrong? Does my code seem right? (i'm junior in OPenGL)

Here is relevant part of code:

**Renderer**

```
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig confid) {
    gl.glEnable(GL10.GL_TEXTURE_2D);
    gl.glShadeModel(GL10.GL_SMOOTH);
    //gl.glClearColor(0.5f, 0.5f, 0.5f, 0.0f);
    //gl.glClearColor(0,0,0,0);
    gl.glClearDepthf(1.0f);
    gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
    gl.glEnable(GL10.GL_BLEND);
    gl.glDisable(GL10.GL_DEPTH_TEST);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
    gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,                /*GL10.GL_REPLACE*/ GL10.GL_MODULATE);
}

```

**\[text sprite image\]**

```
gl.glPushMatrix();
try {
    float transx = ...'
    float transy = ...;

    gl.glTranslatef(transx, transy, 0.0f);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, floatBufferArray[mFrame]);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    gl.glColor4f(1f, 1f, 1f, 0.2f); // <---- alpha 0.2f
} catch (NullPointerException e) {
   Log.e("Fess", e.getMessage());
}
gl.glPopMatrix();

```

**\[other sprite images with alpha 1f\]**

```
gl.glPushMatrix();
try {
    float transx = ...'
    float transy = ...;

    gl.glTranslatef(transx, transy, 0.0f);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, floatBufferArray[mFrame]);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    gl.glColor4f(1f, 1f, 1f, 1f);
} catch (NullPointerException e) {
   Log.e("Fess", e.getMessage());
}
gl.glPopMatrix();

```

and this is how im load them:

```
public void loadTextures(GL10 gl, Context context) {
    Log.e(LOG_TAG, "ExplosionSprite :: loadTextures");

    mFrame = 0;

    InputStream is;
    Bitmap bitmap;
    is = context.getResources().openRawResource(DRAW_SOURCE);

    bitmap = BitmapFactory.decodeStream(is);
    try {
        is.close();
        is = null;
    } catch (IOException e) {
    }

    gl.glGenTextures(TEXTURE_COUNT, textures, 0);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();

}

```

Thank you

# Answer
Have you tried calling glColor4f(1,1,1,1) after you have drawn the image? You have to do that to reset the drawing color back to solid.

EDIT: Now that I read your code more carefully, it seems that you set the color only AFTER you have drawn the sprites. Call the glColor function before glDrawArrays, and it should work.
> 1 votes

---
Tags: android, opengl-es
---


# Question
Title: OpenGL draws draw buffers in wrong order
I'm trying to implement deferred rendering and for now I only have diffuse, normal (in world space) and position (in world space) as textures inside the GBuffer. I create the GBuffer like this:

```
void GBuffer::Initialize(unsigned int width, unsigned int height)
{
    glGenTextures(1,&_diffuseTexture);
    glGenTextures(1,&_worldPosTexture);
    glGenTextures(1,&_normalTexture);

    auto textureSetup = [](unsigned int width, unsigned int height) {
        glTexImage2D(GL_TEXTURE_2D,0,GL_RGB32F,width,height,0,GL_RGB,GL_FLOAT,0);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    };

    glBindTexture(GL_TEXTURE_2D,_diffuseTexture);
    textureSetup(resolutionX,resolutionY);
    glBindTexture(GL_TEXTURE_2D,_worldPosTexture);
    textureSetup(resolutionX,resolutionY);
    glBindTexture(GL_TEXTURE_2D,_normalTexture);
    textureSetup(resolutionX,resolutionY);

    glGenFramebuffers(1,&_framebuffer);
    glBindFramebuffer(GL_FRAMEBUFFER,_framebuffer);

    glGenRenderbuffers(1,&_depthBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER,_depthBuffer);
    glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH_COMPONENT,width,height);

    //attach the depth buffer as well as the textures to the framebuffer
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,_depthBuffer);
    glFramebufferTexture(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,_diffuseTexture,0);
    glFramebufferTexture(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT1,_worldPosTexture,0);
    glFramebufferTexture(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT2,_normalTexture,0);

    GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
    glDrawBuffers(3,drawBuffers);

    glBindFramebuffer(GL_FRAMEBUFFER,0);

}

```

As you can see, at the bottom of the function glDrawBuffers is called so that (at least intentionally) first the diffuse texture is drawn to, then the position texture, and then the normal texture.

The shaders for them look like this (here worldViewProjection and world matrices are attributes because I use them in instanced rendering. They're actually only advanced once per instance of the mesh that I draw):

Vertex:

```
#version 430

layout(location = 0) in vec4 position;
layout(location = 1) in vec4 vertexColor;
layout(location = 2) in vec4 vertexNormal;
layout(location = 3) in mat4 worldViewProjection;
layout(location = 7) in mat4 world;

smooth out vec3 diffuse;
smooth out vec3 worldPosition;
smooth out vec3 normal;

void main()
{
    gl_Position = worldViewProjection * position;
    worldPosition = (world * position).xyz;
    normal = world * vertexNormal;
    diffuse = vertexColor;
}

```

Fragment:

```
#version 430

smooth in vec3 diffuse;
smooth in vec3 worldPosition;
smooth in vec3 normal;

out vec3 outDiffuse;
out vec3 outWorldpos;
out vec3 outNormal;

void main()
{
    outDiffuse = diffuse.xyz;
    outWorldpos = worldPosition;
    outNormal = normalize(normal);
}

```

During rendering I do nothing but

```
glBindFramebuffer(GL_FRAMEBUFFER,gbuffer->_framebuffer);

```

before I start rendering, then draw the geometry using the shader program.

The rendered results look correct, the only problem is that the program draws results of the position into the normal texture, and vice versa (weirdly enough, the diffuse texture is correctly drawn to).

This is a screenshot of the test draw, where I expect bottom left to be diffuse texture (correct), bottom right position texture and top left normal texture (those two are switched):

Just to make sure that I don't just draw them on the screen reversed, this is how I actually display the textures:

```
void sun::graphics::DrawTexture(GLuint texture,  unsigned int posX, unsigned int posY , unsigned int width , unsigned int height )
{
    if(!inited2)
    {
        glGenBuffers(1,&buffer2);
        inited2 = true;

        /*glGenSamplers(1, &sampler);
        glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);*/
    }
    glViewport(posX,posY,width,height);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,texture);

    FullscreenTextureShader->Bind();
    GLuint loc = glGetUniformLocation(FullscreenTextureShader->_program,"tex");
    glUniform1i(loc,0);

    float vertices[] =
    {
        -1.0f,1.0f,-1.0f,1.0f,
        1.0f,1.0f,-1.0f,1.0f,
        1.0f,-1.0f,-1.0f,1.0f,
        1.0f,-1.0f,-1.0f,1.0f,
        -1.0f,-1.0f,-1.0f,1.0f,
        -1.0f,1.0f,-1.0f,1.0f,
    };
    glBindBuffer(GL_ARRAY_BUFFER,buffer2);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STREAM_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0,4,GL_FLOAT,GL_FALSE,0,0);

    glDrawArrays(GL_TRIANGLES,0,6);

    glDisableVertexAttribArray(0);

    FullscreenTextureShader->Unbind();
}

```

and call them like this (never mind attribute access, I just made everything public for debugging comfort, will switch to private soon):

```
DrawTexture(renderer->_gbuffer._diffuseTexture,0,0,400,300); //bottom left
DrawTexture(renderer->_gbuffer._worldPosTexture,400,0,400,300); //bottom right
DrawTexture(renderer->_gbuffer._normalTexture,0,300,400,300); //top left

```

Where could the problem be here?

edit: to confirm that there's nothing wrong with how it's displayed on the screen, if I disable two of those calls and only draw, e.g. worldPosTexture, it does indeed show up with the contents of what should be in the normal texture.

Also, if I reverse the last two elements in the array that I give to glDrawBuffers, it's indeed drawn correctly.

# Answer
```
out vec3 outDiffuse;
out vec3 outWorldpos;
out vec3 outNormal;

```

Remember how you did this in your vertex shader?

```
layout(location = 0) in vec4 position;

```

The `location` qualifier specified which attribute the `position` comes from. Fragment shader outputs have the same concept. Each output goes to a location; if you don't *explicitly specify* the location, then the shader will arbitrarily assign them. And no, the shader is *not* required to start from zero and assign them sequentially.

So you should use the same syntax in your fragment shader. You set up your draw buffers like this:

```
GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};

```

So you need to assign the locations appropriately. Given the names of the textures you used, you should use the following:

```
layout(location = 0) out vec3 outDiffuse;
layout(location = 1) out vec3 outWorldpos;
layout(location = 2) out vec3 outNormal;

```

Note that the locations are *not* the `GL_COLOR_ATTACHMENT#` numbers. They're the *indices into the draw buffers array*. So 0 in this case means `drawBuffers[0]`. It only refers to `GL_COLOR_ATTACHMENT0` because that's what is in `drawBuffers[0]`. You could just as easily set `GL_COLOR_ATTACHMENT1` to index 0; the `outDiffuse` would then be written to `GL_COLOR_ATTACHMENT1`
> 4 votes

# Answer
I can see that your fragment shader is the culprit. The problem is in the way you are storing the output of the fragment shader in the Gbuffer.

This is how I do it, and how it works for me flawlessly:

```
out vec4 GBuffer[3]; // how I declare it
...
GBuffer[0] = diffuse; // and how I set them
GBuffer[1] = normal;
GBuffer[2] = position;

```
> -1 votes

---
Tags: opengl
---


# Question
Title: How to properly translate a point by a matrix?
I wrote a simple Matrix class and it has methods like rotate, translate, etc. They all seem to be working, but whenever I try to translate a rectangle using the matrix, the translation axis seem to be flipped. It doesn't appear to be the fault of the matrix, however, because if I do `matrix.translate(50, 0)`, It gives me a matrix that looks like this:

$$ \begin{bmatrix} 1 & 0 & 50 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} $$ As expected. It appears that I am applying the matrix incorrectly instead. I am using this code to get the resulting X/Y axis for each point in the rectangle:

```
pointX = x * mat.row1.x + y * mat.row1.y + mat.translateX
pointY = x * mat.row2.x + y * mat.row2.y + mat.translateY

```

But when I call `translate(50, 0)`, I get this:

Instead of this:

As you would expect. What am I doing wrong? Am I incorrectly calculating the points?

# Answer
I would expect your matrix multiplication code to look like

$$ \begin{bmatrix} x & y & 1 \\ \end{bmatrix} * \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 50 & 0 & 1 \end{bmatrix} = \begin{bmatrix} x+50 & y & 1 \\ \end{bmatrix} $$ This is because matrix multiplication is defined so that you go by row in the first operand and by column in the second operand.

Here's the relevant formula from wikipedia, although you should consider reviewing the whole page: $$ (AB)\_{ij}=\sum\_{k=1}^m i^2 =A\_{ik}B\_{kj} $$ As LuisW points out in the comments, this is merely a row- vs column- major issue. As an example, your matrix would be just fine this way:

$$ \begin{bmatrix} 1 & 0 & 50 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} * \begin{bmatrix} x \\ y \\ 1 \end{bmatrix} = \begin{bmatrix} x+50 \\ y \\ 1 \end{bmatrix} $$

But that is apparently not how you are multiplying it.
> 6 votes

# Answer
Here is an excerpt for the integer Matrix struct I use, for comparison:

```
/// <summary>Row-major order representation of an immutable integer matrix.</summary>
/// <remarks> Represents Points as row vectors and planes as column vectors.
/// This representation is standard for computer graphics, though opposite
/// to standard mathematical (and physics) representation, and treats
/// row vectors as contravariant and column vectors as covariant.</remarks>
public struct IntMatrix2D : IEquatable<IntMatrix2D> {

  static IntMatrix2D TransposeMatrix = new IntMatrix2D(0,1, 1,0);
  public static IntMatrix2D Transpose(IntMatrix2D matrix) {
    return matrix * TransposeMatrix;
  }

  /// <summary>Get the x-scale component.</summary>
  public int M11 { get; private set; }
  /// <summary>Get the X-shear component</summary>
  public int M12 { get; private set; }
  /// <summary>Get the y-shear component</summary>
  public int M21 { get; private set; }
  /// <summary>Get the Y-scale component</summary>
  public int M22 { get; private set; }
  /// <summary>Get the x-translation component</summary>
  public int M31 { get; private set; }
  /// <summary>Get the y-translationcomponent</summary>
  public int M32 { get; private set; }
  /// <summary>Ge the normalization component</summary>
  public int M33 { get; private set; }
  /// <summary>Get the identity matrix.</summary>
  public static readonly IntMatrix2D Identity = new IntMatrix2D(1,0,0,1,0,0);

  #region Constructors
  /// <summary> Initializes a new <code>IntMatrix2D</code> as the translation defined by the vector v.</summary>
  /// <param name="vector">the translation vector</param>
public IntMatrix2D(IntVector2D vector)  : this(1,0, 0,1, vector.X,vector.Y, 1) {}
  /// <summary> Initializes a new <code>IntMatrix2D</code> as the translation (dx,dy).</summary>
  /// <param name="dx">X-translate component</param>
  /// <param name="dy">Y-translate component</param>
public IntMatrix2D(int dx, int dy)  : this(1,0, 0,1, dx,dy,1) {}
  /// <summary> Initialies a new <code>IntMatrix2D</code> with a rotation.</summary>
  /// <param name="m11">X-scale component.</param>
  /// <param name="m12">Y-shear component</param>
  /// <param name="m21">X-shear component</param>
  /// <param name="m22">Y-scale component</param>
  public IntMatrix2D(int m11, int m12, int m21, int m22) : this(m11,m12, m21,m22, 0,0, 1) {}
  /// <summary>Copy Constructor for a new <code>IntMatrix2D</code>.</summary>
  /// <param name="m">Source IntegerMatrix</param>
  public IntMatrix2D(IntMatrix2D m) : this(m.M11,m.M21, m.M12,m.M22, m.M31,m.M32, m.M33) { }
  /// <summary>Initializes a new fully-specificed <code>IntMatrix2D</code> .</summary>
  /// <param name="m11">X-scale component.</param>
  /// <param name="m12">Y-shear component</param>
  /// <param name="m21">X-shear component</param>
  /// <param name="m22">Y-scale component</param>
  /// <param name="dx">X-translate component</param>
  /// <param name="dy">Y-translate component</param>
  public IntMatrix2D(int m11, int m12, int m21, int m22, int dx, int dy)
  : this(m11,m12,m21,m22,dx,dy,1) {}
  /// <summary>Initializes a new fully-specificed non-normed <code>IntMatrix2D</code>.</summary>
  /// <param name="m11">X-scale component.</param>
  /// <param name="m12">Y-shear component</param>
  /// <param name="m21">X-shear component</param>
  /// <param name="m22">Y-scale component</param>
  /// <param name="dx">X-translate component</param>
  /// <param name="dy">Y-translate component</param>
  /// <param name="norm">Normalization component</param>
  public IntMatrix2D(int m11, int m12, int m21, int m22, int dx, int dy, int norm) : this() {
    M11 = m11;  M12 = m12;
    M21 = m21;  M22 = m22;
    M31 = dx;   M32 = dy;   M33 = norm;
  }
  #endregion

  #region operators
  /// <summary> Vector application.</summary>
  /// <param name="v">IntVector2D to be transformed.</param>
  /// <param name="m">IntMatrix2D to be applied.</param>
  /// <returns>New IntVector2D resulting from application of this matrix to vector v.</returns>
  public static IntVector2D operator * (IntVector2D v, IntMatrix2D m) {
    return new IntVector2D (
      v.X * m.M11 + v.Y * m.M21 + m.M31,   v.X * m.M12 + v.Y * m.M22 + m.M32,  v.W * m.M33
    ).Normalize();
  }
  /// <summary>Matrix multiplication.</summary>
  /// <param name="m1">Prepended transformation.</param>
  /// <param name="m2">Appended transformation.</param>
  /// <returns></returns>
  public static IntMatrix2D operator * (IntMatrix2D m1, IntMatrix2D m2) {
    return new IntMatrix2D (
      m1.M11*m2.M11 + m1.M12*m2.M21,           m1.M11*m2.M12 + m1.M12*m2.M22,
      m1.M21*m2.M11 + m1.M22*m2.M21,           m1.M21*m2.M12 + m1.M22*m2.M22,
      m1.M31*m2.M11 + m1.M32*m2.M21 + m2.M31,  m1.M31*m2.M12 + m1.M32*m2.M22 + m2.M32,  m1.M33 * m2.M33
    );
  }
}

```

where the `IntVector2D` struct is similar.

Complete code project available.
> 0 votes

---
Tags: matrix, axis
---


# Question
Title: Roguelike corridor creation; Connecting rooms
I have a simple Tile\[,\] that I populate with Rooms. Now I need to connect the rooms with a single tile wide corridor. At first I used A\* to hook up the rooms but that, of course, get's the best path from tile to tile, but that's a bit boring.

So I decided to roll my own path walker, which very inefficiently get's me the same paths currently as A\* except for some reason it never reaches the end tile. I was planning to add a randomness to it by adding a random chance to go in a random direction for a few steps before going back to it's route.

```
public static List<Tile> GetPath( Room startRoom, Room endRoom, Tile[,] map, int drunkenStep )
{
    //Select random tile from the wall list
    Tile startTile = startRoom.wallTiles[ UnityEngine.Random.Range( 0, startRoom.wallTiles.Count) ];
    Tile endTile = endRoom.wallTiles[   UnityEngine.Random.Range( 0, endRoom.wallTiles.Count) ];
    startRoom.wallTiles.Remove( startTile );
    endRoom.wallTiles.Remove( endTile );

    //Make it a floor tile
    startTile.type = RoomType.FLOOR;
    endTile.type = RoomType.FLOOR;
    startRoom.floorTiles.Add( startTile );
    endRoom.floorTiles.Add( endTile);

    //Add the start tile to the list
    Tile selectedTile = startTile;
    List<Tile> path = new List<Tile>();
    path.Add( selectedTile );

    List<Tile> tilesToCheck = new List<Tile>();
    do
    {
        //loop four times for each adjascent tile
        for(int i = 0; i < 4; i++)
        {
            int x = selectedTile.x + Convert.ToInt32( selectedTile.adj[i].x );
            int y = selectedTile.z + Convert.ToInt32( selectedTile.adj[i].y ); //x/y because 2D map. Tile y is for height displacement
            //Check if we are within bounds
            if( x < 0 || x > map.GetLength(0) || y < 0 || y > map.GetLength(1) ) continue;
            //We cant back track through a room and only use tiles that aren't set yet
            if( map[x,y].type == RoomType.NONE || (map[x,y].type == RoomType.FLOOR && map[x,y].roomId == -1) ) tilesToCheck.Add( map[x,y] );
        }

        float minDist = Mathf.Infinity;
        Vector2 endPos = new Vector2( endTile.x, endTile.z );
        foreach (Tile t in tilesToCheck)
        {
            float dist = Vector2.Distance( new Vector2( t.x, t.z), endPos);
            if (dist < minDist)
            {
                selectedTile = t;
                minDist = dist;
            }
        }

        path.Add(selectedTile);
        tilesToCheck.Clear();

    } while( selectedTile != endTile );

    return path;
}

```

Right now this never resolves and i'm not entirely sure why it doesnt reach the end tile. So my question is:

**What is going wrong and what should I do to get straighter corridors and maybe some drunken randomness; maybe have a path loop around a little bit**

Thanks for your time!

# Answer
> 1 votes
Your pathfinding would reach the room if this were true (when `map[x,y]` is `endTile`)

```
(map[x,y].type == RoomType.NONE ||
(map[x,y].type == RoomType.FLOOR && map[x,y].roomId == -1) )

```

You know the `type` property is `RoomType.FLOOR`, because you set it explicitly. So, the `endTile.roomId` is not -1.

# Answer
> 2 votes
Do you only want straight 1 wide corridors? If you're willing to have some more 'organic' paths I like using Drunk Walk to simulate some paths being natural fissures, or created by a burrowing/digging entity.

**Drunk Walk:** Given your start tile and end tile for the path step in the direction of the end tile 50% of the time otherwise move in a random direction. Every time you move into a Wall tile replace it with a Floor. The weights on the various directions can be changed, also you can have a preference to move in the one direction for a couple of steps.

**Random-Path Generation:** The other idea I like is to randomly generate a set of paths irrespective of your room locations (easy as picking two random points and drawing a line to connect them, repeat) then do pass to check that all your rooms are connected and if not either drop down more random paths, or apply your current algorithm.

---
Tags: path-finding, procedural-generation, grid, roguelikes
---


# Question
Title: Box2d : How to apply a force to keep swinging from left to right?
i'm losing myself in this...

**Situation:** Working on a game in cocos2d with box2d and I have a ropejoint between one fixed body and one dynamic body.

When I drop the dynamic body is swings from left to right and then from right to left due to the gravity in the world.

**The problem:** The swings are getting shorter and shorter till finally the dynamic body hangs still beneath the fixed body. This is normal behavior but I need it to keep swinging.

**My thoughts:** I think I need to apply a tangential force to the ropejoint in the direction of the swinging but how to do this is a mystery for now :)

*EDIT 1* The swinging does not have to be in perfect balance, it just can't slowly die.

# Answer
> 2 votes
Add an impulse to the dynamic body at a regular interval. You can apply it in the direction of movement when the dynamic body is (almost) directly beneath the fixed body. But the impulse should be timed, not based on position.

You might be able to calculate the interval by analyzing your system as an ideal pendulum to determine its frequency...but there's no guarantee that number will be correct in box2d. You should experiment with different values that are roughly the period of oscillation of your swing. If you get close, the deviation from an ideal pendulum will provide some negative feedback to the system. Then you'll get a regular, persistent swing.

# Answer
> 1 votes
If you have any other bodies that will interact with your body attached to the rope or even the rope itself during your game (eg. a collision mid-swing), then it will be a really hard task to find the forces necessary to restore the swinging motion after collisions have been resolved.

And if you can ensure that there will be no interaction with other dynamic bodies, why use a physics-engine for the swinging animation in the first place? You could just as well make a looping animation?

If I had to build this with Box2D, I'd probably add a "Revolute Joint" at the top of the rope and enable its motor. Then use the motor to apply a rotational force to the rope. My first try would be a sine force, or just enable the motor in specific intervals/impulses. But you would have to experiment with the setup to see which values work best.

---
Tags: box2d, cocos2d
---


# Question
Title: Using python as a controller in Blender Game Engine
I'm trying to learn how to use BGE, and one of the things I'd like to do is programatically move the cube using a python script. I added a controller but no luck. See screenshot. I'm trying to run the python script at the top of the page, all it's supposed to do is move the cube a little. It works if I click "Run Script" but I want it to happen automatically when BGE is running. What am I missing?

https://i.stack.imgur.com/WpmUm.png

# Answer
As well as using bge (the blender game engine module) instead of bpy, you want to set the true or false level triggering to get the always sensor to repeatedly call the python script. That is the buttons to the side of the Freq setting which will determine how often it will be triggered.

```
import bge
bge.logic.getCurrentController().owner.localPosition.z += 0.01

```

would be the replacement code for what you have. You may find that this will be better joined with a keyboard sensor to move the object when you press a key.
> 1 votes

---
Tags: blender-game-engine
---


# Question
Title: free web library for leaderboards / achievements
I would like to know if there is any free leaderboard libraries for web games developed in HTML5/JS (as openfeint is for iPhone, Android)

I found this http://www.appmobi.com/, but it seems the leaderboard APIs which are in BETA is not free.

# Answer
> 3 votes
Clay.io does this as well:

Info Page: http://clay.io/development-tools
Documentation: http://clay.io/docs/leaderboards

Basic implementation is:

```
var leaderboard = new Clay.Leaderboard( { id: 'some-id' } );
leaderboard.post( { score: 500 } ); // Post a score of 500
leaderboard.show(); // Show the list of high scores

```

Of course, it's very customizable - that's just what's required to get it going.

# Answer
> 3 votes
There is a new open source initiative by the creators of Open Feint. It's called Open Kit (http://openkit.io/) and it's open and free as they come.

# Answer
> 2 votes
I would point you to http://tapjs.com

Been thinking of implementing this on a project of mine. Haven't done a lot of research though. Have a look.

# Answer
> 2 votes
I integrated playtomic framework with my project. Its very simple to use. Doc can be found at: https://playtomic.com/api/html5

# Answer
> 1 votes
i suggest for better leaderboard integration use ShepHertz App42 ..this is not free but 1 million call are free ,that is sufficient for starting app developers. leaderboard

---
Tags: html5, leaderboards
---


# Question
Title: Picking problem with rotated view matrix
I have picking code that works, if my view matrix has no rotation (only translation). Now If I rotate my camera, picking goes to hell.

I cant find whats wrong

My code:

```
/*-----------------------------------------------------------
Function:   GetViewportSystem
Returns:
    viewportCoordSystem

Get viewport coordinate system (only for reading)
Forward ray goes through origin
d = distance |camera, projection plane|
cameraPos = position of camera in World Space
lookAt = camera target in World Space
-------------------------------------------------------------*/
ViewportCoordSystem Camera::GetViewportSystem() const
{
    ViewportCoordSystem viewportCoord;
    viewportCoord.w = this->cameraPos;
    viewportCoord.w = this->cameraPos - this->lookAt;
    viewportCoord.w.Normalize();

    viewportCoord.u = MyMath::Vector3::Cross(viewportCoord.w, MyMath::Vector3::UnitY());

    viewportCoord.v = MyMath::Vector3::Cross(viewportCoord.u, viewportCoord.w);

    float d = (this->viewport.Height * 0.5f) * (1.0f / tanf(this->viewport.fov * 0.5f));

    viewportCoord.origin = this->cameraPos;
    viewportCoord.origin -= d * viewportCoord.w;

    return viewportCoord;
}

/*-----------------------------------------------------------
Function:   MapViewport2Dto3D
Parametrs:
    [in] viewportSystem - cameras viewport coordinate system
    [in] point - 2D point on image
Returns:
    3D mapped point in space

Map 2D image point to 3D space
Info about mappind 2D to 3D: http://meatfighter.com/juggler/
-------------------------------------------------------------*/
MyMath::Vector3 Camera::MapViewport2Dto3D(const ViewportCoordSystem & viewportSystem, const MyMath::Vector2 & point) const
{
    MyMath::Vector3 res = viewportSystem.origin;
    res += (point.X - this->viewport.Width * 0.5f) * viewportSystem.u;
    res += (this->viewport.Height * 0.5f - point.Y) * viewportSystem.v;

    return res;
}

```

And calculating ray (x, y are mouse coordinates within screen, my world is scaled, so I amd trasnforming ray and origin to transformed world)

```
    ViewportCoordSystem vpSystem = this->camera->GetViewportSystem();
    MyMath::Vector3 pos = this->camera->MapViewport2Dto3D(vpSystem, MyMath::Vector2(x, y));

    float inverseScale = 1.0f / scale;
    MyMath::Matrix4x4 worldInv = MyMath::Matrix4x4::Scaling(inverseScale, inverseScale, inverseScale);

    this->ray.dir = pos - this->camera->GetPosition();
    this->ray.dir = MyMath::Vector3::TransformCoordinate(this->ray.dir, worldInv); //transform ray to object space
    this->ray.dir.Normalize();

    this->ray.origin = this->camera->GetPosition();
    this->ray.origin = MyMath::Vector3::TransformCoordinate(this->ray.origin, worldInv); //transform ray to object space

```

# Answer
> 1 votes
`viewportCoord.u` and `viewportCoord.v` will not come out unit length when the view is rotated. You might need (or it may help) to normalize `.u`

---
Tags: mathematics, transformation, picking
---


title: Rendering lightmaps at runtime

text:
# Question
Title: Rendering lightmaps at runtime
I'm creating a procedural terrain system for Unity. And I'm looking for ways to efficiently cast self-shadows on it. If it wasn't procedural, I could simply bake a lightmap using Beast. But, I can't because the terrain mesh is created at runtime. What kind of methods can be done for this, I'm sure it has been done before. If possible, I'm looking for a solution that works for non-pro.

I was thinking that maybe some kind of onetime ray-tracing method might be a solution.

# Answer
There isn't a way to bake lightmaps at runtime using Beast (Unity's lightmap engine). Beast only works in the editor. However, you can run editor functions from the command line using `-executeMethod` so if your procedural level was XML you could send it to a server, run an editor method similar to this (javascript):

```
static void PerformBuild () {
    Lightmapping.Bake()
}

```

I didn't compile this yet, so it might not be all the code neccesary. Here are a few links that I used as a reference:

http://docs.unity3d.com/Documentation/ScriptReference/Lightmapping.html http://docs.unity3d.com/Documentation/Manual/CommandLineArguments.html http://docs.unity3d.com/Documentation/Components/gui-ExtendingEditor.html
> 2 votes

---
Tags: unity, shadow-mapping, procedural, raytracing, lightmap
---


# Question
Title: How can a web game store points online without giving the user the possibility to do the same call but with more points?
Imagine I have an HTML5 web game where the user can get points by doing certain activities. The game can be played offline, so there's not necessarily a live internet connection (*note: this makes this question other than existing questions*). Game state will then be synchronized at a later moment.

How can the frontend tell the server that the user has indeed gained those points without giving the user the ability to cheat? E.g. by doing a REST call with a multitude of his points? How can the server tell the difference between a real call and a fake call?

What I can think of is to send not the points, but e.g. all the moves of the game, and then the server recomputes the game and calculates the gained points? But that is quite hard, and the game must be deterministic in order to give the client and server the exact same result from the moves.

Does anybody know how existing games implement this? Or how it could theoretically be done?

# Answer
You might think it's hard, but the way you came up with is the way to do it:

> send not the points, but e.g. all the moves of the game, and then the server recomputes the game and calculates the gained points

(this is just one of a million reasons why developing multiplayer online games is harder than developing single-player games)
> 9 votes

# Answer
You really should tell us how this is being constructed as different technologies can have different advantages to your situation. Is it in Flash? PHP? HTML5? JavaSript? Java? The "web" tag doesn't give us much to go off.

**That being said:**

One of the most secure ways to transmit points score is to not let the client side decide what those points are. What you want is to create points based events:

* `Willem killed a zombie! - Score_KillZombie`
* `Willem looted a zombie! - Score_LootZombie`
* `Willem became a zombie! - Score_OopsIAmZombie`

These could be represented as enums in your client and get transmitted to the server on a per score event basis. You just killed a zombie? Excellent take the zombies ID - apply the killed zombie event and send this packet of info to the server. The server then confirms the actions - keeps tally of the score and confirms this with the client side so it can display it.

The zombie having an ID prevents your players from replicating any ID's they can't send Score\_KillZombie on a zombie ID "10000000" that your server knows isn't there or already dead. They can also not reloot a zombie that your server flags as empty of loot.

These situations go on and on but the important thing is that you give your server all the control on what actually is set in the game environment. Your client should simply tell the server what *predefined* event has happened and the server itself will decide if the client is lying or not (remember - it doesn't always have to listen to a client - that's where it weeds out any cheaters.)

Pretty much any implementation of a web game that relies on interaction with a client-server model does this predefined event driven approach. FPS's tell the server when they have shot and in which direction - the server decides if it actually hit the player. MMO's tell the server who their target it is and what spell they want to cast - the server decides if they have enough mana and are in range to do so, reporting back if the target dies. Even Facebook apps will authenticate actions like in Marvel Avengers, sending a move and the target bad guy, the server will decide how much damage it did and what the bad guy does as a reaction.

**In conclusion**

Never let the client make any authoritative decisions.
> 2 votes

# Answer
Two options that I can think of, but neither are really perfect.

Option one is when the user has completed those activities have the game send a request to the server and the server then sends a request back to the game for evidence that the user has indeed completed those activities (i.e.: presence of a certain item in the inventory, a dead something or another with a flag that designates that player x killed it).

Option two is to program the game in an unusual language and use unusual commands (i.e.: make everything do the opposite of what it usually does). However, this will only really give you a headache and slow down determined users.
> -2 votes

---
Tags: web, security, anti-cheat
---


# Question
Title: XNA & HLSL - rendering a model with its original materials (colors)
I am currently trying to code my own HLSL effect file, in order to render an FBX model I made with Autodesk maya, and to which I have applied some materials (colors).

before trying to write an effect file, I have tried using XNA's BasicEffect, which rendered the model as expected with the materials I had set in maya. Now though, when I'm using my own HLSL effect file, there's always an error saying that my model doesn't have any colors:

> The current vertex declaration does not include all the elements required by the current vertex shader. Color0 is missing.

My HLSL effect file (partially leared from riemers.net):

```
float4x4 xWorldViewProjection;

float4x4 xWorld;
float3 xLightPos;
float xLightPower;
float xAmbient;

struct VertexToPixel
{
    float4 Position     : POSITION;
    float4 Color        : COLOR0;
    float3 Normal        : TEXCOORD0;
    float3 Position3D    : TEXCOORD1;
};

struct PixelToFrame
{
    float4 Color        : COLOR0;
};

float DotProduct(float3 lightPos, float3 pos3D, float3 normal)
{
    float3 lightDir = normalize(pos3D - lightPos);
        return dot(-lightDir, normal);
}

VertexToPixel SimplestVertexShader(VertexToPixel input)
{
    VertexToPixel Output = (VertexToPixel)0;

    Output.Position =mul(input.Position, xWorldViewProjection);
    Output.Normal = normalize(mul(input.Normal, (float3x3)xWorld));
    Output.Position3D = mul(input.Position3D, xWorld);
    Output.Color = input.Color;

    return Output;
}

PixelToFrame OurFirstPixelShader(VertexToPixel PSIn)
{
    PixelToFrame Output = (PixelToFrame)0;

    float diffuseLightingFactor = DotProduct(xLightPos, PSIn.Position3D, PSIn.Normal);
    diffuseLightingFactor = saturate(diffuseLightingFactor);
    diffuseLightingFactor *= xLightPower;

    Output.Color = PSIn.Color* (diffuseLightingFactor + xAmbient);

    return Output;
}

technique Simplest
{
    pass Pass0
    {
        VertexShader = compile vs_3_0 SimplestVertexShader();
        PixelShader = compile ps_3_0 OurFirstPixelShader();
    }
}

```

And my XNA code:

```
foreach (ModelMesh mesh in MainRoom.Meshes)
    foreach (ModelMeshPart meshPart in mesh.MeshParts)
        meshPart.Effect = roomEffect.Clone();

```

...

```
private void DrawModel(Model model, Matrix world)
{
    Matrix[] bones = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(bones);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (Effect currentEffect in mesh.Effects)
        {
            Matrix worldMatrix = bones[mesh.ParentBone.Index] * world;

            roomEffect.CurrentTechnique = roomEffect.Techniques["Simplest"];
            currentEffect.Parameters["xWorldViewProjection"].SetValue(worldMatrix * camera.view * camera.projection);
            currentEffect.Parameters["xWorld"].SetValue(worldMatrix);
            currentEffect.Parameters["xLightPos"].SetValue(lightPos);
            currentEffect.Parameters["xLightPower"].SetValue(lightPower);
            currentEffect.Parameters["xAmbient"].SetValue(ambientPower);
        }
        mesh.Draw();
    }
}

```

I'm fairly new to HLSL (but not to XNA though), any help would be nice.

**EDIT:** I have also tried rendering a different model with materials, but it just gives the same error.

---

---

---

---

**Solution:** Thanks to Cole Campbell's answer and, the full working code can be found here

# Answer
You're getting this error because your HLSL effect requires a color channel on the vertex data:

```
struct VertexToPixel
{
    float4 Position     : POSITION;
    float4 Color        : COLOR0;
    float3 Normal        : TEXCOORD0;
    float3 Position3D    : TEXCOORD1;
};

```

...but your models don't have that channel on their vertices. Which channels exist on a model is a function of how they're exported from the program that created them.

The built-in XNA `BasicEffect` is intelligent enough to choose a different technique depending on the vertex format of the model being rendered, which is why it doesn't run into this problem.

The specific problem which you face arises from a misunderstanding of what Color0 constitutes. *Material colors* are different from *vertex colors*. Material colors should be specified as a parameter in the shader. Vertex colors are part of the vertex data.

You'll need to add a parameter to your shader that represents the material color:

```
float4 DiffuseColor;

```

...and copy it from the effect that you're replacing:

```
myEffect.Parameters["DiffuseColor"].SetValue(oldBasicEffect.DiffuseColor);

```

...and then use that to produce the final color for your vertex, and remove the `float4 Color: COLOR0` declaration from your vertex data entirely.
> 1 votes

---
Tags: xna, c#, models, hlsl, fbx
---


# Question
Title: LibGDX Drawing sprites when moving orthographic camera
I've been having this problem for a long time and I just can't seem to find the exact problem. I have a game where the map is 480x1600 and my camera has a view of 480x800. I have a button that when pressed, allows the user to place a platform on the map, and since the map is too big to fit on the screen, I made it so the user can move the camera up and down the map by dragging.

```
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.unproject(pos);
    cam.position.y = pos.y;
    return true;
}

```

Method that controls when the user tries to put a platform down

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.unproject(pos);
    Gdx.app.log(Game.LOG, "X Coordinate: " + pos.x + " Y Coordinate: " + pos.y);

    if (GameScreen.createPlatform == true) {
        world.setPlatform(new Vector2(pos.x - 0.6f, pos.y - 0.1f), 1);
        GameScreen.createPlatform = false;
        return true;
    }

    ...
}

```

Where I render the platform sprites

```
public void render(float delta) {
    ...
    spriteBatch.setProjectionMatrix(cam.combined);
    spriteBatch.begin();
    for (Sprite platformSprite: world.getPlatformSprites()) {
        platformSprite.draw(spriteBatch);
    }
    spriteBatch.end();
    ...

}

```

The game works fine when I don't move the camera. But when I do, the platforms aren't placed where I click, they're always either higher or lower where I actually clicked. Also, the platforms are always placed somewhere where the camera was originally looking before anything has been moved.

I think it's doing this is because for some reason, the coordinates never actually change. So wherever I am on the map, the top of the screen is always 120 and the bottom is always 90. This also causes objects on the map to have different coordinates if I move the camera.

This problem has me completely lost and I would appreciate any help.

# Answer
`cam.unproject(touchPos)` will give you the coordinates as they relate to your screen and `cam.project(touchPos)` will give you the coordinates as they relate to the game world.

gamedev.stackexchange.com/a/27793/20399

so in here:

```
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.unproject(pos);
    Gdx.app.log(Game.LOG, "X Coordinate: " + pos.x + " Y Coordinate: " + pos.y);

    if (GameScreen.createPlatform == true) {
        world.setPlatform(new Vector2(pos.x - 0.6f, pos.y - 0.1f), 1);
        GameScreen.createPlatform = false;
        return true;
    }

    ...
}

```

make it like this:

```
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.project(pos); //changed
    Gdx.app.log(Game.LOG, "world X Coordinate: " + pos.x + " world Y Coordinate: " + pos.y);

    if (GameScreen.createPlatform == true) {
        world.setPlatform(new Vector2(pos.x - 0.6f, pos.y - 0.1f), 1);
        GameScreen.createPlatform = false;
        return true;
    }

    ...
}

```
> 3 votes

---
Tags: java, android, libgdx
---


# Question
Title: .dat files in 2D Games: Spritesheets vs Individual Images
I've been doing some research and I found that the game RollerCoaster Tycoon uses .dat files to store all the animations/images for each ride. Basically we're talking hundreds of images (per ride even), that are separate .bmp files inside this .dat file. This goes against the preaching of always using spritesheets... or maybe I misunderstand how the .dat file is being used? Using spritesheets are nice when the images and animation frames are all the same size, but when they vary so much (like varying ride sizes), it would be nice to use individual images. From my understanding, there's limits on image counts, and generally bad things when using tons of individual images... but ancient RoolerCoaster Tycoon seems to do just that with its .dat files.

What am I missing? What is the best way to store a massive amount of images?

# Answer
There's an overarching theme to this question because there's more to it than just storing images separately vs. packed in a custom file format. I'll go through this theme, then I'll circle back to spritesheets.

On older systems, the ones that Roller Coaster Tycoon was made for, reducing hard drive latency was one of the big things that developers had to watch out for. Disks were relatively slow. It's still the case, and today the canonical term is "cooked". The assets are said to be "cooked" when they are packed and compressed for a specific processor and storage medium (think PC, PS3, Xbox, and so on).

The advantage of doing this is to reduce the seek-time of hard drive by making the assets as close to each other on the disk as possible. This is achieved by placing them all in one file. There's often a process that's involved in figuring out how often one asset is accessed relative to another, and the assets are placed in this file accordingly.

Back to the question, I haven't taken a look at the RCT .dat file, but it sounds like it takes several .bmp files and places them inside of one .dat file. This is essentially a spritesheet, just that instead of having all the sprites inside of one .bmp, all the .bmp files are inside of one .dat.

Most games employ some kind of a compression technique to store a lot of spritesheets into reasonable sizes. There's a tradeoff between how good the sprites themselves look (ie. do you use 256-colors lookup table, or do you go with a full 32-bit RGBA sprite), and the compression technique used across the entire file where your individual spritesheets are packed into (.zip, .7z, .mpq, etc...)
> 2 votes

---
Tags: xna, spritesheet
---


# Question
Title: Spot lights - making narrow/broad spot lights give more/less intense light
When I use "normal" spot lights as presented in tutorials such as this (with the exception that I use inverse square fall-off and then gamma correction), the spot light doesn't behave like a real spot light would, because in real life I would expect a narrow spot light to cast a brighter light than a broad one. In my primitive understanding this is because the light that would be cast outside of the spot lights casting angle is reflected on the inside of the spotlight device (e.g. flashlight) and effectively cast inside spotlights cone.

The spotlights usually presented in tutorials do not account for this, because the light calculation is still based on a spot light that distributes all of its energy evenly in a 360 degree radius, and the light that isn't visible is simply "clipped away", thus removing energy from the system.

My question is this:

I plan on accounting for this by just multiplying the outgoing color by a factor that depends on the casting angle of the spot light. The function of this factor is just

```
f(x) = 360/x;

```

This means that the color will be multiplied by 4 when the spot light casts its light in a 90 degree angle. This function makes the assumption that the energy received by the lit area of a 180 degree spot light is twice as much as the energy received by the lit area of a 360 degree spot light.

Is this assumption correct? If not, how does the energy distribution change with the width of the spot light? Are there maybe other ways to account for this more effectively?

# Answer
> 3 votes
If you want to maintain the total amount of light power generated by the spotlight, then its brightness should be scaled inversely by the amount of solid angle it can emit into. With a little math you can calculate this: if the spotlight angle is `a` then the fraction of solid angle (i.e. fraction of area on the sphere of directions) is

```
0.5 * (1.0 - cos(0.5 * a))

```

So if you want to maintain the same total amount of light power generated by the spotlight, you should divide the brightness by this value.

Here's the derivation if you're curious: I'm going to calculate the area of the circular cap where a unit sphere intersects the spotlight cone, in spherical coordinates. The cap ranges from θ = 0 to θ = a/2 in spherical coordinates (taking the polar axis of the sphere to be aligned with the spotlight axis). The area is then

```
(integral from 0 to 2π) dφ (integral from 0 to a/2) sin θ dθ

```

Doing this integral gives `2π (1 - cos a/2)`. The total area of the sphere is , so divide by that to get the area fraction, and you have the above result.

---
Tags: lighting
---


# Question
Title: How would one store global context data in an entity component system?
My question is this:

**How would one store global context data, ie. world data information, current world time, etc in an entity component system?**

I'm think of working towards building a Dwarf Fortress-style open ended world simulation game in C++. I've build up an entity component style game engine just for fun, and I'm currently trying to figure out how I am going to work in all the features I want. In addition to standard game play (rendering, physics, entity-specific component data, etc), I would also like to have some global contextual data that all relevant systems would have access to (ie, the world data like what year it currently is, whether global warming is happening, Any kind of thing that would be relevant to simulating a world). I had originally thought of making a "world" component, but this seems pointless and difficult if a lot of different systems need access to this logically "global" data.

Would it make sense to have a "world" component or should I store this data some other way?

I'd also thought of simply making this data global, thus giving access to any systems that would want to use it; it seems like a violation of entity-component principles in general, and maybe messy for other reasons, but I thought that it might really work.

The other thing I'd thought of would be to actually embed relevant world-context data directly into the systems themselves. For example, if I had an `AgeSystem` that "aged" all entities that have a `getsWeakerAsTimePasses` component or whatnot, then maybe this system could store relevant time data for the world directly as member data that it would use to calculate the passage of time and how much to age and weaken people, etc. This third option was my least favorite, but something that had occurred to me in brainstorming.

Can anyone advise?

# Answer
> 12 votes
Any way that works is a way that works. That sounds snide, but really, your game is 1000x more important than your architecture. Pick any approach you like and find easy to use.

The ones I've seen in real shipping games (using component-based design, not ECS specifically; I've never seen pure ECS "in the wild", though many component designs have ECS-like elements to them) include:

* Singletons
* "Context" objects passed to components/systems that contain references to all relevant other systems
* Component factories that pass system handles to individual components
* Components which store references to systems in the root of an object hierarchy (only in some oddball Unity games)
* Singular "Engine" objects passed to systems or component which hold references to all other systems
* String-based resource lookup systems (allowing you in C++ to do something like `handle<PhysicsSystem> = GetResource<PhysicsSystem>("/systems/physics")`, yes, really)
* Piles of global data and C-style free functions that operate on them
* Spaces/subspaces and accompanying video

They all work. I have gripes with some approaches and an obvious favorite, but they've all been used to ship AAA games. Sometimes multiple approaches in a single project (40-100+ engineer teams tend to create haphazard duplicate code, alas).

---
Tags: c++, entity-system, component-based
---


title: Languages to develop games

text:
# Question
Title: Languages to develop games
Hello I am a 10th grade student from India...I have been playing games since a very young age. I want to work in the game industry as a game developer...I have started learning the basics of C programming language...Can anyone tell me which language I should focus on or should I just continue with C

Thank You

# Answer
That's great that you want to get into game development. When it comes to choosing a programming languages, it all boils down to your requirements.

Some examples:

* If you want to develop for Android, take a look at Java.
* If you want to develop for Xbox 360 or Windows Phone take a look at C#.

There are some choices that will work great on several platforms. C or C++ are some of them. Learning C is a good choice, but I would not actually recommend it. Game development is not really about the language, it's more about abstract concepts and patterns, most languages support an implementation of these. So it does not really matter which languages you choose.

I would recommend C++ or C#, to ease the learning curve. Remember there's much more to learn then just the language when it comes to game development. One important thing to remember is that making games is nothing like playing them.
> 0 votes

---
Tags: game-design, education
---


# Question
Title: Creating and connecting rooms for a roguelike
I'm creating a Roguelike and I'm having constant troubles with map generation, it's just something I have a lot of difficulty wrapping my head around.

I currently have my map as a 50x50 square of tiles, which is then cut up into a 6x6 grid. The grid resembles as follows

```
+---+---+---+----+----+----+
| 1 | 2 | 3 | 4  | 5  | 6  |
+---+---+---+----+----+----+
| 7 | 8 | 9 | 10 | 11 | 12 |
+---+---+---+----+----+----+

```

etc etc up to 36. I can generate perfectly an identical room into each of these map sections but what I'm actually concerned about is filling a small number of them and connecting them.

Is there a known approach to this? Currently what I'm doing is just looping through the sections, taking a 50/50 coin toss and making a room there but I'm unsure how I can tell where to make paths, what if I have my map set out as follows

```
+---+---+---+----+----+----+
| 4 |   |   | 1  |    |    |
+---+---+---+----+----+----+
|   |   |   |    | 2  |    |
+---+---+---+----+----+----+
|   |   | 3 |    |    |    |
+---+---+---+----+----+----+

```

How do I intelligently map between 1 and 2? How do I map between 2 and 3, much less how do I map between 3 and 4?

I'm very new to game development, so please excuse me if this is a silly question

# Answer
The first roguelike game, the Rogue have such algoritm to connect the rooms:

1.Pick direction of corridor: vertical or horizontal based on room's relative position:

```
x1, y1 - coords of first room
w1, h1 - size of first room, etc.

if(x1 + w1 < x2 || x2 + w2 < x1) then vertical
if(y1 + h1 < y2 || y2 + h2 < y1) then horizontal
if(both) then random
if(none) they overleap and doesn't need to be connected via coridor

```

2.Pick a point on side of each room (that side in the direction), like this:

3.Pick a random X coordinate between (or Y if you're doing vertical)

4. Draw a line from first point to that X, than from second point to that X:

5. Last step: connect it vertically:
> 6 votes

# Answer
I think you have a few options:

* Use a path finding algorithm like A\* to find the shortest paths between rooms. This would give you a quick algorithm, but the paths would all be optimal, so it might be boring. There are some tweaks you can do to add some randomness to the path finding and make the hallways a little less optimal and maybe more interesting.
* Pick your rooms, then fill the rest of the grid with "hallway" nodes. Pick a hallway node at random to remove, and remove it if doing so doesn't affect the connectivity of your rooms. Continue until there are no removable hallway nodes left. This would use something like a breadth first search to ensure connectivity among the rooms.
* Test out some alternative algorithms for generating rooms, like a BSP generator or read up on Unangband dungeon generation.
> 3 votes

# Answer
I'm also a newbie C++ programmer and happens to write one maze generation program a couple of days ago. I believe BSP or A\* are too complex for me and I won't touch them until I'm comfortable with data structures and algorithms. So what I did is the following:

1. Find the center of each room;
2. Connect the centers. Say you generated rooms at 1, 4, 8, 10 and 12 so simply connect the center of 1 to the center of 4 and go on until there is no more room that is not connected.

It's very easy and very fast, but also boring and sometimes gives me double hallways which I think it's OK.

Hope this helps!
> 0 votes

---
Tags: maps, tilemap, roguelikes
---


# Question
Title: How can I get the texture file name for my polygon?
I have a problem with the FBX SDK. I read in the data for the vertex position and the UV coordinates. It works fine, but now I want to read for each polygon to which texture it belongs, so that I can have models with multiple textures. Can anyone tell me how I can get the texture file name for my polygon? My code to read in vertex position and uv coordinates is the following:

```
int i, j, lPolygonCount = pMesh->GetPolygonCount();
FbxVector4* lControlPoints = pMesh->GetControlPoints();

int vertexId = 0;
for (i = 0; i < lPolygonCount; i++)
{

    int lPolygonSize = pMesh->GetPolygonSize(i);

    for (j = 0; j < lPolygonSize; j++)
    {
        int lControlPointIndex = pMesh->GetPolygonVertex(i, j);
        FbxVector4 pos = lControlPoints[lControlPointIndex];
        current_model[vertex_index].x = pos.mData[0] - pivot_offset[0];
        current_model[vertex_index].y = pos.mData[1] - pivot_offset[1];
        current_model[vertex_index].z = pos.mData[2]- pivot_offset[2];

        FbxVector4 vertex_normal;
        pMesh->GetPolygonVertexNormal(i,j, vertex_normal);

        current_model[vertex_index].nx = vertex_normal.mData[0];
        current_model[vertex_index].ny = vertex_normal.mData[1];
        current_model[vertex_index].nz = vertex_normal.mData[2];

        //read in UV data
        FbxStringList lUVSetNameList;
        pMesh->GetUVSetNames(lUVSetNameList);

        //get lUVSetIndex-th uv set
        const char* lUVSetName = lUVSetNameList.GetStringAt(0);
        const FbxGeometryElementUV* lUVElement = pMesh->GetElementUV(lUVSetName);

        if(!lUVElement)
            continue;

            // only support mapping mode eByPolygonVertex and eByControlPoint
        if( lUVElement->GetMappingMode() != FbxGeometryElement::eByPolygonVertex &&
            lUVElement->GetMappingMode() != FbxGeometryElement::eByControlPoint )
            return;

        //index array, where holds the index referenced to the uv data
        const bool lUseIndex
            = lUVElement->GetReferenceMode() != FbxGeometryElement::eDirect;
        const int lIndexCount= (lUseIndex) ? lUVElement->GetIndexArray().GetCount() : 0;

        FbxVector2 lUVValue;

        //get the index of the current vertex in control points array
        int lPolyVertIndex = pMesh->GetPolygonVertex(i,j);

        //the UV index depends on the reference mode
        int lUVIndex = pMesh->GetTextureUVIndex(i, j);
        lUVValue = lUVElement->GetDirectArray().GetAt(lUVIndex);
        current_model[vertex_index].tu = (float)lUVValue.mData[0];
        current_model[vertex_index].tv = (float)lUVValue.mData[1];

        vertex_index ++;
        }

    }

    float v1[3], v2[3], v3[3];
    v1[0] = current_model[vertex_index - 3].x;
    v1[1] = current_model[vertex_index - 3].y;
    v1[2] = current_model[vertex_index - 3].z;

    v2[0] = current_model[vertex_index - 2].x;
    v2[1] = current_model[vertex_index - 2].y;
    v2[2] = current_model[vertex_index - 2].z;

    v3[0] = current_model[vertex_index - 1].x;
    v3[1] = current_model[vertex_index - 1].y;
    v3[2] = current_model[vertex_index - 1].z;

    collision_model->addTriangle(v1,v2,v3);

```

# Answer
You can get the the texture information by following steps,

FbxNode -\> FbxSurfaceMaterial -\> FbxLayeredTexture or FbxTexture -\> Texture name (and other properties)

The code looks like,

```
int mcount = node->GetSrcObjectCount<FbxSurfaceMaterial>();
for (int index=0; index<mcount; index++ )
{
   FbxSurfaceMaterial *material = (FbxSurfaceMaterial*)node->GetSrcObject<FbxSurfaceMaterial>(index);
   if (material)
   {
      // This only gets the material of type sDiffuse, you probably need to traverse all Standard Material Property by its name to get all possible textures.
      FbxProperty prop = material->FindProperty(FbxSurfaceMaterial::sDiffuse);

      // Check if it's layeredtextures
      int layered_texture_count = prop.GetSrcObjectCount<FbxLayeredTexture>();
      if (layered_texture_count > 0)
      {
         for (int j=0; j < layered_texture_count; j++)
         {
            FbxLayeredTexture* layered_texture = FbxCast<FbxLayeredTexture>(prop.GetSrcObject<FbxLayeredTexture>(j));
            int lcount = layered_texture->GetSrcObjectCount<FbxTexture>();
            for (int k=0; k<lcount; k++)
            {
               FbxTexture* texture = FbxCast<FbxTexture>(layered_texture->GetSrcObject<FbxTexture>(k));
               // Then, you can get all the properties of the texture, include its name
               const char* texture_name = texture->GetName();
            }
         }
      }
      else
      {
         // Directly get textures
         int texture_count = prop.GetSrcObjectCount<FbxTexture>();
         for (int j=0; j<texture_count; j++)
         {
            const FbxTexture* texture = FbxCast<FbxTexture>(prop.GetSrcObject<FbxTexture>(j));
            // Then, you can get all the properties of the texture, include its name
            const char* texture_name = texture->GetName();
         }
      }
   }
}

```
> 2 votes

# Answer
Can't tell FBX SDK specification from what you linked but that's how this data is stored in your FBX file, for instance:

* "Cube" - mesh object
* "Logo.png" - texture

FBX contains section called "Connections" which looks like this:

```
; Object connections
;------------------------------------------------------------------

Connections:  {
    Connect: "OO", "Model::Cube", "Model::Scene"
    Connect: "OO", "Material::Material__Logo_png", "Model::Cube"
    Connect: "OO", "Texture::Logo_png", "Model::Cube"
    Connect: "OO", "Video::Logo_png", "Texture::Logo_png"
}

```

FBX files can either be binary or ASCII and either contain paths to textures or having textures packed inside. You can use FBX Converter 2013 by Autodek to switch and pack/unpack textures.
> 1 votes

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


# Question
Title: How to achieve rendering at huge distances?
These days I was reading some information about the upcoming GTA V technology, in particular, how it is able to truly render all buildings you can see without a draw distance cap or any faking.

Since I will soon be prototyping a big city environment, I wanted some advice on this topic. We're talking about a really big city, with simple geometry but fully lit and shadowed. My doubt comes in particular to the projection matrix, which imposes a maximum draw distance (the zFar parameter).

Now, at the same time, I read everywhere that zFar should be as small as possible for better rendering results, in particular related to depth buffer issues etc, because of the floating point issues.

So, assuming my computer can render this big city in a stable framerate, how should I approach the problem of rendering parts of the city which I can see REALLY far away, fully lit and shadowed? Shadow maps also seem to have problems with low depth buffer precision..

Thanks

# Answer
Default Z buffer is impractical for huge distances because it wastes A LOT of prescision for what is very close to the camera. A tiny increase in zNear kills prescision for distant objects.

Logarithmic Z buffer solves this problem by offering a more sensible distribution of prescision. It ensures there is enough prescision at almost any distance (at least enough to render a GTA city without resorting to rendering different parts or world with different Z buffers). There is too much details about implementing logarithmic Z to discuss here but I find this article great. The best trick from the article: if you are using Direct3D you can simply swap zNear and zFar in the code and you get an almost logarithmic z buffer!

Also, it is possible to render geometry closer than zNear and farther than zFar by enabling Depth Clamp but of course z buffer becomes useless outside of the frustum.
> 5 votes

# Answer
There's a few thing:

* Determine a good far and near clip.
* A smooth Level of Detail system, using simplified models at distance too reduce detailed z-fighting.
* Combining camera outputs
* Tesselation

Combining camera outputs is used by FPS games as a solution too the lack of precision you get from needing a near clip very close to the camera (e.g. to see the gun) and the need to see very far (e.g being able to see a mountain). So what you can do is to render the stuff that need to be close and detailed first and then the more distant surrounding. Combine the two images and there you go.

Then it comes to zFar and zNear their values does not really matter. It's the difference between them that decides the precision when comes to depth testing. You only got a few bytes to save the depth. Bad precision results in a lot of z-fighting and thats's usually bad thing.
> 2 votes

# Answer
As a simple aproach:

You may perform a first render pass, with only far/low-polygon building. In this pass, you may use a small scale which allow a correct zBuffer accuracy.

In the second render pass, you delete the zBuffer and you render only near high-polygon objects with a higher scale.
> 1 votes

---
Tags: opengl
---