# Question
Title: What is a legal way to use music from registered authors in a game?
I have recently asked a question about music in games like Guitar Hero.

I have found that that in Europe (at least) if I do want to use a track composed by a musician member of a royalty collecting society I need to pay a flat fee to the society and not only to the member.

So a "one-to-one" agreement is not valid and the society can come up to me and ask me for money for each download. Even if for FREE!

This is a fee sheet list of the UK agency: for fee, see "Permanent download services"

It is about 1,200 GBP for less than 22,000 copies and they DON'T specify anything more and they said me on the phone that **I need to wait and see how many downloads I get before knowing the price.**

This is kind of crazy as If I give away the App for free I will have to PAY 1,200 GBP!!

I am shocked and I feel very bad.

The other solution is to work only with non registered musicians.

The question here to you is:

Has anyone found a legal way to use music from registered authors in a game?

# Answer
> 8 votes
If the artist has entered into an agreement with a royalties collection agency - whether for the recording, or the songwriting - then you can't use their music without a licence from the relevant agency or agencies in order to use the music. This is because the artist has assigned their rights to the collection agency, and is no longer legally allowed to give you a separate licence to use the work.

In theory, the artist and the collection agency could negotiate individual exceptions. In practice, this won't happen. The reason collections agencies exist is to make it easier for everybody - without them, each artist would have to talk to each venue or business to get their royalties. With a collections agency, the artist only has to deal with one organisation, and so do the venues and businesses. If the agency then had to keep track of each individual direct agreement between artists and 3rd parties, the job of collecting and distributing revenues would be much more complex.

Your only options are these:

* buy a licence for yourself
* work as part of an organisation that already has a licence
* work exclusively with artists who have not transferred their rights to a collections agency

---
Tags: game-industry, music, copyright
---


# Question
Title: Stop a rotating object at a specified angle?
I'm working in JavaScript with HTML5 and the canvas. I have an object which is rotating at a certain speed, and I need the object's rotation to slow down gradually and the front of the object to stop at a specified angle. (I'm using radians, not degrees.) I have a variable to keep track of the angle which the object is facing, as it rotates.

How would I go about getting the object to come to rest, facing the direction I want it to?

# Answer
> 1 votes
maybe a good way of seeing the problem is to ask : \- can i do another cycle ?

count the number of cycle, and see if this is the begining of a cycle:

```
var beginingNewCycle=false;
numCycle = Math.floor ( (angle - endAngle ) / 6.28318531 ;
if (old_numCycle != numCycle) beginingNewCycle=true;
old_numCycle=numCycle;

```

( when the rotation starts,
you should : 1) reset angle with angle=angle % 6,28318531 ;
and 2) set old\_numCycle to -1
)

So when you have a new cycle, ask yourself if this will be the last, for example if speed \< threshold. Then you do the last turn controlling the speed fade-out to zero.

for instance for the fade out, you can use :

```
 var rotSpeedAtenuation =  1 -   ( (angle-EndAngle) % 6.28318531 ) / 6.28318531 ;

```

which is a number going from 1 to 0 linearly as angle gets nearer from goal. multiply the speed by this number, but keep a minimum speed not to freeze the object before arrival.

But linear might be hugly, maybe you want to 'shape' the atenuation, like for
instance with :

```
  var sqM1 = function (x) { return 1 - x*x ;}

```

and you use sqM1(rotSpeedAtenuation) to multiply to current speed.

# Answer
> 2 votes
Visualise a graph of rotation versus time that gradually drops to zero and notice there is an infinite number of ways of drawing such a graph. First, you'll have to specify how you want the angular velocity to decrease. Formulate a function *ω(t)* that equals the starting angular velocity (*s*) at *t=0* and drops to zero eventually (*t=T*). Tune the variables to match the following criterium: *ω(t)* integrated over *t* from *0* to *T* equals the rotation yet to be covered. An example:

I want my angular velocity to decrease in a linear fashion, i.e.: *ω(t) = s + a t*. To find *T*, we solve: *s + a T = 0*, ergo: *T = -s/a*. Integrating yields that the angle covered in this gradually decelerated rotation equals *-½ s² / a*. Solving for *a* gives us the desired angular velocity at every timestep, which we can numerically integrate as we go to find the current angle, or do this in advance to obtain a function angle of time which we can use directly.

---
Tags: javascript, html5, rotation, easing
---


title: C# 2D Camera Max Zoom

text:
# Question
Title: C# 2D Camera Max Zoom
I have a simple ship sprite moving around the screen along with a 2D Camera.

I have zooming in and out working, however when I zoom out it goes past the world bounds and has the cornflower blue background showing.

How do I sort it that I can only zoom out as far as showing the entire world (which is a picture of OZ) and thats it? I dont want any of the cornflower blue showing.

Cheers!

```
namespace GamesCoursework_1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    // player variables
    Texture2D Ship;
    Vector2 Ship_Position;
    float Ship_Rotation = 0.0f;
    Vector2 Ship_Origin;
    Vector2 Ship_Velocity;
    const float tangentialVelocity = 4f;
    float friction = 0.05f;

    static Point CameraViewport = new Point(800, 800);
    Camera2d cam = new Camera2d((int)CameraViewport.X, (int)CameraViewport.Y);
    //Size of world
    static Point worldSize = new Point(1600, 1600);
    // Screen variables
    static Point worldCenter = new Point(worldSize.X / 2, worldSize.Y / 2);

    Rectangle playerBounds = new Rectangle(CameraViewport.X / 2, CameraViewport.Y / 2, worldSize.X - CameraViewport.X, worldSize.Y - CameraViewport.Y);
    Rectangle worldBounds = new Rectangle(0, 0, worldSize.X, worldSize.Y);

    Texture2D background;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);

        graphics.PreferredBackBufferWidth = CameraViewport.X;
        graphics.PreferredBackBufferHeight = CameraViewport.Y;
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
        Ship = Content.Load<Texture2D>("Ship");
        Ship_Origin.X = Ship.Width / 2;
        Ship_Origin.Y = Ship.Height / 2;

        background = Content.Load<Texture2D>("aus");

        Ship_Position = new Vector2(worldCenter.X, worldCenter.Y);
        cam.Pos = Ship_Position;
        cam.Zoom = 1f;

    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here
        Ship_Position = Ship_Velocity + Ship_Position;
        keyPressed();

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null,null, cam.get_transformation(GraphicsDevice));
        spriteBatch.Draw(background, Vector2.Zero, Color.White);
        spriteBatch.Draw(Ship, Ship_Position, Ship.Bounds, Color.White, Ship_Rotation, Ship_Origin, 1.0f, SpriteEffects.None, 0f);
        spriteBatch.End();

        base.Draw(gameTime);
    }

    private void Ship_Move(Vector2 move)
    {
        Ship_Position += move;
    }

    private void keyPressed()
    {
        KeyboardState keyState;
        // Move right
        keyState = Keyboard.GetState();

        if (keyState.IsKeyDown(Keys.Right))
        {
            Ship_Rotation = Ship_Rotation + 0.1f;
        }
        if (keyState.IsKeyDown(Keys.Left))
        {
            Ship_Rotation = Ship_Rotation - 0.1f;
        }
        if (keyState.IsKeyDown(Keys.Up))
        {

            Ship_Velocity.X = (float)Math.Cos(Ship_Rotation) * tangentialVelocity;
            Ship_Velocity.Y = (float)Math.Sin(Ship_Rotation) * tangentialVelocity;

            if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y;
            if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X;

            Ship_Position += new Vector2(tangentialVelocity, 0);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(tangentialVelocity * 2, 0.0f);
            Ship_Position += new Vector2(-tangentialVelocity, 0.0f);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(-tangentialVelocity * 2, 0.0f);
            Ship_Position += new Vector2(0.0f, -tangentialVelocity);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, -tangentialVelocity * 2);
            Ship_Position += new Vector2(0.0f, tangentialVelocity);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, 2 * tangentialVelocity);

        }
        else if(Ship_Velocity != Vector2.Zero)
        {
            float i = Ship_Velocity.X;
            float j = Ship_Velocity.Y;

            Ship_Velocity.X = i -= friction * i;
            Ship_Velocity.Y = j -= friction * j;

            if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y;
            if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X;

            Ship_Position += new Vector2(tangentialVelocity, 0);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(tangentialVelocity * 2, 0.0f);
            Ship_Position += new Vector2(-tangentialVelocity, 0.0f);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(-tangentialVelocity * 2, 0.0f);
            Ship_Position += new Vector2(0.0f, -tangentialVelocity);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, -tangentialVelocity * 2);
            Ship_Position += new Vector2(0.0f, tangentialVelocity);
            if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, 2 * tangentialVelocity);

        }
        if (keyState.IsKeyDown(Keys.Q))
        {
            if (cam.Zoom < 2f) cam.Zoom += 0.05f;
        }
        if (keyState.IsKeyDown(Keys.A))
        {
            if (cam.Zoom > 0.3f) cam.Zoom -= 0.05f;
        }

    }
}
}

```

# Answer
> 0 votes
I'm assuming you are generating a scaling matrix to perform zoom.

First is the easy part(you probably have this already). You want is to stop zooming when the background becomes the same size as the viewport. The point to stop zooming out is 'backgroundwidth/viewportwidth'. This will be 0.5 in your case. Don't let the zoom factor go below this value.

This will work fine if the camera is in the centre of the background, but if the camera is off centre, you will still see your cornflower blue on the edge of the screen.

In order to prevent the user from being shown outside the edge of the world, yo will need to change the size of `playerBounds` rectangle. You are already using this to stop camera movement when the player gets too close to the edge. You just need to make sure that this rectangle has the appropriate size. Basically you want to prevent the camera position from getting within `camerawidth/2` pixels of the edge of the background. During zooming out the background is effectively getting smaller

```
float scaledWorldHalfWidth=worldSize.x*cam.Zoom/2.0f;
float scaledWorldHalfHeight=worldSize.y*cam.Zoom/2.0f;

playerBounds = new Rectangle(worldcentre.X-scaledWorldHalfWidth +CameraViewport.X/2,
                             worldcentre.Y-scaledWorldHalfHeight+CameraViewport.Y/2,
                             worldcentre.X+scaledWorldHalfWidth -CameraViewport.X/2,
                             worldcentre.Y+scaledWorldHalfHeight -CameraViewport.Y/2);

```

In this code I am decreasing the size of the rectangle as the zoom factor decreases (as the player sees more and more of the background).

EDIT

This new player bounds should be generated whenever you change the camera zoom factor. So call it when 'q' or 'a' is pressed.

Also, whenever the camera moves check if the camera is still in playerbounds, if not adjust it position so that it is;

```
        if (cam._Pos.X < playerBounds.Left) //too far left? Any further left, the camera will start to show the edge of the map
            cam._Pos.X=playerBounds.Left //put it on the left most edge player bounds

         // similar code needed for top, bottom and right

```

A couple of other things;

1. As you zoom out, you will need to check if camera position still lies within the `playerBounds` rectangle, as the rectangle gets smaller. You will need to adjust/move the camera to make sure it lies in the rectangle.
2. All this code will be implemented much simpler if you centre the world on the origin, rather than having the upper-left of the world drawn at the origin. (check out the 'origin' parameter in spritebatch.Draw(.....);

---
Tags: c#, xna-4.0, camera
---


title: Guitar hero clone and music

text:
# Question
Title: Guitar hero clone and music
I am an indie game developer and I am doing a game similar to **guitar hero**. I am using tracks composed by musicians and I contacted them to sing a licensing contract. As is my first indie project I have no idea on how I should deal with the royalties aspect of this because each track as an ISRC code and each time a track is played in public there is a fee to pay to the "local" registration authority.

An iPhone game it is downloaded and not played on air (or physically distributed), and hence I think there is a specific legislation for this that specifies how much one should pay. I own some of the tracks composed and for this I think I won't have to pay a royalty (even if the track has an ISRC code) but for other tracks I just have a license "to use".

I wonder how a game like Guitar hero can sell on iPhone for as little as 0,99$ and then have "in app purchases" for packs of 3 songs (for about 2 dollars) and make a profit (I imagine they will have to pay a ISRC royalty).

Does anyone of you have any idea of this can work or if there is a **section in this forum where I can ask this question? I understand is not about coding but I think is about development of a game in the broader sense.**

# Answer
> 0 votes
Here is the correct answer posted in a follow up question by Kylotan.

Please feel free to share your experience by adding other answers if there are other legal ways to do so. I think legislation might change in the near future providing easier ways to do deals with agencies. I have had to contact the headquarters of one of these agencies (EU country) and they will have to get back to me in two weeks and they said that they never dealt with this before. Instead the UK one proposed me those weird flat licenses that are no good if you want to get the app downloaded for free.

# Answer
> 4 votes
ISRC codes have little to do with royalties. The code merely identifies a track. Whether a track has a code or not, you still have to comply with copyright laws to use the track. Generally speaking the rates are not covered by legislation, but by agreements between broadcasters and music publishers.

Unless you wrote and recorded the songs, you do not 'own' any of the tracks. You may own a copy of a recording of them, but that doesn't give you a right to redistribute or broadcast them, which would prohibit you bundling them with your game or making them downloadable via your game.

Games like Guitar Hero work because they have come to financial agreements with publishers over use of the track. This may be via a synchronization licence or it might be via a separate deal. You are unlikely to be able to reach similar agreements with well-known artists. You may however be able to do so with individual musicians, especially unsigned ones, who do not have to clear copyright issues with their publisher.

---
Tags: iphone, game-industry, music, copyright
---


title: XNA- Rotating around another model

text:
# Question
Title: XNA- Rotating around another model
Lets say I have a model with multiple meshes. **Mesh A** is at position `PositionA = new Vector3(5,0,10)`. And **mesh B** is at position `PositionB = new Vector3(7,0,9)`. How can I rotate **mesh B** around **meshes A** pivot point, or its centre?

# Answer
In Xna, you can orbit `positionB` around `positionA` like this:

```
Matrix orbit = Matrix.CreateFromAxisAngle(someAxis, someAngle);
positionB = Vector3.Transform(positionB - positionA, orbit) + positionA;
MeshBworld.translation = positionB;

```

where `someAxis` is a unit length vector representing the direction of the pivot axis and `someAngle`represents the amount of single frame orbiting rotation in radians. `MeshBworld` is simply Mesh B's world transform... whatever you've named it.
> 3 votes

---
Tags: xna, c#, xna-4.0
---


title: Stage3D: Camera pans the whole screen

text:
# Question
Title: Stage3D: Camera pans the whole screen
I am trying to create a 2D Stage3D game where you can move the camera around the level in an RTS style. I thought about using Orthographic Matrix3D functions for this but when I try to scroll the whole "stage" also scrolls.

This is the Camera code:

```
    public function Camera2D(width:int, height:int, zoom:Number = 1) {
        resize(width, height);
                    _zoom = zoom;
    }

    public function resize(width:Number, height:Number):void {
        _width = width;
        _height = height;

        _projectionMatrix = makeMatrix(0, width, 0, height);

        _recalculate = true;
    }

    protected function makeMatrix(left:Number, right:Number, top:Number, bottom:Number, zNear:Number = 0, zFar:Number = 1):Matrix3D {
        return new Matrix3D(Vector.<Number>([
            2 / (right - left), 0, 0, 0,
            0, 2 / (top - bottom), 0, 0,
            0, 0, 1 / (zFar - zNear), 0,
            0, 0, zNear / (zNear - zFar), 1
        ]));
    }

    public function get viewMatrix():Matrix3D {
        if (_recalculate) {
            _recalculate = false;

            _viewMatrix.identity();
            _viewMatrix.appendTranslation( -_width / 2 - _x, -_height / 2 - y, 0);
            _viewMatrix.appendScale(_zoom, _zoom, 1);

            _renderMatrix.identity();
            _renderMatrix.append(_viewMatrix);

            _renderMatrix.append(_projectionMatrix);
        }

        return _renderMatrix;
    }

```

And the camera is send directly to the GPU with: `c3d.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, cameraMatrix, true);`

And these are the shaders:

```
------Vertex Shader------
m44 op, va0, vc0
mov v0, va1.xy
mov v0.z, va0.z

------Fragment Shader------
tex ft0, v0, fs0 <2d,linear,nomip>
mov oc, ft1

```

---

Here is a example and here are two screenshots to show what I mean:

How do I only let the inside of the stage3D scroll and not the whole stage?

# Answer
I already figured it out, the problem was in the fact that I had different passes for the shaders.

So my shader logic was like this:

1. Draw Stage to Texture as normal and as diffuse map
2. Draw the Texture to the Stage

And for both passes I used the same transformation `Matrix3D`, so when the Stage was panned the texture that the whole Stage was drawn on was also panned. The solution is that all I had to do was create a simple `Matrix3D` object for drawing the Textures to the Stage, because the positions of the Texture should never change.
> 0 votes

---
Tags: flash, actionscript-3, camera, matrix, stage3d
---


# Question
Title: Saving a list of points into a text file
I recently posted a question about this, but was not really sure where to go. I've gotten some progress, and have generated some simple noise here:

http://pastie.org/5408655

That works well enough for me, but I would really like to be able to save the points into an ascii text file. currently it's formatted so that something like this:

11111111

11111111

11111111

11111111

would create a square. I need to save in this format with the points(and lines connecting them) generated in the method above.

Essentially, I need to write the array of points created in the first example to a text file formatted like the second example. EDIT: I ended up using serialization. This method makes it un-editable, but works for my purposes, I can really have good terrain generation now. here's my code: http://pastie.org/5455624 Everything is working excellently. Thanks to all those who helped

# Answer
> 3 votes
You could consider `Serialization`

http://www.tutorialspoint.com/java/java\_serialization.htm

Advantages

1. Hides your values
2. Easier to save/load

Disadvantages

1. Values can not be modified in text editor.

---
Tags: java, tiles, terrain, side-scroller, perlin-noise
---


# Question
Title: Getting into the details of game engine programming
I am interested in learning game programming, but I really have an interest in the *lower level* engineering in games. I have OpenGL experience, and I am really interested in learning more about implementing AI, Physics, etc. I have a computer science degree, so I really like getting into technical stuff.

Many times when I ask about this sort of thing, I get a lot of "Use an engine", "Use Unity3d", "Why waste your time writing code that already exists", etc, etc. My idea was to use simpler libraries such as SFML or XNA so that I could learn how to implement the more complex systems.

The thing is, although I do want to write games, I want to learn things that using something like Unity simply doesn't teach you. My goal is not to make a current generation quality 3D game to sell, I just want to make some cool smaller games and learn all I can about the programming side of game development.

**Is this something that people just do not do anymore?**

It seems like everywhere I turn people are using Unity or UDK or GameMaker. I fully understand why you would use a tool like these, but I cant see how they would suit my purposes.

**So where does someone like myself turn? Am I trying to learn something that people just do not bother doing anymore? Is the innovation in this area gone and just all about gameplay now?**

I'm sorry if this question seems silly, but I am genuinely interested in knowing more about this and meeting more people who are interested in this sort of thing.

# Answer
Regardless of what known engine you use, the chances of you making a game that becomes the next big thing or even nets a profit over the development time and costs are pretty slim. Therefore the real goal is doing what you enjoy, and if that is playing at the lower level and creating your own engine, then by all means go for it.

Some people like to be able to have something more to show for their work in the eyes of someone who doesn't understand programming, thus the huge appeal of such engines as unity 3d and such. But the bottom line is enjoying what you do and learning something, so I say go for it. I'm sure you will find some like minded people to help, I am the same way I really dislike using engines I don't understand the inner workings of.
> 1 votes

# Answer
If you're interested in getting into engine development I would check out a good survey book like Game Engine Architecture, Realtime Rendering, or Real-Time Collision Detection

You can also learn a lot by checking out the successful open source projects out there like Box2d or Recast.

You might also enjoy spending some time dissecting previous engines that have release their source: http://fabiensanglard.net/doom3/index.php
> 1 votes

# Answer
> Is this something that people just do not do anymore?

**No.** People are working low-level on game engines all the time. Otherwise you'd never get new versions of Unity or the Unreal Engine with all those fancy features.

> So where does someone like myself turn? Am I trying to learn something that people just do not bother doing anymore? Is the innovation in this area gone and just all about gameplay now?

**Keep going, and be good at it**, we'll need low-level engineers for a long time to come. Innovation happens everywhere, from the very high level to the very low level.

But don't limit your vision to a small part of the spectrum, you should always maintain a good picture of how things work at all levels. A side effect of team sizes growing is that people are getting more and more specialized, so a deep knowledge of the machine *is* valuable, as long as you're able to work in a team so this knowledge gets beneficial to everybody.
> 1 votes

# Answer
If you studied OpenGl you are on the right track.

Also read about the DirectX, The understanding of it might be useful due to the fact that Microsoft always gives some bonuses to the users of their software..
> 0 votes

---
Tags: architecture
---


# Question
Title: OOP implementation of BUFFS and Stats. Suggestion
I am developing an MMORPG server using NodeJS.

I am not sure how to implement Buffs, i mean, equipped objects or used skills have effects on the Player() which has many Stats(), some of them have a max cap...

Effects can change the Stat value, increasing or decreasing it by a value, a percentage or completly rewrite the value of the stat.

After a while I have decided to create a base class for buffs, which can be hidden (if they are casted from an equipped object) or shown if they came from an ability (Spell).

Anyway I need suggestion how to implement it, use an array for all active buffs for a stat and have a function calculate the value of the stat affected by buffs each time I need the value of the stat or...? Other more OOP's ways to do it?

I have read this What's a way to implement a flexible buff/debuff system? but this implements only a percentage system, which buffs can only say "+10%, +20%, etc...", but I would love to have an hybrid system, which can have percentage values or static values (like WoW does), and using modifiers it's hard to implement, because modifiers refers to the current value of stat :/

Thanks for suggestions :)

# Answer
> 3 votes
Just some short ideas:

1. Only re-calculate the Player's stats when buffs/debuffs occure, not when you need the value. Much likely to what Sequel-based Databases do with indicies (MySQL for example updates the index cache on each write execution providing a verry fast interface for reading data).
2. When you have multiple Types of values, you need to think of a formula or a hirachy. EvE online for example uses mostly percentage values with a stacking penalty. You take each percentage value into an array, sort it so the highest value comes in first, then for each percentage value in the array the following recieves a higher penalty. This is basicly a formula instead of a hierachy. Ragnarok Online did something simillar, there you had fixed values and percentages, you first took all your fixed + and - modifiers, added them to your base value, then added all the percentages onto that value.

its really up to your game design, everyone does it diferently.

for the OOP question:

I would highly recommend looking into entity systems, using effects as baseclass for buffs, debuffs, item boni, etc and stack them all into one array, or remove them when their timer runns out or whatever you like.

# Answer
> 3 votes
A little example for you, i hope it will be helpful.

```
// Base game object
var GObject = function () {
    // Entities storage
    this.entity = {
        hp: new GEntityHp()
        // ...
    };

    // Storage for buffs, debuffs
    this.buffs = [];
};

GObject.prototype.addBuff = function (buff) {
    buff.applyTo(this);

    this.buffs.push(buff);
};

// Entity Health
var GEntityHp = function () {
    // Unique entity name
    this.name = 'hp';

    // Entity components
    this.data = {
        curValue: 1, // current health value
        maxValue: 1, // maximum health value
        maxBonus: 0  // maximum health bonus, %
    }
};

GEntityHp.prototype.getCur = function () {
    return this.data.curValue;
};

GEntityHp.prototype.getMax = function () {
    return this.data.maxValue + this.data.maxValue * this.data.maxBonus / 100;
};

GEntityHp.prototype.update = function (list) {
    var self = this;
    list.forEach(function (data) {
        data.key in self.data && (self.data[data.key] += data.value);
    });
};

// Game buff
var GBuff = function (data) {
    // Buff bonuses grouped by entity name
    this.data = data || {};

    this._applied = false;
};

// Apply buff to given game object..
GBuff.prototype.applyTo = function (gObject) {
    if (!this._applied) {
        this._applied = true;

        var self = this;

        Object.keys(this.data).forEach(function (entityName) {
            var entity = gObject.entity[entityName];

            if (entity) {
                entity.update(self.data[entityName]);
            }
        });

    }
};

// Let test

var gObject = new GObject();

gObject.addBuff(new GBuff({
    hp: [
        {key: 'maxValue', value: 99},
        {key: 'maxBonus', value: 25}
    ]
}));

alert('hp: ' + gObject.entity.hp.getCur() + ',' + gObject.entity.hp.getMax());

```

# Answer
> 1 votes
Since you wish to have three types of buffs, you will need a priority system. Which types of buffs comes first? Do you completely change the stat and then add values or ignore other buffs?

Since you wish to use OOP I would use an Interface for this. Every spell, weapon or piece of equipment that is imbued with power should implement this IBuff interface. The interface will include a getter function that classifies the type of buff and when it comes into play(priority) and another getter that determines the potency of the buff for the calculation.

Weapons or equipment that is not buffed should implement the interface and possibly return some generic value such as -1, 0 or null for these values.

Mind you, it probably overkill and not wise to think of buffs as objects. It would be wiser to think of them as components. Then you can have a few objects for buffs and simply add them as members to buffed items.

---
Tags: javascript, architecture, mmo, node.js, effect-modifier
---


title: Learning resource for 3d modeling

text:
# Question
Title: Learning resource for 3d modeling
I want to start learning 3d modeling. I already have experience with maya and 3dsmax but I made a long pause (2 years)

Now I have free access to maya, 3dsmax and blender (I am a student). I know that all tools are very powerful so I thought I just pick the one with the best learning materials.

The best site that I found is http://www.digitaltutors.com/11/index.php and it has over 7600 videos for maya.

Maybe you can recommend me some other learning sites that are as good as digitaltutors?

# Answer
> 2 votes
I have been learning how to use Blender on CGcookie, that is why I will recommend you the page - http://cgcookie.com/

It gives you tutorials on 3DS MAX and Blender which is similar to Maya (there is a Maya Mode), and its definitely worth getting the premium access (I learned a lot there). + its only ~ $30 for 90 days

I am not saying that open source is always better (its definitely cheaper) but in your situation I'd also give Blender a try, you will probably love it!

On the website. They have many videos + resources (models from the tutorial, textures etc.)

I'd also suggest that you visit the official Autodesk tutorial page

http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=16759124&linkID=9241175

And definitely go to one of these :)

http://cgcookie.com/blender/

http://cgcookie.com/max/

Goog luck in your training!

# Answer
> 2 votes
I highly recommend http://www.3dbuzz.com They have videos for many skill levels, though if you have an advanced level of skill with it already some of them will be pointless. Most videos require a membership but the introduction to Maya series is free in its entirety. Ive worked through some of them my self, and have watched some of their other videos on other topic and really enjoy the site as a whole.

---
Tags: 3d, animation, blender, 3dsmax, maya
---


# Question
Title: Changing the color of a sprite at runtime
Is there a form to change the color of a sprite in runtime?}

I have a black point loaded with an image, but i dont want to load various images with different colors, is there a mode to change the color in runtime and not loading lot of images?

And i want to tell it what part to color of the sprite, is it possible?

# Answer
> 8 votes
I had to do something like this in XNA with pixel-art sprites. The best way i've found was using pixel shader.

The sprites are done in gray-scale (8 bits colors without alpha), then you'll have to map each gray-color to the correspondent 32 bit color you want, using a 256 lenght array of Colors.

In the shader you can use the gray colors of the sprite as a look-up table to the array of 32 bit colors.

# Answer
> 3 votes
If you refer to libgdx then the class com.badlogic.gdx.graphics.g2d.Sprite provides two different methods called setColor: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/g2d/Sprite.html#setColor(com.badlogic.gdx.graphics.Color)

# Answer
> 3 votes
```
Color c = new Color(batch.getColor());
batch.setColor(a,b,c,d);
batch.draw(yourSprite, x, y);
batch.setColor(c);

```

---
Tags: sprites, libgdx
---


# Question
Title: Unity Android: Truecolor texture performance hit and alternatives for truecolor
After integrating the graphics assets to my application, I noticed that when the textures are compressed they look very bad compared to truecolor. This happens to all the textures and it did not seem to help changing the texture type to GUI nor did it help to switch the 32-bit display buffering on.

Does using truecolor textures make the application much heavier to run? Or does it just increase the size of the .APK? Are there alternatives to getting a good texture quality and a smaller texture size instead of using truecolor?

**EDIT:** I did some experiments with the dithering. I created a textures in GIMP 2.8, one which was RGB and one which was indexed with 255 colours and Floyd-Steinberg dithering with reduced colour bleeding. In the Windows Explorer this looked promising, the image quality had hardly been reduced but the size was halved.

But when they were imported to Unity, they were exactly the same size. And trying out different formats, there was not much noticeable difference between the image quality. Although the banding was a little bit less pronounced but still clearly seen.

**EDIT 2:** I played around with the importing settings. And the only conclusion I can come up with is: ***Don't use alpha!*** Without the alpha channel, there is no banding with the ETC-compression which is supported by all OpenGL ES 2.0 GPUs.

To have an alpha channel and no banding. I had to go all the way to RGBA 32-bit, which increased the texture file size to 64Kb compared to the no alpha channel ETC's 8Kb.

Here again: not much difference between the GIMP dithered and the RGB versions. So conclusion with this: **Dithering in GIMP did next to nothing.**

# Answer
Compression setting for a texture is different from Texture Type. See here

This screen is from windows project, Android would probably have slightly different settings, but it should have at least one uncompressed option.

Note that uncompressed textures need WAY more memory during runtime (and more space in APK too).
> 1 votes

# Answer
First off: As with any optimization, first check if this is a problem, only then try to solve it.

> Does using truecolor textures make the application much heavier to run?

When compared to compressed textures, truecolor textures mainly take more RAM. The compressed data also takes less bandwidth to transfer around and may also help with cache hits (depending on where the cache is located in the pipeline).

I haven't benchmarked it, nor can't I find any easily accessible benchmark, but I'd guess that unless you're using huge textures, you probably won't see much of a difference in performance, especially if you're using mipmaps properly.

> Or does it just increase the size of the .APK?

Not sure how unity handles these things, but "truecolor" textures may be shipped as jpg images, for instance, in which case they will probably take less space (1:10 or better) in an apk than ETC compressed files (1:4 or 1:6) would.

> Are there alternatives to getting a good texture quality and a smaller texture size instead of using truecolor?

Sure, but that depends on how much effort you're willing to put into it. There's always a cost..

Procedurally generated textures fully in the shader, building a big texture from tiles within a shader, or using detail textures to mask the low resolution of the main texture are some techniques that come to mind.

If you can get away with it, just store your texture as grayscale and tint it in a shader. Next, you can combine several textures into a single texture's R, G and B channels, and separate them in a shader to grayscale and tint it.

A word of warning regarding paleted textures: they're hardly supported by any hardware these days and may end up being "plain" truecolor textures in the end (eating memory etc). Simulating a paleted texture using shaders is one interesting option though, but I wouldn't go there unless I needed to do palette-cycling effects or some such.
> 1 votes

---
Tags: android, unity, textures
---


# Question
Title: Fast software color interpolating triangle rasterization technique
I'm implementing a software renderer with this rasterization method, however, I was wondering if there is a possibility to improve it, or if there exists an alternative technique that is much faster. I'm specifically interested in rendering small triangles, like the ones from this 100k poly dragon:

As you can see, the method I'm using is not perfect either, as it leaves small gaps from time to time (at least I think that's what's happening).

I don't mind using assembly optimizations. Pseudocode or actual code (C/C++ or similar) is appreciated.

# Answer
> 2 votes
Rasterizing triangles in software is commonly done using either Bresenham's algorithm or using a differential digital analyzer (DDA) with fixed point math to interpolate the values. Bresenham uses a lot of branching, so is probably less efficient than a fixed-point DDA on modern CPUs.

The tutorial you have linked uses an odd mix of C++ classes, floating point math, and a per-pixel function call to set the colors. You can do a lot better than that example by just writing less inefficient code! Both Bresenham and DDA will get you more numerical stability than mixing floats and ints haphazardly as in the linked tutorial (a probable cause of the gaps you see).

---
Tags: optimization, computational-geometry, software-rendering, rasterization
---


# Question
Title: How to pass one float as four unsigned chars to shader by glVertexPointAttrib?
For each vertex I use two floats as position and four unsigned bytes as color. I want to store all of them in one table, so I tried casting those four unsigned bytes to one float, but I am unable to do that correctly...

All in all, my tests came to one point:

```
    GLfloat vertices[] = { 1.0f, 0.5f, 0, 1.0f, 0, 0 };
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
        vertices);

// VER1 - draws red triangle
//  unsigned char colors[] = { 0xff, 0, 0, 0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
//          0xff };
//  glEnableVertexAttribArray(1);
//  glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte),
//          colors);

// VER2 - draws greenish triangle (not "pure" green)
//  float f = 255 << 24 | 255; //Hex:0xff0000ff
//  float colors2[] = { f, f, f };
//  glEnableVertexAttribArray(1);
//  glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte),
//          colors2);

// VER3 - draws red triangle
int i = 255 << 24 | 255; //Hex:0xff0000ff
int colors3[] = { i, i, i };
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte),
        colors3);

glDrawArrays(GL_TRIANGLES, 0, 3);

```

Above code is used to draw one simple red triangle. My question is - why do versions 1 and 3 work correctly, while version 2 draws some greenish triangle? Hex values are one I read by marking variable during debug. They are equal for version 2 and 3 - so what causes the difference?

Edit: Question is already answered, I just want to add some more information, to clarify my motives for eventual future readers.

I am aware, that when copied to graphics memory, all values will be eventually stored as floats (even 4 unsigned bytes). "Packing" 4 colors into one float is used by me just to decrease memory usage by color values in my VertexBufferObject class, where all vertex values are stored in one float array. Thanks to this approach, color information for each vertex (RGBA) is stored into single float value, instead of four. Memory usage is significantly lower, at small cost of one additional reinterpret\_cast at color creation/change

# Answer
```
float f = 255 << 24 | 255

```

This code converts the integer value 0xff0000ff into a float-representation of the value, which uses a completely different (and complex) memory layout. Since you are using GL\_UNSIGNED\_BYTE, OpenGL is unable to interpret it correctly, so... you're getting gibberish.

If you really want to pack into a float array (seems silly to me), use reinterpret\_cast.
> 1 votes

# Answer
Interleaved arrays allows you to store them in one chunk of contiguous memory, by just adjusting the pointer offsets.

```
struct {
  float xy[2];
  unsigned char rgba[4];
} vertices = { ... };

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 12, vertices.xy);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 12, vertices.rgba);

```

Or you you can use a union to convert an RGBA quartet to a float with the same bit representation...

```
float pack_color(unsigned char rgba[4])
{
    union { float f; unsigned char rgba[4]; } u;
    u.rgba[0] = rgba[0];
    u.rgba[1] = rgba[1];
    u.rgba[2] = rgba[2];
    u.rgba[3] = rgba[3];
    return u.f;
}

```
> 3 votes

# Answer
You cannot break a float into four bytes that make sense individually. Floats conform to a certain format, namely 1 sign bit, 8 exponent bits and 23 mantisa bits.

```
    S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMMMM

```

breaking it up into 4 bytes yields this

```
   [SEEE EEEE]
   [EMMM MMMM]
   [MMMM MMMM]
   [MMMM MMMM]

```

Once you print a binary value of 1.0f, 1.1f, 1.453f and 2.735f you will see why mangling floats and doubles have no practical value; if you want floats use them as floats - else use integers ;)
> 2 votes

# Answer
Let's read some documentation (GL may have a reputation for being easy but that doesn't mean that you get to skip reading documentation).

http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml

> **size**
>
> Specifies the number of components per generic vertex attribute
>
> **type**
>
> Specifies the data type of each component in the array

OK, so you're using 4 components and your "type" param is GL\_UNSIGNED\_BYTE, which means that the data you use for your "pointer" param will be interpreted as 4 unsigned bytes.

In other words, **glVertexAttribPointer will not do any type conversion for you** (GLvoid * as the data type of the pointer param should be sufficient hint of that). You tell it what type you're using for your data via it's parameters, and GL will interpret your data as if it was that type, and nothing else.
> 0 votes

---
Tags: opengl
---


# Question
Title: When to unload graphics object from main memory?
I writing my resource mangaer, and I consider about how it can work for graphics objects (like textures, meshes).
I think about this :
I want to load texture (in pseudocode):

```
Texture t = resMgr.GetTex("image.png");

```

and `GetTex` make something like this:

1. load texture from disk to main memory
2. create texture object (load it to gpu memory)
3. unload texture from main memory

I consider about 3 step, does game engines that you know unload meshes/textures after load them into gpu memory ?

# Answer
> 2 votes
No, fetching them from the hard drive is very time-intensive. It is possible that you have so much texture/model/animation data that everything will not fit concurrently on the GPU, especially for someone using an older graphics card or laptop.

Main memory is probably the cheapest resource you have to work with on a modern computer. You should leave things like unloading textures from memory for when you are switching maps.

# Answer
> 2 votes
Loading and unloading resources at runtime is not practical. The only time you do that is when you are streaming resources.

A general idea to go on is to load rescouers that you need for a current map or segment. and when the player is past that to unload the rescoures. Never keep something you dont need, but keep what you need now or soon.

# Answer
> 1 votes
You should generally free your mesh and texture data after uploading into OpenGL textures or vertex buffers. The driver must keep a copy of your data in any case, so why waste memory by keeping another useless copy around?

Main memory may be cheap, but even so you shouldn't waste for no reason. Especially not on 32-bit architectures where you may bump into the 4GB per-process virtual address space limit sooner rather than later.

The best performing method to load mesh data, if using OpenGL, is to:

1. Create vertex buffer object.
2. Use glMapBuffer to get a pointer to driver memory.
3. Load data directly into driver memory.
4. glUnmapBuffer to tell the driver you've finished filling the buffer with data.

Less applicable on textures, since the driver may need to convert your data to an internal format.

---
Tags: architecture, resource-management
---


# Question
Title: Multiple objects listening for the same key press
I want to learn the best way to implement this:

I have a hero and an enemy on the screen. Say the hero presses "k" to get out a knife, I want the enemy to react in a certain way.

Now, if in my game loop I have a listener for the key press event and I identify a "k" was pressed, the quick and easy way would be to do:

```
// If K pressed
// hero.getOoutKnife()
// enemy.getAngry()

```

But what is commonly done in more complex games, where say I have 10 types of character on screen and they all need to react in a unique way when the letter "k" is pressed?

I can think of a bunch of hacky ways to do this, but would love to know how it should be done properly.

I am using C++, but I'm not looking for a code implementation, just some ideas on how it should be done the right way.

# Answer
Well, if you're talking about much, much more advanced games, rather than having an enemy react to the press of the button, you'd have the enemy's AI react to "seeing" the player *armed* with a knife, and "seeing" it would require that the player was in line of sight, and the enemy "inspected" the character, in terms of health/equipment/etc, and then based on the final determination, "angry" was what the enemy AI decided on.

ie: on each update-cycle (or every several, to save CPU), have each enemy that's in-range, check to see that they've still got sight of the hero and run a basic AI routine to choose their strategy, based on what they inspect.

If your question is more about what to do about an event which several things need to know about, in general...

Suppose `ESC` is to toggle "pause"/"main-menu" if you're in-game, but it's also used to back out of sub-menus, if you're in a sub-menu, setting options, or to close your character's stat/inventory screen in real-time, during gameplay.

So now you've got all of these things which need to know when ESC is being pressed.

Instead of tying them all together in one gigantic function with a boatload of conditional statements to work through what should happen...
...you should look into a pattern where various menus can `subscribe` (or "register" or "listen") to the keypress event, and fire their own methods when notified about the event in question.

I'm most used to JavaScript now, so it almost feels like cheating, with how easily you can pass methods back and forth.

But with a little bit of planning, you can use the `Mediator` pattern to create one "emitter" per type of thing that you want to listen to:

Say you have an `Input` mediator, which listens for keyboard presses and mouse clicks, and deals with all of the hard stuff like timestamps and working out screen-coordinates and the rest.

Then, using a "subscribe" or "listen" method of input, each object interested in being notified will subscribe to something:

```
//[pseudo]
input.subscribe("input/keypress/ESC", thisObj);
input.subscribe("input/keypress/SPACE", otherObj);
input.subscribe("input/keypress/ESC", anotherObj);

```

Then, when Input hears about a keypress and works it out to be the proper key, it will `publish` or `notify` (or whatever), all of the objects which have subscribed (and support the proper interface).

```
//[pseudo]
input.notify("input/keypress/ESC", data_to_send_to_each_subscriber);

```

So now, if you're in-game, the game window can subscribe to `ESC` to pause, and unsubscribe to `ESC` once it IS paused (and subscribe again when it resumes). Other menus can subscribe to `ESC` as soon as they're initialized, or "opened", or whatever (depending on if you want to create new instances every time, or use the same one), and unsubscribe when they're being closed.

Now your menus don't need to know about one another, and they don't all need to be a part of the same function/switch/whatever... ...they just need to know when to listen, and when to clean up after themselves.
> 6 votes

# Answer
Well your enemies shouldn't be reacting to a key press, since they're not controlled by the player.

One way to do this would be to implement a system where enemies know what's in their vicinity. When your player is in a certain radius of enemies, the enemies could react in different ways (get suspicious/get angry when he gets out his knife/etc).

The way I would handle this would be to have a certain area around enemies that is considered "in range", when the player performs an action, you could raise an event for all enemies that have the player in range and the logic of how they react would be executed by the enemy objects themselves.

I guess my point is, having enemies react to key presses directly isn't terribly good design.
> 2 votes

# Answer
Your problem can be solved through applying the Observer Pattern.

You have Subjects like the keyboard key handlers, and you have Observers like the player character which need to react on events.

Every Observer can "subscribe" to one or more Subjects. This causes the Subject to add the Observer to an internal list. When something happens in the Subject, it calls a method on every Observer which subscribed to it. The Observer can then react on the event as it sees fit.

But as the others pointed out: Entities like enemies shouldn't react on user input directly - they should react on the behavior of the entity which is controlled by the player. The Observer pattern can also be used in that context, but there are also other patterns to consider (like using a Controller or just have each enemy check the state of the player in the game logic update loop).
> 1 votes

---
Tags: architecture
---


# Question
Title: What causes the iOS OpenGLES driver to allocate extra memory?
I'm trying to optimize the memory usage of our iOS game and I'm puzzled about when/why the iOS GLES driver allocates extra memory at runtime... When I run our game through Instruments with the OpenGL ES Driver instrument the gartUsedBytes value can fluctuate quite wildly. We preload all our textures and build the buffer objects up front, so it's not the game engine requesting extra memory from GL.

Currently we are manually requesting around 50MB of GL memory, yet the gartUsedBytes value sits at around 90MB most of the time, peaking at 125MB from time to time. It seems to be linked to what you are rendering that frame - our PVS only submits VBO's for visible meshes.

Can anyone shed some light on what the driver is doing in the background ? Like I said earlier, all our game engine allocations are done on level load, so in theory there shouldn't be any fluctuation on GL memory usage while the level is running.

Thanks.

# Answer
> 1 votes
and welcome to the world of "binned", "tiled", or "scene capture" rendering.

The screen on most mobile devices (Adreno, PowerVR, Mali at least) is split into smaller tiles, and when you render something, the driver actually records your rendering commands, and when it has no other option, it starts rendering.

Then it re-plays those commands from said buffers for each tile.

That's a bit trivial way of explaining what's going on, but the details don't really matter.

Oddly enough, this is more efficient in both rendering performance and power use than rendering directly to a large framebuffer - you can have a small amount of very, very, VERY fast memory which contains one tile.

---
Tags: ios, opengl-es2
---


# Question
Title: What technology(s)would be suitable for the front end part of a Java web game?
As asked in a previous question, I'm looking to create a small MMO that will be deployed onto GAE.

I'm confused about what technologies I could use for the user interface, I've considered the following

1. **JSP Pages** \- I've got experience with JSP/JSTL and I would find this easy to work with, it would require the user having to "submit" the page each time they perform an action so may become a little clumsey for players.
2. **Applet** \- I could create an applet that sits on the front end and communicates to the back end game engine, however I'm not sure how good this method would be and have not used applets since university..

What other options do I have? I don't have any experience in Flash/Flex so there would be a big learning curve there.

Are there any other Java based options I may be able to use?

My game will be text based, I may use some images, but I'm not intending to have any animations/graphics etc

Thanks

# Answer
**JSP Pages that automatically refresh/poll via JavaScript ("AJAX").** An applet is overkill and would be tough to get to interact with GAE as your "server". Now if you had a dedicated server for socket communications then I would say applet, but given your situation, the best option is to learn some JavaScript so that you can update the page dynamically.

That being said, if you're not familiar with JavaScript, that's a pretty big learning curve just to create your text game.

This is how, for example, Gmail can show you new emails while you're on the page; it uses JavaScript and polls the server in the background.
> 2 votes

# Answer
If you're looking for something Java-based, GWT seems like a natural fit, even though I've never tried to use it for a game.

That being said if you're juste looking for a simple client, you might find that Flex learning curve is not so steep, and, as a bonus, it will allow you to easily extend your game if need be.
> 3 votes

# Answer
Did you consider using WebSockets? This is a relatively new Javascript feature which allows web applications to communicate bi-directional with a server in real-time. It's much more efficient than ajax because it allows the server to send data to the client without receiving a request for it.
> 1 votes

---
Tags: java
---


title: Point of contact of 2 OBBs?

text:
# Question
Title: Point of contact of 2 OBBs?
I'm working on the physics for my GTA2-like game so I can learn more about game physics.

The collision detection and resolution are working great.

I'm now just unsure how to compute the point of contact when I hit a wall.

Here is my OBB class:

```
public class OBB2D
{
   private Vector2D projVec = new Vector2D();
   private static Vector2D projAVec = new Vector2D();
   private static Vector2D projBVec = new Vector2D();
   private static Vector2D tempNormal = new Vector2D();
   private Vector2D deltaVec = new Vector2D();

// Corners of the box, where 0 is the lower left.
   private  Vector2D corner[] = new Vector2D[4];

   private Vector2D center = new Vector2D();
   private Vector2D extents = new Vector2D();

   private RectF boundingRect = new RectF();
   private float angle;

    //Two edges of the box extended away from corner[0].
   private  Vector2D axis[] = new Vector2D[2];

   private double origin[] = new double[2];

   public OBB2D(float centerx, float centery, float w, float h, float angle)
    {
       for(int i = 0; i < corner.length; ++i)
       {
           corner[i] = new Vector2D();
       }
       for(int i = 0; i < axis.length; ++i)
       {
           axis[i] = new Vector2D();
       }
       set(centerx,centery,w,h,angle);
    }

   public OBB2D(float left, float top, float width, float height)
  {
       for(int i = 0; i < corner.length; ++i)
       {
           corner[i] = new Vector2D();
       }
       for(int i = 0; i < axis.length; ++i)
       {
           axis[i] = new Vector2D();
       }
       set(left + (width / 2), top + (height / 2),width,height,0.0f);
   }

   public void set(float centerx,float centery,float w, float h,float angle)
   {
       float vxx = (float)Math.cos(angle);
       float vxy = (float)Math.sin(angle);
       float vyx = (float)-Math.sin(angle);
       float vyy = (float)Math.cos(angle);

           vxx *= w / 2;
           vxy *= (w / 2);
           vyx *= (h / 2);
           vyy *= (h / 2);

           corner[0].x = centerx - vxx - vyx;
           corner[0].y = centery - vxy - vyy;
           corner[1].x = centerx + vxx - vyx;
           corner[1].y = centery + vxy - vyy;
           corner[2].x = centerx + vxx + vyx;
           corner[2].y = centery + vxy + vyy;
           corner[3].x = centerx - vxx + vyx;
           corner[3].y = centery - vxy + vyy;

           this.center.x = centerx;
           this.center.y = centery;
           this.angle = angle;
           computeAxes();
           extents.x = w / 2;
           extents.y = h / 2;

           computeBoundingRect();
   }

   //Updates the axes after the corners move.  Assumes the
   //corners actually form a rectangle.
   private void computeAxes()
   {
       axis[0].x = corner[1].x - corner[0].x;
       axis[0].y = corner[1].y - corner[0].y;
       axis[1].x = corner[3].x - corner[0].x;
       axis[1].y = corner[3].y - corner[0].y;

       // Make the length of each axis 1/edge length so we know any
       // dot product must be less than 1 to fall within the edge.

       for (int a = 0; a < axis.length; ++a)
       {
        float l = axis[a].length();
        float ll = l * l;
        axis[a].x = axis[a].x / ll;
        axis[a].y = axis[a].y / ll;
           origin[a] = corner[0].dot(axis[a]);
       }
   }

   public void computeBoundingRect()
   {
       boundingRect.left = JMath.min(JMath.min(corner[0].x, corner[3].x), JMath.min(corner[1].x, corner[2].x));
       boundingRect.top = JMath.min(JMath.min(corner[0].y, corner[1].y),JMath.min(corner[2].y, corner[3].y));
       boundingRect.right = JMath.max(JMath.max(corner[1].x, corner[2].x), JMath.max(corner[0].x, corner[3].x));
       boundingRect.bottom = JMath.max(JMath.max(corner[2].y, corner[3].y),JMath.max(corner[0].y, corner[1].y));
   }

   public void set(RectF rect)
   {
       set(rect.centerX(),rect.centerY(),rect.width(),rect.height(),0.0f);
   }

    // Returns true if other overlaps one dimension of this.
    private boolean overlaps1Way(OBB2D other)
    {
        for (int a = 0; a < axis.length; ++a) {

            double t = other.corner[0].dot(axis[a]);

            // Find the extent of box 2 on axis a
            double tMin = t;
            double tMax = t;

            for (int c = 1; c < corner.length; ++c) {
                t = other.corner[c].dot(axis[a]);

                if (t < tMin) {
                    tMin = t;
                } else if (t > tMax) {
                    tMax = t;
                }
            }

            // We have to subtract off the origin

            // See if [tMin, tMax] intersects [0, 1]
            if ((tMin > 1 + origin[a]) || (tMax < origin[a])) {
                // There was no intersection along this dimension;
                // the boxes cannot possibly overlap.
                return false;
            }
        }

        // There was no dimension along which there is no intersection.
        // Therefore the boxes overlap.
        return true;
    }

    public void moveTo(float centerx, float centery)
    {
        float cx,cy;

        cx = center.x;
        cy = center.y;

        deltaVec.x = centerx - cx;
        deltaVec.y  = centery - cy;

        for (int c = 0; c < 4; ++c)
        {
            corner[c].x += deltaVec.x;
            corner[c].y += deltaVec.y;
        }

        boundingRect.left += deltaVec.x;
        boundingRect.top += deltaVec.y;
        boundingRect.right += deltaVec.x;
        boundingRect.bottom += deltaVec.y;

        this.center.x = centerx;
        this.center.y = centery;
        computeAxes();
    }

    // Returns true if the intersection of the boxes is non-empty.
    public boolean overlaps(OBB2D other)
    {
        if(right() < other.left())
        {
            return false;
        }

        if(bottom() < other.top())
        {
            return false;
        }

        if(left() > other.right())
        {
            return false;
        }

        if(top() > other.bottom())
        {
            return false;
        }

        if(other.getAngle() == 0.0f && getAngle() == 0.0f)
        {
            return true;
        }

        return overlaps1Way(other) && other.overlaps1Way(this);
    }

    public Vector2D getCenter()
    {
        return center;
    }

    public float getWidth()
    {
        return extents.x * 2;
    }

    public float getHeight()
    {
        return extents.y * 2;
    }

    public void setAngle(float angle)
    {
        set(center.x,center.y,getWidth(),getHeight(),angle);
    }

    public float getAngle()
    {
        return angle;
    }

    public void setSize(float w,float h)
    {
        set(center.x,center.y,w,h,angle);
    }

    public float left()
    {
        return boundingRect.left;
    }

    public float right()
    {
        return boundingRect.right;
    }

    public float bottom()
    {
        return boundingRect.bottom;
    }

    public float top()
    {
        return boundingRect.top;
    }

    public RectF getBoundingRect()
    {
        return boundingRect;
    }

    public boolean overlaps(float left, float top, float right, float bottom)
    {
        if(right() < left)
        {
            return false;
        }

        if(bottom() < top)
        {
            return false;
        }

        if(left() > right)
        {
            return false;
        }

        if(top() > bottom)
        {
            return false;
        }

        return true;
    }

    public static float distance(float ax, float ay,float bx, float by)
    {
      if (ax < bx)
        return bx - ay;
      else
        return ax - by;
    }

    public Vector2D project(float ax, float ay)
    {
        projVec.x = Float.MAX_VALUE;
        projVec.y = Float.MIN_VALUE;

      for (int i = 0; i < corner.length; ++i)
      {
        float dot = Vector2D.dot(corner[i].x,corner[i].y,ax,ay);

        projVec.x = JMath.min(dot, projVec.x);
        projVec.y = JMath.max(dot, projVec.y);
      }

      return projVec;
    }

    public Vector2D getCorner(int c)
    {
        return corner[c];
    }

    public int getNumCorners()
    {
        return corner.length;
    }

    public static float collisionResponse(OBB2D a, OBB2D b,  Vector2D outNormal)
    {

        float depth = Float.MAX_VALUE;

        for (int i = 0; i < a.getNumCorners() + b.getNumCorners(); ++i)
        {
            Vector2D edgeA;
            Vector2D edgeB;
            if(i >= a.getNumCorners())
            {
                edgeA = b.getCorner((i + b.getNumCorners() - 1) % b.getNumCorners());
                edgeB = b.getCorner(i % b.getNumCorners());
            }
            else
            {
                edgeA = a.getCorner((i + a.getNumCorners() - 1) % a.getNumCorners());
                edgeB = a.getCorner(i % a.getNumCorners());
            }

             tempNormal.x = edgeB.x -edgeA.x;
             tempNormal.y = edgeB.y - edgeA.y;

          tempNormal.normalize();

          projAVec.equals(a.project(tempNormal.x,tempNormal.y));
          projBVec.equals(b.project(tempNormal.x,tempNormal.y));

          float distance = OBB2D.distance(projAVec.x, projAVec.y,projBVec.x,projBVec.y);

          if (distance > 0.0f)
          {
            return 0.0f;
          }
          else
          {
            float d = Math.abs(distance);

            if (d < depth)
            {
              depth = d;
              outNormal.equals(tempNormal);
            }
          }
        }

        float dx,dy;
        dx = b.getCenter().x - a.getCenter().x;
        dy = b.getCenter().y - a.getCenter().y;
        float dot = Vector2D.dot(dx,dy,outNormal.x,outNormal.y);
        if(dot > 0)
        {
            outNormal.x = -outNormal.x;
            outNormal.y = -outNormal.y;
        }

        return depth;
    }

    public Vector2D getMoveDeltaVec()
    {
    return deltaVec;
}
};

```

Thanks!

**Append**

Can someone please tell me what I need to provide to get an answer for this? How do 2D games calculate the force of an impact without an impact point??

I know how to find the normals of collision but that is not enough. And it is NOT simply a corner.

I really do not want to award the bounty to the current -4 downvoted answer.

# Answer
> 7 votes
I'm quite sure (100% sure, because I've implemented this myself) that your point of contact is either the corner of your car, or the corner of the building. Whether you use the corner before or after the car's position is adjusted to handle it's penetration with the static object, is up to you (I recommend after).

It seems your concern is that you don't think the corner of the car is the correct location to apply a force on the vehicle when it hits a wall. However, it actually is! Here's why:

The corner of the car is exactly the point that originally contacts the wall, so conceptually it is the point you are looking for. Also, it only matters for the *angular* force you're going to apply to the car. **The point on the car at which you apply a linear force is not important, because angular and linear momentum are entirely decoupled.**

This phenomenon simplifies things greatly; we can apply the force equal-and-opposite to the car's velocity into the wall directly to the center of mass of the car, and viola, the calculation for the change of the car's linear momentum is complete!

As for calculating the angular force exerted on the car by the wall... it's a little more complicated, because the point of contact will matter. I will again put a plug in for Chris Hecker's articles on rigid body dynamics. Almost everything you need will be explained there. Hecker explains it clearly enough that I'd struggle to give a better explanation here, but I'll provide a synopsis.

There is a formula for calculating the angular momentum of a point around another point. Assuming that you know the center of mass of your car, you can calculate the angular momentum of the corner with something like the following:

```
angularMomentum = dot(perp(A-B), momentumOfB);

```

where `B` is the center of mass, `A` is the corner of your car, or whatever point is contacting the wall, and `perp` is a function that returns the 'perpendicularized' vector from `B` to `A`. You can then do with this whatever you need to calculate the additional force that is applied to the car from the wall. Just to reiterate: though the force that the wall applies to the car is applied to the corner of the car, **the car's linear momentum is unaffected by the locality of the force**. Only the angular momentum depends on where the force is applied. Again, there is a formula for calculating the change in angular momentum given a force at a point, which involves the moment of inertia of the car. Hecker provides that formula in his articles as well.

The case you have to watch out for is when a face of the car is perfectly perpendicular to a face of the wall. Technically, you have an infinite number of contact points, making determining a contact point unsolvable. This is where things will get messy. I believe the best thing to do in this case is to, first, detect the situation by dotting together the normals of the relevant faces of the car and the building. If the result is `-1`, then you have this special case. From here, you can choose to cancel the angular momentum of the car, or leave it unmodified; to be honest, I'm not sure off the top what the "physically accurate" solution is, but it would be complicated. So the quick 'all-or-nothing' method is easier, and might give you results you're happy with. In sum, face-face contact is a non-trivial problem to solve.

Happy coding!

# Answer
> 1 votes
You should look at Erin Catto's 2006 GDC presentation where he talks about how to do this.

http://code.google.com/p/box2d/downloads/list

According to him (He wrote Box2d) you should:

* Find the axis of depest penetration (one of the OBB surface normals)
* Find the incident face on the other OBB (It's dot product should have the largest negative magnitude)
* Then clip the incident face against the face you got the surface normal from.

the resulting points are all of the collision points that you need to resolve from. Some solvers just use the most deeply embedded collision point and maintain a contact manifold (don't stop resolving against a point until you detect that it has moved out of collision) but clipping should be more stable.

# Answer
> 0 votes
EDIT ohh I got what you miss! When people say the point of contact is a corner, they don't mean it is necessarily a corner of the car, but a corner of either of the two colliding objects. In your picture, it is a corner of the wall. See my original response below.

Original response

Well, for 2D convex polygons, there can be up to 2 points of contact, but each point of contact IS definitely a corner. It can be a corner of the car, or a corner of the wall, but it is a corner nonetheless. This is because objects should not overlap in the first place; they can only touch, and when they do, the touching point is a corner (*deleted irrelevant comment*). These points are where you apply forces. The determination is commonly using Separating Axis Theorem. This method is useful to detect collision, determine the contact normal, contact point, as well as the amount of overlap. A good tutorial on the subject can be found here. For more detailed discussion, you can refer to the book "Real Time Collision Detection" by Christer Ericson.

---
Tags: java, collision-detection, physics
---


title: Typical collision detection

text:
# Question
Title: Typical collision detection
I would like to know how is the typical collision detection of most games. For example, you control a character which can move in 2 dimensional directions (except up and down). Now lets asume he walks into a wall, most of the games depending on character angle and the BB normal face will only stop the player in one axis, but will continue moving in the other along the wall axis. How is that done?

I've only managed to stop the character from going through the wall by seting the position to the last one in the past frame if the new position colllisions the bounding box. But this just makes the player stop sharply and unrealisticly.

# Answer
It sounds like you have collision detection working fine. What you're asking about is collision resolution. To make the character continue moving in a valid direction, don't move him back to his last valid position. That will just freeze him in place in an unnatural fashion. Instead, move him along the wall's normal until he is no longer colliding with it. This will however require you to know more data about the collision than just whether it happened or not, but if you're using bounding boxes it won't be too bad.

So the red dots are the points at which the player is rendered, and the grey line follows the bottom-right corner of the player's bounding box. The player is moving in the x direction and the y direction, but when he hits the wall he is only moved back in the y direction, the x direction is not affected. As a result he will "slide" along the wall. Note that he is always moved up the exact amount required to get him out of the wall.
> 3 votes

# Answer
Your question is a bit vague ("Typical collision detection"), but your concern about stopping the player in one axis can be answered.

The easiest solution (in terms of required work) is to check collisions in each axis separately. You wrote "seting the position to the last one in the past frame if the new position colllisions the bounding box" will work, but you need to check and reset the X and Y coord separately.
> 0 votes

---
Tags: collision-detection, collision-resolution, bounding-boxes
---


title: Separate update and render

text:
# Question
Title: Separate update and render
I'm programming a simple Snake in Java. I'm a complete newbie when it comes to Java and Game Developing, so please bear with me ;)

Until now, I have been using a UI thread, as well as a update-thread. The update thread just set the position, set the `GameObject`s, and so on.

I didn't think much of concurrency, but now I've come to a problem.

I wanted to modify the `ArrayList<GameObject>`, but it throws a `java.util.ConcurrentModificationException`.

With a little research I found out that this happens because the two threads are trying to access the variables at the same time.

But I didn't really find a way to prevent this. I thought about copying the array and swapping them out when the rendering is finished, but I would have to deep-copy them, which isn't really the best solution in my opinion. It probably eats up more CPU resources than a single-threaded game.

Are there any other ways to prevent this?

Thanks a lot for your help!

# Answer
> 4 votes
Use wait and notify to ensure that only one of your threads is modifying the object at a time. You'll need a class to hold your ArrayList:

```
class GameObjectManager {
    private ArrayList<GameObject> objects;
    private Boolean rendering = false;

    public GameObjectManager(){
        //Initialize objects
    }

    public synchronized void update() {
        if (rendering)
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println("InterruptedException caught");
            }

        // update objects...

        rendering = true;
        notify();
    }

    public synchronized void render() {
        if (!rendering)
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println("InterruptedException caught");
            }

        // render objects...

        rendering = false;
        notify();
    }
}

```

The Update thread might look something like this:

```
class UpdateThread implements Runnable {
    private GameObjectManager manager;

    public UpdateThread(GameObjectManager m) {
        this.manager = m;
        new Thread(this, "Update").start();
    }

    public void run() {
        while (true) {
            m.update();
        }
    }
}

```

The Render thread would follow suit:

```
class RenderThread implements Runnable {
    private GameObjectManager manager;

    public RenderThread(GameObjectManager m) {
        this.manager = m;
        new Thread(this, "Render").start();
    }

    public void run() {
        while (true) {
            m.render();
        }
    }
}

```

Now the main function that controls it all would do something resembling this:

```
public static void main(String args[]) {
    GameObjectManager manager = new GameObjectManager();
    new UpdateThread(manager);
    new RenderThread(manager);
    System.out.println("The game is running now...");
}

```

So here's what happens:
1. The main function creates two threads, the update and render threads.
2. Both threads try to do their task, but the `GameObjectManager` forces the render thread to `wait()` until the update thread has called `notify()`.
3. The update thread finishes updating, notifies the render thread, and then waits.
4. The render thread finishes rendering, notifies the update thread, and then waits.

And so on.

---
Tags: java, multithreading
---


# Question
Title: Can't click on a button with startDrag() active on stage
I need to know how can I enable mouse click on a button when I have a `MouseEvent` listener for the stage.

I have an `MClip` associated with the mouse cursor:

```
Mouse.hide();
scope.startDrag(true);

```

And a `MouseEvent` on the stage:

```
stage.addEventListener(MouseEvent.CLICK, FunctionXYZ);

```

When I try to click on any button they don't call the function that I create for those buttons... for example, button for fullscreen, exit, help, etc... What can I do?

# Answer
One thing you can try:

```
MClip.mouseEnabled = false

```
> 2 votes

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


# Question
Title: XNA C# Platformer - physics engine or tile based?
I would like to get some opinions on whether I should develop my game using a physics engine (Farseer Physics seems to be the best option) or follow the traditional tile-based method.

Quick background:

* It's a college project, my first game, but have 4 years academic programming experience
* I just want a basic platformer with a few levels, nothing fancy
* I want a shooting mechanic, run and gun, just like contra or metal slug for example
* Possibly some simple puzzles

I have made a basic prototype with Farseer, the level is hardcoded with collisions and not really tiled, more like big full-screen sized tiles, with collision bodies drawn manually along the ground and walls etc. My main problem is I want a simple retro feel to the jumping and physics, but because it's a physics simulation engine, it's going to be realistic, whereas typical in air controllable physics for platformers aren't realistic. I have to make a box with wheel body fixture under it to have this effect, and it's glitchy and doesn't feel right.

I chose to use a physics engine because I tried the tile method initially and found it very hard to understand. The engine took care of a lot things to save me time. Being able to do slopes easily was nice, as was the freedom to draw collision bounds wherever I liked, rather then be restricted to a grid. This also gave me more freedom for art design.

In conclusion, I don't know which method to pick. I want to implement this in the most straightforward way, so it won't give me a headache later on. Preferably, a method which has an abundance of tutorials and resources so I don't get "stuck" doing something which has been done a million times before!

# Answer
> 7 votes
The answer is simple: **a physics engine is *not* a platformer engine**.

While you can get kind-of platformer-like behaviour out of a physics engine, you simply do not have enough control to get that really "fluid" gameplay feel of a proper platformer.

For example: The classic Mario-style jump requires changing the *gravity* for the player at different stages of the jump - as well as directly setting the velocity in a few places.

The reason for this is that you want the jump to start as soon as the player presses the button (responsive), and the height will be specified *after* the jump starts (by the player releasing the key - which also must be responsive). The reason is that it feels good.

To give another example: the friction experienced by an object sliding (or rolling) along the ground is very different to the behaviour of a walking biped - or a player's expectations of how a traditional platformer character will accelerate and decelerate.

If you want to use a physics engine, these are two of the *many* places where you must customise the engine to get the behaviour you want. For my own game I have found that you even have to heavily customise things like collision detection to get things to feel right (sticking to the ground, *not* sticking to the ground, falling off ledges, etc).

---

It's very important to note that using a physics engine is orthogonal to the question of whether or not to make your platformer tile-based or vector based. , for example, is tile-based but uses many techniques you'd find in a physics engine.

---

**To answer your question directly, here is a decision tree:**

* If you want to get something up-and-running *quickly*, and you don't need a good, polished platformer feel, by all means use a physics engine. There are even lots of tutorials on how to get kinda-sucky platformer behaviour out of one.
* If your game design revolves deeply around platforming (ie: movement), then a tile-based engine is probably best (eg: Mario, N, Super Meat Boy, etc). It will make it easier for everyone involved - movement designer, level designer, and ultimately the player - to focus on the movement mechanics. And tile-based *is* easier to program in the long term.
* If your game is not movement-based (eg: Braid), then a vector based design allows for more varied, natural levels.
* Obviously a game that has physics as a game-play component (eg: Limbo) requires a physics engine.
* If you're absolutely crazy (like me), you could make a vector-based game with deep movement on a physics engine. It's not impossible - just difficult.

If you're not using the rigid-body simulation, then the use of a physics engine for a vector-based platformer is really a toss-up. On the one hand you get a lot of functionality for free. On the other hand: there's a lot of functionality you'll have to override and modify and circumvent.

# Answer
> 2 votes
Physics engines and tile based platformers are not mutually exclusive. For example you can combine the Farseer Physics engine and the XNA Platformer Starter Kit (This will also explain a pure tile based approach to you). Simply remove all exisiting collision detection code (from the Player class) and give the Tiles and Player class Bodies and associated Shapes for Farseer to perform collision on.

In reality combining the two together is not ideal. Moving the player body across a series of adjacent tiles (floor, walls etc) will cause problems and not provide smooth motion. See this great article for further explanation.

Most modern platform games simply draw the game elements as tiles but have an underlying physics environment which matches the geometry as much as possible. This is why you can sometimes see the players feet dip below the surface of the "floor". Here is an example from an early prototype of Braid:

In the Farseer physics engine you are able to control the gravity of the world, drag coefficients and player movement enough so that you should get the old-school platformer feel to it. Simply find a set of drag, mass and movement velocities and play with these settings until you get the right feel.

Use what you are most comfortable with.

---
Tags: xna, c#, tilemap, farseer-physics-engine
---


# Question
Title: How can I generate a view or projection matrix for OpenGL 3.+
I'm transitioning from OpenGL 2 to OpenGL 3.+ and to GLSL 1.5. I'm trying to avoid using the deprecated features.

My question how do we now generate the view or projection matrix. I was using the matrix stack to calculate the projection matrix for me;

```
GLfloat ptr[16];
gluPerspective(...);
glGetFloatv(GL_MODELVIEW_MATRIX, ptr);
//then pass ptr via a uniform to the shader

```

But obviously the matrix stack is deprecated. So this approach is not the best an option going forward.

I have the 'Red Book', 7th ed, which covers 3.0 & 3.1 and it still uses the deprecated matrix functions in it's examples.

I could write some utility-code myself to generate the matrices. But I don't want to re-invent this particular wheel, especially when this functionality is required for every 3D graphics program.

What is the accepted way to generate world,view & projection matrices for OpenGL? Is there an emerging 'standard' library for this? Or is there some other hidden (to me) functionality in OpenGL/GLSL which I have overlooked?

# Answer
> 1 votes
Take a look at the Unofficial OpenGL Software Development Kit.

Not only does it include the GLM library, there's also a GL Util module which contains a replacement for the matrix stack.

You can also see this tutorial for an introduction to the library.

# Answer
> 5 votes
I'm sure somebody will write a whole novel on how to calculate the perspective projection and the view matrix, but that's just unnecessary. You'll find this information in any modern book on 3D graphics. If you don't have access to books like Real-Time Rendering then there are OpenGL Tutorials. Alternatively you can just use google. You're looking for common knowledge that's been answered dozens of times. If you don't care about the mathematics then libraries like GLM have functions to generate these matrices.

As for a commonly accepted way of doing this, the principle is always the same for both the view and perspective matrices. There are multiple ways of achieving both (f.e. you can calculate the view matrix as a camera transform and then invert it, or you can calculate it inverted already, the second being much faster), but if you know where to plug your variables then there isn't much difference. The thing you have to look out for is whether you're using the right or left hand coordinate system. Another thing to look out for is DirectX and OpenGL requiring different perspective projection matrices due to the way they define their clip spaces, so make sure that the perspective projection matrix you use is for OpenGL specifically.

# Answer
> 3 votes
For those looking for a copy/paste answer, or something a little more code like, here is an implementation for OpenGL. It supports a zoom feature to zoom in/out on the center of the view. I think the variable names are fairly self explanatory.

* Camera is defined by it's position, direction it's looking and its up vector. The view matrix is made up of these values.
* The "lens" you're using (I suppose it could be called?) describes the "cone" that represents what you're looking at in the world. It takes the view angle (how wide narrow the cone of view is) the size of your game window and the near and far cut offs for your view cone. These values make up the projection matrix.

The code below is working and taken from my game. I don't know if this is the most fashionable way to make the matrices, but it works for me and supports the older hardware the I'm targeting.

```
view = createView(getCameraPosition(), getCameraDirection(), getCameraUpVector());
projection = createProjection(cameraViewAngle * zoomFactor, (float) getWindowX() / (float) getWindowY(), nearPlane, farPlane);

Matrix4f createView(Vector3f position, Vector3f direction, Vector3f up) {
    Vector3f.cross(up, direction, getRightVector());
    setRightVector((Vector3f) getRightVector().normalise());

    result.m00 = getRightVector().x;
    result.m10 = getRightVector().y;
    result.m20 = getRightVector().z;
    result.m30 = -(Vector3f.dot(getRightVector(), position));

    result.m01 = up.x;
    result.m11 = up.y;
    result.m21 = up.z;
    result.m31 = -(Vector3f.dot(up, position));

    result.m02 = direction.x;
    result.m12 = direction.y;
    result.m22 = direction.z;
    result.m32 = -(Vector3f.dot(direction, position));

    return result;
}

Matrix4f createProjection(float fov, float aspect, float znear, float zfar) {

    float ymax, xmax;
    ymax = (float) (znear * Math.tan(fov * Math.PI / 360.0));
    xmax = ymax * aspectRatio;
    Matrix4f result = new Matrix4f();
    glhFrustumf2(result, -xmax, xmax, -ymax, ymax, znear, zfar);
    return result;
}

private Matrix4f glhFrustumf2(Matrix4f matrix, float left, float right, float bottom, float top, float znear, float zfar) {
    float twoZNear, deltaW, deltaH, deltaZ;
    twoZNear = 2.0f * znear;
    deltaW = right - left;
    deltaH = top - bottom;
    deltaZ= zfar - znear;
    matrix.m00 = twoZNear / deltaW;
    matrix.m01 = 0.0f;
    matrix.m02 = 0.0f;
    matrix.m03 = 0.0f;
    matrix.m10 = 0.0f;
    matrix.m11 = twoZNear / deltaH;
    matrix.m12 = 0.0f;
    matrix.m13 = 0.0f;
    matrix.m20 = (right + left) / deltaW;
    matrix.m21 = (top + bottom) / deltaH;
    matrix.m22 = (-zfar - znear) / deltaZ;
    matrix.m23 = -1.0f;
    matrix.m30 = 0.0f;
    matrix.m31 = 0.0f;
    matrix.m32 = (-twoZNear * zfar) / deltaZ;
    matrix.m33 = 0.0f;
    return matrix;
}

```

# Answer
> 2 votes
If you're using C++, the common answer is to use GLM. For C, you'll have to roll your own matrix math (which really isn't all that much code, a few hundred lines will get you everything you could possibly want). Look at the source code to Mesa or Blender if you want inspiration. Blender in particular has a nice set of matrix math functions. Beware of licensing issues if you intend to copy open source code to reuse though!

---
Tags: opengl, matrix
---


# Question
Title: Confusion on HLSL Samplers. Can I Set Samplers Inside Functions?
I'm trying to create a system where I can instance a quad to the screen, however I've run into a problem. Like I said, I'm trying to instance the quad, so I'm trying to use the same geometry several times, and I'm trying to do it in one draw call. The issue is, I want some quads to use different textures, but I can't figure out how to get the data into a sampler so I can use it in the pixel shader. I figured that since we can simply pass in the 4 bytes of our IDirect3DTexture9\* to set the global texture, I can do so when passing in my dynamic buffer. (Which also stores each objects world matrix and UV data) Now that I'm sending the data, I can't figure how to get it into the sampler, and I really want to assume that it's simply not possible. Is there any way I could achieve this?

# Answer
> 1 votes
With D3D9 you can't use a texture array (which otherwise would have been my recommendation) so I'd suggest that you put your textures into a texture atlas instead. That can be ideal if you're drawing sprites or GUI items.

If that's not an option for you (e.g. you may need mipmapped or repeated textures), you could potentially call SetTexture with a different Stage for each texture you wish to use (SM3 will allow you up to 16 simultaneous textures), then add a per-instance attribute to your vertex declaration identifying the Stage to read from in your shader. That's potentially a bit messier, but it can work.

---
Tags: textures, hlsl
---


# Question
Title: Physics-based dynamic audio generation in games
I wonder if it is possible to generate audio dynamically without any (!) audio assets, using pure mathematics/physics and some input values like material properties and spatial distribution of content in scene space. What I have in mind is something like a scene, with concrete floor, wooden table and glass on it. Now let's assume force pushes the glass towards the edge of table and then the glass falls onto the floor and shatters. The near-realistic glass destruction itself would be possible using voxels and good physics engine, but what about the sound the glass makes while shattering? I believe there is a way to generate that sound, because physics of sound is fairly known these days, but how computationaly costy that would be? Consumer hardware or supercomputers? Do any of you know some good resources/videos of such an experiment?

# Answer
This is discussed regularly in the Game Programming Gems.

That's probably one of the best resource you can find, here's a quick selection of articles:

* GPG4: 7.6 Controlling Real-Time Sound Synthesis from Game Physics
* GPG6: 6.1 Real-Time Sound Generation from Deformable Meshes
* GPG8 : 6.3 Real-Time Sound Synthesis for Rigid Bodies
> 1 votes

---
Tags: physics, audio
---