# Question
Title: Xcode workspace with Unity3D as a sub-project?
Let's say we're developing a 2D game with Cocos2d-iPhone and UIKit and CoreAnimation. But we're also considering leveraging the 3D capabilities of Unity 3D.

Is it possible that we add the Unity3D-generated Xcode project as a sub-project into the workspace and expose the 3D UI element as some kind of UIView subclass so that the native UIKit and CoreAnimation code could use them without the need to mess up with their underlying Unity3D implementation?

# Answer
> -1 votes
**Well it's possible to combine the languages:**

1. **integration of Unity-3D with cocos2D** @Unity-3D official forum
    * **Unity does not offer any kind of source code** for the engine, as such no you can't integrate cocos (or any other engine) into unity nor vice versa
    * **You can use plugins yes and basically run Unity, or pause unity and run cocos,** but you can not use the same assets in unity as in cocos and the build size will grow even further.
    * You will have to ask on the cocos board about cocos stuff I fear
2. If your going to bother to use an advanced engine like `Unity-3D`
    * To take advantage of nice features requires lots of money
    * `Unity-3D` engine has multiple plugins for video and audio doesn't need integration
    * Learning Unity-3D will be difficult
    * Integrating cocos-2d would limit your abilities

---

**I suggest you choose an option:**

1. Stick to `cocos2D` because the combination could cause unwanted problems
2. Move everything over to `Unity-3D` for more control
3. If you have to integrate them, and for more questions try the `Unity-3D` forums.

---
Tags: unity, cocos2d-iphone, ios, objective-c, xcode
---


# Question
Title: What should I worry about when changing OpenGL origin to upper left of screen?
For self education, I'm writing a 2D platformer engine in C++ using SDL / OpenGL. I initially began with pure SDL using the tutorials on sdltutorials.com and lazyfoo.net, but I'm now using SDL to create an OpenGL rendering context and then render with OpenGL functions (specifically immediate mode but I'm learning about VAOs/VBOs). I am using SDL only for interface, audio, etc.

SDL uses a coordinate system with the origin in the upper left of the screen and the positive y-axis pointing down. It's easy to set up my orthographic projection in OpenGL to mirror this.

I know that texture coordinates are a right-hand system with values from 0 to 1 -- flipping the texture vertically before rendering (well, flip the file before loading) yields textures that render correctly... which is fine if I'm drawing the entire texture, but ultimately I'll be using tilesets and can imagine problems.

What should I be concerned about in terms of rendering when I do this?

If anybody has any advice or they've done this themselves and can point out future pitfalls, that would be great, but really any thoughts would be appreciated.

# Answer
"What should I be concerned about in terms of rendering when I do this?" - not much. A co-ordinate system is just a convention, not a hard-and-fast rule, and this is a perfectly legal and valid thing to do. Just make sure that you are consistent in your own usage and everything will work fine.
> 8 votes

# Answer
When working in 2D with OpenGL, I often use the top-left corner as the origin. This can be done with:

```
glOrtho(0,      // left
        width,  // right
        height, // bottom
        0,      // top
        0,      // zNear
        1       // zFar
        );

```

However, there are some pitfalls when changing the origin to the upper-left.

One pitfall I've run into more than once: `glScissor()`, which is used for clipping, always uses lower-left coordinates.

Its signature is:

```
void glScissor( GLint x, GLint y, GLsizei width, GLsizei height )

```

where `x, y` specify the **lower left** corner of the scissor box.

More generally, any functions that operate in *window coordinates* all use the lower left as the origin. This includes functions like `gluProject`, `gluUnProject`, `glCopyPixels`, etc.

But some functions like `glDrawPixels` use `glRasterPos` for positioning, and `glRasterPos` uses *object (i.e. transformed) coordinates*.

If you're running on Linux, and know how to use `man`, you might want to grab a copy of the OpenGL manpages here: ftp://ftp.sgi.com/sgi/opengl/doc/ I find them a real time-saver.

Also, I notice you say "flip the file before loading" textures. This is not necessary. Instead of flipping the image when loading it, just flip the texture coordinates to go from 1.0 to 0.0 when rendering.
> 5 votes

---
Tags: c++, opengl, 2d, sdl
---


title: How to control an actor movement in UDK

text:
# Question
Title: How to control an actor movement in UDK
This might be very basic, but I couldn't find something relevant to what I need (see below). I am working on a very basic thing: a 3D environment with some buildings, and actors walking inside it. It looks like following:

I mainly want to manage to have one actor standing around, idling, and another walking around the area. Right now, this is done through matinee + skeletal mesh groups, and forcing a looped animation on the actors:

But I realize this is super caveman-level. So I've build an AnimTree, linking the idling and directional animations to the corresponding nodes. But then, I'm stuck. I added the AnimTree in the actors properties, but nothing happens. I've tried MoveToActor, but no success - is there a thing to set to allow an actor to move? Also, I place the actors on the map manually (they are supposed to be unique), should I spawn them instead?

Every tutorial I find explains how to use an AnimTree for the **player** character, which is not what I want. I need a way to move the actors. I tried to look for AI tutorials, but only found UT3 bots-modifications, which is not what I need either.

Since I have so much trouble finding how to do this through Kismet, I'm starting to suspect this has to be done through scripting/coding, but I would like to be **sure** there is no way to do it through Kismet before going that route.

Every bit of answer about how to tell an actor something along the lines of "go in that direction as much as you can, then when you hit a wall turn 45° and continue" would be awesome.

I'll be happy to move/edit the question if there is any problem with it

# Answer
> 2 votes
I recommend you to check following tutorials. And of course controlling the actors using scripts is the best method. It will give you more control over them.

Specifically for Animations,

http://www.moug-portfolio.info/udk-animation-basics/

And here you will find more useful guides. http://www.moug-portfolio.info/

Check the AI pawn movement tutorail as well. If you want to move NPCs it will be really helpful. And that tutorial only shows how to move a default pawn. But you can manually set an animation to your charactor.

---
Tags: software-engineering, udk
---


# Question
Title: How can I implement an Iris Wipe effect?
For those who doesn't know:

> An iris wipe is a wipe that takes the shape of a growing or shrinking circle. It has been frequently used in animated short subjects, such as those in the Looney Tunes and Merrie Melodies cartoon series, to signify the end of a story. When used in this manner, the iris wipe may be centered around a certain focal point and may be used as a device for a "parting shot" joke, a fourth wall-breaching wink by a character, or other purposes.

Example from flasheff.com

##

Your answer may or may not include a coding sample, a language agnostic explanation is considered enough.

# Answer
In a 2D iPhone game I played recently, `iris wipe effect` was simply done using full screen sprites with some transparency :

These pictures are simply draw over the screen once everything else have been draw (like hud, background, ...).

You can easily build theses pictures in `photoshop`, `gimp`, `flash` or whatever 2D program you have.

---

You can also do it "realtime", by using 2D primitives that are available in your framework (you dont specify any). Here is an example in opengl (un-tested) :

```
void drawIris(float inner_radius)
{
   const float outer_radius = 300.0f; //something big enough to cover whole screen

   glBegin(GL_TRIANGLE_STRIP);
   for (int i = 0; i < 360; i++)
   {
      float degInRad = i * DEG2RAD;
      glVertex2f(cos(degInRad) * inner_radius, sin(degInRad) * inner_radius);
      glVertex2f(cos(degInRad) * outer_radius, sin(degInRad) * outer_radius);
   }
   glEnd();
}

//to change the way iris animation is done,
//you can replace this function by something else like smoothstep() function
float lerp(float a, float b, float t)
{
   return a * (1.0f - t) + b * t;
}

//usage :
drawIris(lerp(0.0f, 50.0f, time));

```

Here is how it works :

We draw a open circle with an *outer radius* bigger than the screen. Everything outside the screen will automatically be clipped by opengl. *Inner radius* is aperture size of iris.
> 10 votes

# Answer
If using OpenGL or Direct3D, you can write a post-processing shader to do the job rather easily.

You'll be rendering a full-screen quad on top of the already rendered scene. The shader takes in (as a uniform) current radius of the iris (so you'll "animate" that on the CPU).

In the fragment/pixel shader, you'll get the current't pixel's screen coordinates from the interpolated vertex coordinates. You then calculate the distance to the center of the screen and output a black pixel if the distance is greater than the current iris radius, and a transparent one if not.

If you desire softer edges, you could look up vignette shader and animate its radius in the same way.
> 8 votes

# Answer
Another approach would be to generate a 2d mesh that has a hole in the middle, and render that on top of everything else.

Generating this mesh may seem complicated at first, especially when the hole is partially bigger than the screen, but remember that the mesh may be way bigger than the screen.

I'd go with something like a huge "o" circle shape.

Alternatively, you can use stencil buffers to first render the parts that you want to keep visible to the stencil buffer and then render a huge quad over everything using said stencil buffer.
> 2 votes

---
Tags: graphic-effects
---


# Question
Title: Orthogonal projection and world transform
I'm reading about projection matrix. Needs of perspective projection is obvious, but I'm not sure about orthogonal projection. Because orthogonal projection effect looks possible with only world transform.

What is main purpose of orthogonal project which make it different with world transform?

# Answer
> 1 votes
It is possible to skip the orthogonal projection entirely, you are correct. It is usefull however, since most of the time when doing 2D you want to be working with screen space coordinates and not the (-1,1) range. It's more intuitive and hides the implementation details from the user.

All OpenGL does is, it expects your vertex shader to output clip space coordinates so it can do the perspective divide. So if you leave the w coordinate as 1 then it's like OpenGL did nothing. OpenGL will certainly not perform any transformations unless you tell it to.

---
Tags: matrix, projection, transformation
---


# Question
Title: C++ Game Engine Book/Tutorial/Anything recent?
Before I get flamed, please understand that I have been looking for a while now. Yes, I have found a good amount of game engine tutorials...except filled with errors, out of date syntax, missing crucial information, and so on. Is there anywhere with a *recent* tutorial, or a book, anything at all?

I'm not asking for an opinion in graphics API's, just a point in the right direction to get started on game engine development.

I just want to make it clear, I have googled/stac5ked like crazy.

Any help appreciated. Thank you.

# Answer
This might not look like an answer but from my own experience - no, I haven't seen any tutorial or book on the subject that is worth mentioning.

I started learning it by making a game. When I built my second engine, I started by just picking any book on the subject and trying to reimplement things. I found lots of problems with the ways things were done according to the book on the way and if you want to follow any book, I suspect you will find just as many. So if possible, I'd suggest you avoid all of them as pure examples of design and let your work shape your engine as you improve it while making a game.

This doesn't mean you shouldn't read them and think about the things written. It's just that no book will be even 50% right about things and it's what you should keep in mind while you read them.
> 2 votes

# Answer
I've found Game Coding Complete to be a very good game / game engine programming book. It has up-to-date C++11 syntax along with some bits about C# and Lua for scripting.
> 1 votes

# Answer
I own C4 Engine license and new book was for C4 Engine was recently released on Amazon

http://www.amazon.com/Beginners-Guide-Engine-Second-Edition/dp/0985811714

C4 Engine is developed Eric Lengyel He is author of following book about 3D Games and Math http://www.amazon.com/Eric-Lengyel/e/B001K8753Q/ref=ntt\_athr\_dp\_pel\_1

C4 Engine comes with full source code for only $250

IMO It is very good deal.
> 0 votes

---
Tags: education
---


# Question
Title: How do I use D3DXVec3Unproject with D3D11?
I'm having a small issue with D3DXVec3Unproject. I'm currently using Direct3D 11 and not 10, and the signature for this function is:

```
D3DXVECTOR3 *pOut, CONST D3DXVECTOR3 *pV, CONST D3D10_VIEWPORT *pViewport,
      CONST D3DXMATRIX *pProjection, CONST D3DXMATRIX *pView, CONST D3DXMATRIX *pWorld

```

As you may have noticed, it requires a `D3D10_VIEWPORT`, and I'm using a Direct3D 11 viewport, `D3D11_VIEWPORT`.

Do you have any ideas how I can use D3DXVec3Unproject with Direct3D 11?

# Answer
> 6 votes
Instead of `D3DXVec3Unproject()` use XMVector3Unproject(). It accpet float parameters for viewport:

```
XMVECTOR XMVector3Unproject(
  [in]  XMVECTOR V,
  [in]  float ViewportX,
  [in]  float ViewportY,
  [in]  float ViewportWidth,
  [in]  float ViewportHeight,
  [in]  float ViewportMinZ,
  [in]  float ViewportMaxZ,
  [in]  XMMATRIX Projection,
  [in]  XMMATRIX View,
  [in]  XMMATRIX World
);

```

NOTE: Here you get some info about converting D3DXMath into DirectxMath.

# Answer
> 2 votes
The structures are passive data, the only difference is that the D3D11 flavor deals with floats instead of integers for most of the fields.

If your quantities are integral, simply construct a corresponding `D3D10_VIEWPORT` and call the function.

---
Tags: c++, 3d, directx11, directx10, picking
---


# Question
Title: Good practices while working with multiple game engines, porting a game to a new engine
I have to work with multiple game engines, like

* Cocos2d
* Unity3d
* Galaxy

While working with multiple game engines, what practices should I follow?

For instance, we made a game with Cocos2d and released it on the AppStore. Now we want to port it to other platforms using Unity.

What would be the course of actions to follow?

# Answer
> 1 votes
I'd suggest finding a common denominator of these engines. That is, if you will use a physics engine, find one that has ports already made for other environments you use. If you use a MVC approach, use a MVC framework that is either ported to other environments (pureMVC is quite popular) or that works in a similar way as other MVC frameworks you can use in other environments.

In the end it is best to decouple view components specific to game engine from rest of the code, so when porting the game you can focus on a specific part of the source.

---
Tags: software-engineering
---


title: AS3 Stage3D Mouse click problem?

text:
# Question
Title: AS3 Stage3D Mouse click problem?
I have a problem with Mouse interaction and Stage3D.

The only way I found to register to listen to mouse clicks and interact with Stage3D, is to add a mouse eventListener directly to the .stage.

However this will result in any time i click anywhere in the flash application the mouse click will fire, even if there is an overlaid 2D menu where the user intended to click.

IE I have a 3D application running in the background, which listens to clicks, and I have some floating User Interface elements in the foreground, and ideally if I clicked a button in the foreground, then that would NOT fire a click event that the Stage3D would register.

Any idea how to solve this problem?

# Answer
You can read the Mouse Coordinate at the click and check it against the bounds from your interface. If the Mouse is on the interface do nothing in stage...
> 1 votes

# Answer
You could also call the stopImediatePropagation on your UI elements, but that will probably give you some other problems later on.

But I assume it is better than having a list of items to be ignored.
> 1 votes

---
Tags: 3d, actionscript-3, mouse
---


# Question
Title: Circle-Rectangle collision in a tile map game
I am making a 2D tile map based putt-putt game.

I have collision detection working between the ball and the walls of the map, although when the ball collides at the meeting point between 2 tiles I offset it by 0.5 so that it doesn't get stuck in the wall. This aint a huge issue though.

```
  if(y % 20 == 0) {
    y+=0.5;
  }

  if(x % 20 == 0) {
    x+=0.5;
  }

```

Collisions work as follows

1. Find the closest point between each tile and the center of the ball
2. If `distance(ball_x, ball_y, close_x, close_y) <= ball_radius` and the closest point belongs to a solid object, collision has occured
3. Invert X/Y speed according to side of object collided with

The next thing I tried to do was implement floating blocks in the middle of the map for the ball to bounce off of. When a ball collides with a corner of the block, it gets stuck in it. So I changed my `determineRebound()` function to treat corners as if they were circles. Here's that functon:

```
   `i and j are indexes of the solid object in the 2d map array. x & y are centre point of ball.`
   void determineRebound(int _i, int _j) {
     if(y > _i*tile_w && y < _i*tile_w + tile_w) {
        //Not a corner
        xs*=-1;
      } else if(x > _j*tile_w && x < _j*tile_w + tile_w) {
        //Not a corner
        ys*=-1;
      } else {
        //Corner
        float nx = x - close_x;
        float ny = y - close_y;
        float len = sqrt(nx * nx + ny * ny);
        nx /= len;
        ny /= len;

        float projection = xs * nx + ys * ny;
        xs -= 2 * projection * nx;
        ys -= 2 * projection * ny;
      }
    }

```

This is where things have gotten messy. Collisions with 'floating' corners work fine, but now when the ball collides near the meeting point of 2 tiles, it detects a corner collision and does not rebound as expected.

I'm a bit in over my head at this point. I guess I'm wondering if I'm going about making this sort of game in the right way. Is a 2d tile map the way to go? If so, is there a problem with my collision logic and where am I going wrong?

Any advice/feedback would be great.

# Answer
> 6 votes
First of your problem is that you're not looking in a further perspective. The ball blocks itself on a wall - just move it 0.5 pixels away. Why not try to unblock it instead? Later you treat a corner like a circle (do you mean a point? If not, I don't understand the idea and it makes me dizzy when I try).

It's OK to do quick, dirty fixes and try if they work. But after every such fix you should consider changing your base - well, you actually did that by asking the question, so I'll better get to the answer:

You have some easy conditions for your ball colliding with terrain, because:

* terrain is made of squares, that are very easy to define mathematically, and therefore it's easy to detect collision (just check if X is higher then square's X but lesser then square's X plus square's width, then do same with it's Y and height)
* additionally squares are tiles, that is, you have a grid.

So we have a situation:

1. We assume the ball is never larger then a tile (or a cell of the grid)
2. Therefore our ball takes usually one, but sometimes up to 4 cells as the lower ball on the picture.
3. We first treat the ball as a cross. If we want the collision to be pixel-perfect, then we can't treat the ball as a square, because sometimes where square would take fourth cell with it's corner, a circle doesn't reach. On example picture, top ball treated as a square would take a cell on left and down from it, while it shouldn't.
4. To count if the ball takes fourth cell, we treat it like a circle. That's a little bit less or more tricky, depends on how accurate you want your collision detection to be. Solution for perfect accuracy is to check two points that extend most:

```
function xToGrid ( x:Number ):int {
    return Math.floor ( x / 20 );
}

function yToGrid ( y:Number ):int {
    return Math.floor ( y / 20 );
}

/**
 * assuming the ball is not bigger then tile/cell.
 */
function markTilesAsOccupiedByBall ( x:int, y:int, r:int ):void {
    var left:int = x - r;
    var right:int = x + r;
    var top:int = y - r;
    var bottom:int = y + r;

    var centerTileX:int = xToGrid ( x );
    var centerTileY:int = yToGrid ( y );

    var localPosX = x % 20;
    var localPosY = y % 20;

    var x1:Number;
    var y2:Number;

    if ( localPosX < 10 ) x1 = localPosX;
    else x1 = 20 - localPosX;
    x1 += .1; //to actually go outside the cell

    if ( localPosY < 10 ) y2 = localPosY;
    else y2 = 20 - localPosY;
    y2 += .1; //to actually go outside the cell

    //Pitagoras: r^2 = x^2 + y^2
    // r*r = x1*x1 + y1*y1
    // we don't know y1
    // y1*y1 = r*r - x1*x1
    var y1:Number = Math.sqrt ( r * r - x1 * x1 );

    // r*r = x2*x2 + y2*y2
    // we don't know x2
    var x2:Number = Math.sqrt ( r * r - y2 * y2 );

    if ( localPosX < 10 ) {
        x1 = x - x1;
        x2 = x - x2;
    } else {
        x1 = x + x1;
        x2 = x + x2;
    }

    if ( localPosY < 10 ) {
        y1 = y - y1;
        y2 = y - y2;
    } else {
        y1 = y + y1;
        y2 = y + y2;
    }

    //it is possible that all below operations assign true to same tile!
    //You should delete duplicates especially for optimization,
    //but duplicates could also make some mechanisms trigger more than once
    tilesOccupied.clear();
    tilesOccupied.push ( [xToGrid(left), centerTileY] );
    tilesOccupied.push ( [xToGrid(right), centerTileY] );
    tilesOccupied.push ( [centerTileX, yToGrid(top)] );
    tilesOccupied.push ( [centerTileX, yToGrid(bottom)] );
    //the "corner":
    tilesOccupied.push ( [xToGrid(x1), yToGrid(y1)] );
    tilesOccupied.push ( [xToGrid(x2), yToGrid(y2)] );
}

function detectCollision ():void {
    markTilesAsOccupiedByBall ( ball.x, ball.y, ball.radius );
    for ( var i:int = 0; i < tilesOccupied.length; i++ ) {
        if ( grid [ tilesOccupied[i][0], tilesOccupied[i][4] ] == GridType.WALL ) {
            //make some action
        }
    }
}

```

You should substitute '20' literals with some CELL\_WIDTH constant. Keep in mind this could be optimized a lot, but I didn't want e.g. mess with minus signs, because the equations would be a lot less readable if I did.

**As for collision-resolution** I would move the circle back as in another answer I made. As the question was deleted, I'll just paste it here:

1. Get a list of nearby rectangles.
2. Iterate through each of them:
    1. If you collide with the red rectangle, move the green rectangle outside of it's boundaries (is very easy with rectangles) - in the way where it came from (vector opposite to original movement vector).
    2. Check which property (x or y) you changed more, and change the other respectively (in the example you have -x;-y vector, then if you increased y by 10, you also need to increase y by 10 to make sure you're backing up to a position where there's surely room for your rectangle)
3. If you moved player Rectangle, go to point 2. and check for collisions again.
4. If you want playerRectangle not to lose full momentum when hitting a wall, you can update it's vx and vy by smoothEffectX and smoothEffectY and repeat.

The code not tested nor optimized, but still is fast and should show you the idea.

```
//main actors in the drama:
var possiblyCollidingRectangles:Array;
var playerRectangle:Rectangle;
var vx:int;
var vy:int;
var smoothEffectX:int;
var smoothEffectY:int;
//Math.abs ( vx ) == Math.abs ( vy )

// [...]

playerRectangle.x += vx;
playerRectangle.y += vy;
var movedBack:Boolean = false;
do {
   for each ( var rect:Rectangle in possiblyCollidingRectangles ) {
      if ( collides (rect, playerRectangle) ) {
         var boundaries:Boundaries = rect.getBoundaries();
         var x:int = getHorizontalBoundary ( boundaries );
         var y:int = getVerticalBoundary ( boundaries );
         movePlayerRectangleBack ( x, y );
         movedBack = true;
      }
} while ( movedBack );

function getHorizontalBoundary ( boundaries:Boundaries ):int
{
   if ( vx > 0 ) return boundaries.left;
   else return boundaries.right;
}

function getVerticalBoundary ( boundaries:Boundaries ):int
{
   if ( vy > 0 ) return boundaries.top;
   else return boundaries.bottom;
}

function movePlayerRectangleBack ( x:int, y:int ):void
{
   var newX:int;
   var newY:int;

   if ( vx > 0 ) newX = x - playerRectangle.width; //I assume registration point of rectangle is in it's top-left corner
   else newX = x;

   if ( vy > 0 ) newY = y - playerRectangle.height;
   else newY = y;

   var dx:int = playerRectangle.x - newX;
   var dy:int = playerRectangle.y - newY;

   var newDX:int=
   var newDY:int;
   if ( Math.abs(dx) > Math.abs(dy) ) {
      if ( sameSign() ) newDY = dx;
      else newDY = -dx;
      smoothEffectY = newDY - dy; //maybe dy - newDY, not sure
   } else {
      if ( sameSign() ) newDX = dy;
      else newDX = -dy;
      smoothEffectX = newDX - dx; //maybe dx - newDX, not sure
   }

   playerRectangle.x += newDX;
   playerRectangle.y += newDY;
}

function sameSign ():Boolean //is playerRectangle's vx and vy both negative or both positive?
{
   return (playerRectangle.vx < 0 && playerRectangle.vy < 0) || (playerRectangle.vx >= 0 && playerRectangle.vy >= 0)
   // or just !(playerRectangle.vx < 0 XOR playerRectangle.vy < 0)
}

```

Now, I know in your case it's a ball. It's a little harder, but here's how you should do it:

* take the vector (x speed, and y speed) and compute angle from it: `var angle:Number = Math.Atan2 ( vx, vy );`
* detect if ball approached the square from top, bottom, left or right
* either use `cosinus(angle) * ball.radius` to offset the ball from square horizontally, or `sinus(angle) * ball.radius` to offset it vertically, depending on 'through which square's border it came'

**And the last point of your question, how to detect ball's callision with a rotated square (I assume it's rotated)**

Well, it's even harder. not much, if you understand that you define a square by 4 lines: `x1=square.x`; `x2=square.x+square.width`; `y1=square.y`; `y2=square.y+square.width`; And a rotated square by also 4 lines: `x1=square.x+cosinus(square.angle)*y`; `x2=square.x+cosinus(square.angle)+square.width;` etc.

And you define a circle by: `x = Math.abs ( Math.sqrt(r*r-y*y) )` or `y = Math.abs ( Math.sqrt(r*r-x*x) )`

---
Tags: java, collision-detection, tilemap, collision-resolution
---


title: Complementing Ogre3D and C++

text:
# Question
Title: Complementing Ogre3D and C++
I will start my first 3D game, and for now I'm inclined to Ogre3D and C++. But Ogre3D isn't an engine. It is a 3D rendering library, and quoting another user here in GameDev: *Ogre3D does not have integrated **collision**, **physics**, **networking**, **sound**, **scripting**, etc.*

My question is, what the solutions for that "missing features"? Is there some good free/oss libraries to make that parts?

# Answer
> 3 votes
Have you checked gamekit? Not the irrlitch version (deprecated) but the ogre3d one, also known as ogrekit.

It's a whole set of libraries that cover most of the aspects of a game engine. Code is super clean (imho), project setup is awesome (imho) and as a bonus it works out of the box on several platforms.

Best part, you can cut off what you don't need or replace it.

---
Tags: c++, ogre
---


title: MMO Data Persistence Question

text:
# Question
Title: MMO Data Persistence Question
I wanted to ask a question regarding data persistence strategies for an MMO. I have some experience in the games industry with social synchronous games. At Zynga, we stored static proto data in XML on both the client and the server and stored instance/runtime data in membase. For clarity sake, proto data for a Potion would be PotionName or MaxCharges, while runtime/instance data would be something like ChargesRemaining. So basically, if a player picks up a potion the instance is (via prediction) created from XML data on the client, the request gets sent to the server where the instance is created from XML and then added to membase.

Is the same strategy that would be used for soemthing like an MMO? Would it be feasible to have static proto data in some kind of in-memory no-sql database on both client and server with instance data being stored on the server in a more enterprise level database? Or should all data (proto/instance) be stored on the server and the client gets everything from server?

I know a lot of this might on certain game requirements, however, i'm basically looking for some general opinion/best practices here if there are any.

# Answer
> 4 votes
Is the same strategy that would be used for something like an MMO? Definitely, but up to a point. The static data is typically deployed with (or patched to) the client and dynamic data is presented by the server when necessary.

But in between those 2 extremes are bits of static data that you don't want to sit on a client all the time. This might include the stats for secret items, or map data for hidden areas. On the server, this will probably be stored in the same way as the other static data - but it'll be sent to the client on a need-to-know basis.

As for the actual storage strategies, there are almost as many approaches as there are games, because each game makes different requirements on the data. On the server side, myself and others supplied several answers here: What kind of databases are usually used in an MMORPG? And on the client side, their 'in-memory no-sql database' is often just a data structure they wrote themselves based on reading in a file format they may have also written themselves.

---
Tags: mmo
---


# Question
Title: Creating models in 3ds max and exporting as .x for XNA
I have created a few models in 3DS max which contains textures, geometry and animations . .however .fbx doesnt really support textures.. So im planning to use .x format.. I have seen a few converters in pandasoft but once i unzip the file and place the .dle file in the plugins folder of 3D max gives an error saying failed to initialize.. Is there any way to convert my .max models into .x format ? ? I dont know blender so that isnt an option. . I'm currently using 3ds max 2013

After adding the .3DS object content importer. . i get the following error:

.3Ds files along with the solution

# Answer
I recommend just using the native 3DS file format. There is an open source project that contains a content processor allowing you to do just that. To add the file type as an option follow Microsoft's tutorial on adding a custom processor.
> 2 votes

---
Tags: xna-4.0, 3dsmax
---


# Question
Title: DrawIndexedPrimitives overdraws data in previous buffer if called in loop
*I doubled the question from stackoverflow here, and will delete the opposite of a question that gave me the answer.*

I have the Draw method in one of my renderers, that loops through the dictionary and gets precollected and preinitialized buffers. When dictionary has only one element, everything is just fine. But with more elements what I get on the screen is only the data from the last buffer (I suppose, not sure)

My Draw method:

```
public void Draw(GameTime gameTime)
{
    if (!_areStaticEffectsSet)
    {
//          blockEffect.Parameters["TextureAtlas"].SetValue(textureAtlas);
            blockEffect.Parameters["HorizonColor"].SetValue(World.HORIZONCOLOR);
            blockEffect.Parameters["NightColor"].SetValue(World.NIGHTCOLOR);

            blockEffect.Parameters["MorningTint"].SetValue(World.MORNINGTINT);
            blockEffect.Parameters["EveningTint"].SetValue(World.EVENINGTINT);

            blockEffect.Parameters["SunColor"].SetValue(World.SUNCOLOR);

            _areStaticEffectsSet = true;
        }

        blockEffect.Parameters["World"].SetValue(Matrix.Identity);
        blockEffect.Parameters["View"].SetValue(_player.CameraView);
        blockEffect.Parameters["Projection"].SetValue(_player.CameraProjection);
        blockEffect.Parameters["CameraPosition"].SetValue(_player.CameraPosition);
        blockEffect.Parameters["timeOfDay"].SetValue(_world.TimeOfDay);

        var viewFrustum = new BoundingFrustum(_player.CameraView * _player.CameraProjection);

        _graphicsDevice.BlendState = BlendState.Opaque;
        _graphicsDevice.DepthStencilState = DepthStencilState.Default;

        foreach (KeyValuePair<int, Texture2D> textureAtlas in textureAtlases)
        {
            blockEffect.Parameters["TextureAtlas"].SetValue(textureAtlas.Value);

            foreach (EffectPass pass in blockEffect.CurrentTechnique.Passes)
            {
                pass.Apply();

                //TODO: Отправлять сгруппированные из чанков по атласам текстур VertexBuffer и IndexBuffer
                foreach (Chunk chunk in _world.Chunks.Values)
                {
                    if (chunk == null || chunk.IsDisposed)
                    {
                        continue;
                    }

                    if (chunk.BoundingBox.Intersects(viewFrustum) && chunk.GetBlockIndexBuffer(textureAtlas.Key) != null)
                    {
                        lock (chunk)
                        {
                            if (chunk.GetBlockIndexBuffer(textureAtlas.Key).IndexCount > 0)
                            {
                                VertexBuffer vertexBuffer = chunk.GetBlockVertexBuffer(textureAtlas.Key);
                                IndexBuffer indexBuffer = chunk.GetBlockIndexBuffer(textureAtlas.Key);
                                //if (chunk.DrawIndex == new Vector3i(0, 0, 0))
                                //{
                                    //if (textureAtlas.Key == -1)
                                    //{
                                        //var varray = new []
                                        //{
                                            //new VertexPositionTextureLight(new Vector3(0,68,0), new Vector2(0,1),1,new Vector3(0,0,0), new Vector3(1,1,1)),
                                            //new VertexPositionTextureLight(new Vector3(0,68,1), new Vector2(0,1),1,new Vector3(0,0,0), new Vector3(1,1,1)),
                                            //new VertexPositionTextureLight(new Vector3(1,68,0), new Vector2(0,1),1,new Vector3(0,0,0), new Vector3(1,1,1))
                                        //};

                                        //var iarray = new short[] {0, 1, 2};
                                        //vertexBuffer = new VertexBuffer(_graphicsDevice, typeof(VertexPositionTextureLight), varray.Length, BufferUsage.WriteOnly);
                                        //indexBuffer = new IndexBuffer(_graphicsDevice, IndexElementSize.SixteenBits, iarray.Length, BufferUsage.WriteOnly);

                                        //vertexBuffer.SetData(varray);
                                        //indexBuffer.SetData(iarray);
                                    }
                                }

                                _graphicsDevice.SetVertexBuffer(vertexBuffer);
                                _graphicsDevice.Indices = indexBuffer;
                                _graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexCount, 0, indexBuffer.IndexCount / 3);
                            }
                        }
                    }
                }
            }
        }
    }

```

Noteworthy things about the code:

XNA version is 4.0.

I've commented the debugging code in the loop, but left it for it may bring some insight.

I try not only to change vertices/indices in the loop, but textureAtlas also. Code in the shader about textureAtlas:

```
Texture TextureAtlas;
sampler TextureAtlasSampler = sampler_state
{
    texture = <TextureAtlas>;
    magfilter = POINT;
    minfilter = POINT;
    mipfilter = POINT;
    AddressU = WRAP;
    AddressV = WRAP;
};

struct VSInput
{
    float4 Position : POSITION0;
    float2 TexCoords1 : TEXCOORD0;
    float SunLight : COLOR0;
    float3 LocalLight : COLOR1;
    float3 Normal : NORMAL0;
};

```

VertexPositionTextureLight is my own realization of IVertexType.

So, do anybody know about this problem, or see the wrongness in my code (that's far more likely)?

# Answer
> 0 votes
The problem is not in overdrawing but indeed in wrong VertexBuffer or/and wrong IndexBuffer content as snake5 noticed.

---
Tags: xna, c#, vertex
---


title: MMORPG game balancing

text:
# Question
Title: MMORPG game balancing
I've seen a couple of examples of some game balancing techniques in books yet they are not comprehensive and not particularly aimed at MMORPGs but I'm looking for practical examples of game balancing techniques for MMORPGs. I am interested to know if anyone has documented the techniques used in popular games with proven success in this area. Ideally, any resource would cover most common types of stats and include layman mathematical models or techniques used to balance game mechanics found in advanced MMORPGs (I know it's a cliché, but WoW style)

Any help would be great!

# Answer
> 4 votes
For balancing mechanics, Grab some friends, and do it manually, the fun way. If your game is good i doubt they would disagree, just spend a weekend playing your MMO for a bit. This should help get the basics out of things like whether bleeding needs a nurf or buff, whether being crippled needs to slow down a character more or less, etc.

For balancing moves and such, try a beta, open or closed and give players the chance to give feedback. Given the fact that your balancing is for the players, maybe players should have a say in the balancing?

I know this isn't about documentation, but it is still THE BEST option out. Or i could save my answer by saying "Documents from players beat general guideline documents".

# Answer
> 11 votes
Have fun. Balancing a MMORPG is supposed to be one of the most difficult things in the industry. People have documented basic guidelines though and here are some articals I found on the subject.

Elder Games

Gamasutra its always a good place to start.

# Answer
> 3 votes
Your first step is to define what an ideal balance for your game would be. The easiest way to start this is with simple statements. For example, "Character classes should not disadvantage players when fighting other players" or maybe "Character classes will have advantages over some other classes and disadvantages to others (think Rock Paper Scissors)"

You need to define what balance is for your game.

Once you've defined what balance means for your game, then you need to quantify it. Using the all classes are equal example above: "Average Class Kill/Death ratio, for any two given classes, should fall close to 1.0 within an error tolerance. The error tolerance is set at .5 when any new balancing is added and decreases to a minimum of .05."

So now you can identify what is in balance and what is out of balance with some statistics. The error tolerance part is to allow for statistical errors that should become less significant with more activity. If you see the numbers going out of this range, you know there's a balance issue.

All of this requires that you collect, keep and analyze data about everything in the game. You need this data to run against the quantitative balance checks.

When you do find something out of balance, don't fix it until you have a good idea what is causing the problem. Trying to fix things, without knowing the problem will make things worse. This is why you need to track data on as much about your game as you can, and not just the data specific to the balance.

# Answer
> 1 votes
I always wonder, why don't mmorpg creators make a self-balancing system, where a skill/item gets it's strength from it's rarity. That is, every day a skill is more popular than an average, it gets weaker, and if it's less popular, it gets stronger.

That said, I remember playing the Witcher: Versus browser mmo, with 3 classes: frightener, sorcerer, wither. People were complaining on forum that witcher is not balanced (much worse than other classes), and developers were responding "it's a class taken by 80% of players!". Incorporating a self-balancing system here would make the witcher class even worse - but in my opinion that makes sense.

---
Tags: game-design, mmo
---


# Question
Title: Depth interpolation for z-buffer, with scanline
I have to write my own software 3d rasterizer, and so far I am able to project my 3d model made of triangles into 2d space:

*I rotate, translate and project my points to get a 2d space representation of each triangle. Then, I take the 3 triangle points and I implement the scanline algorithm (using linear interpolation) to find all points\[x\]\[y\] along the edges(left and right) of the triangles, so that I can scan the triangle horizontally, row by row, and fill it with pixels.*

This works. Except I have to also implement z-buffering. This means that knowing the rotated&translated z coordinates of the 3 vertices of the triangle, I must interpolate the z coordinate for all other points I find with my scanline algorithm.

The concept seems clear enough, I first find Za and Zb with these calculations:

```
var Z_Slope = (bottom_point_z - top_point_z) / (bottom_point_y - top_point_y);
var Za = top_point_z + ((current_point_y - top_point_y) * Z_Slope);

```

Then for each Zp I do the same interpolation horizontally:

```
var Z_Slope = (right_z - left_z) / (right_x - left_x);
var Zp = left_z + ((current_point_x - left_x) * Z_Slope);

```

And if current z is closer to the viewer than the previous z at that index THEN write the color to the color buffer AND write the new z to the z buffer. (my coordinate system is x: left -\> right; y: top -\> bottom; z: your face -\> computer screen;)

The problem is, it goes haywire. The project is **here** and if you select the "Z-Buffered" radio button, you'll see the results... (*note that I use the painter's algorithm (-only- to draw the wireframe) in "Z-Buffered" mode for debugging purposes*)

PS: I've read here that you must turn the z's into their reciprocals (meaning `z = 1/z`) before you interpolate. I tried that, and it appears that there's no change. What am I missing? (could anyone clarify, precisely where you must turn z into 1/z and where(if) to turn it back?)

**\[EDIT\]** Here's some data on what maximum and minimum z values I get:

```
    max z: 1;                  min z: -1;                 //<-- obvious, original z of the vertices of the triangles
    max z: 7.197753398761272;  min z: 3.791703256899924;   //<-- z of the points that were drawn to screen (you know, after rotation, translation), by the scanline with zbuffer, gotten with interpolation but not 1/z.
    max z: 0.2649908532179404; min z: 0.13849507306889008;//<-- same as above except I interpolated 1/z instead of z.
//yes, I am aware that changing z to 1/z means flipping the comparison in the zBuffer check. otherwise nothing gets drawn.

```

Before I go into painstaking debugging, can someone confirm that my concept so far is correct?

## \[EDIT2\]

I have solved the z-buffering. As it turns out, the drawing order wasn't messed up at all. The z coordinates were being calculated correctly.

*The problem was, in an attempt to increase my frame rate, I was drawing 4px/4px boxes, every 4th pixel, instead of actual pixels on screen. So I was drawing 16px per pixel, but checking the z buffer for only one of them. I'm such a boob.*

**TL/DR:** The question still stands: How/why/when do you have to use the reciprocal of Z (as in 1/z) instead of Z? Because right now, everything works either way. (there's no noticeable difference).

# Answer
> 6 votes
Quick answer: Z is not a linear function of (X', Y'), but 1/Z is. Since you interpolate linearly, you get correct results for 1/Z, but not for Z.

You don't notice because as long as the comparison between Z1 and Z2 is correct, the zbuffer will do the right thing, even if both values are wrong. You will definitely notice when you add texture mapping (and to answer the question you'll have then: interpolate 1/Z, U/Z and V/Z, and reconstruct U and V from these values: U = (U/Z)/(1/Z), V = (V/Z)/(1/Z). You'll thank me later)

An example. Get a piece of paper. Top-down view, so forget the Y coordinate. X is the horizontal axis, Z is the vertical axis, the camera is at (0, 0), the projection plane is z=1.

Consider the points A(-2, 2) and B(2, 4). The mid point M of the segment AB is (0, 3). So far so good.

You project A into A': X' = X/Z = -1, so A' is (-1, 1). Likewise, B' is (0.5, 1). But note that the projection of M is (0, 1), which is NOT the midpoint of A'B'. Why? Because the right half of the segment is farther away from the camera than the left half, so it looks smaller.

So what happens if you try to compute the Z of M' using linear interpolation? dx = (0.5 - -1) = 1.5, dz = (4 - 2) = 2, so for M' where X' = 0, the linearly interpolated Z is zA + (dz/dx)*(x - xA) = 2 + (2/1.5)*(0 - -1) = 2 + 1.333 = 3.3333 - NOT 3!

Why? Because for every step in the X' direction, you don't move the same amount in the Z direction (or, in other words, Z is not a linear function of X'). Why? Because the more you go right, the farther away the segment is from the camera, so one pixel represents a longer distance in space.

Finally, what happens if you interpolate 1/Z instead? First you compute 1/Z at A and B: 0.5 and 0.25 respectively. Then you interpolate: dx = (0.5 - -1) = 1.5, dz = (0.25 - 0.5) = -0.25, so at X' = 0 you compute 1/Z = 0.5 + (-0.25/1.5)\*(0 - -1) = 0.3333. But that's 1/Z, so the value of Z is... exactly, 3. As it should be.

Yeah, math is awesome.

---
Tags: javascript, depth-buffer, interpolation, software-rendering
---


# Question
Title: How to draw realtime 3D amoebas in OpenGL?
How would one draw 3D amoebas in real-time in OpenGL? The key components I'm looking for are:

1. Curved closed surface that changes shape
2. Generally transparent
3. Something translucent inside showing the volume is occupied

It has to be in real-time, and be able to handle many (100's) of these moving and animating on screen simultaneously.

What techniques might one use to accomplish this?

# Answer
> 1 votes
1) One approach to create deformable objects like amoeba is to use mass/spring system. You would create few springs that would control position of mesh vertices. You could use some kind of weight system to control how much springs' ends affect each vertex (like in skeletal animation). Also, springs would be affected by some forces, like gravity. Springs math is not very complicated so calculations are not so expensive. You can use Euler's numerical integration for calculations. Take a look at Hooke's law.

This is a problem under Soft body dynamics domain so I suggest you to google about it and spring systems. There is a lot of material online.

2) I think the main job is to do geometry (shape). To make it transparent just apply some transparent material.

3) Depending on your needs, you can put anything inside that geometry. If you want inside object also to be deformable, you can create similar (by that I mean object controlled by spring system) but smaller object, or you could just render same object after applying some scaling to modelview matrix.

# Answer
> 3 votes
One obvious and simple technique is to render offline one or more looping animated amoebas and then draw them as screen facing quads.

That will get you very good performance at the cost of fairly low flexibility.

---
Tags: opengl, rendering
---


title: Sprite Animation using cocos2dx 2.0.2

text:
# Question
Title: Sprite Animation using cocos2dx 2.0.2
I am trying to implement sprite animation using coco2dx. I have tried several demos, but all of them are same. While I tried, getting violation error in my code.

```
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("AnimBear.plist");
    CCSpriteBatchNode *spreetsheet = CCSpriteBatchNode::create("AnimBear.png");
    this->addChild(spreetsheet);

CCArray *bearArray = new CCArray();
     for(int i = 1; i <= 8; i++)
{
        char name[32] = {0};
         sprintf(name, "bear%d.png",i);
        bearArray->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name));
}
    CCAnimation *walkAnim = CCAnimation::animationWithSpriteFrames(bearArray, 0.1f);
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    CCSprite *bear = CCSprite::spriteWithSpriteFrameName("bear1.png");
    bear->setPosition(ccp(size.width/2, size.height/2));
    CCAction *walkAction = CCRepeatForever::actionWithAction(CCAnimate::actionWithAnimation(walkAnim));
    bear->runAction(walkAction);
spreetsheet->addChild(bear);

```

Error is coming in first line while we passing plist refrence. I am using Visual Basic 2010 and put both files in Resource folder (png and plist).

# Answer
> 2 votes
I have this code working in cocos2dx 2.0.3, also make sure that you've added the plist and png file to your project, sometimes visual studio can be a bit funny about resources.

```
   CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("AnimBear.plist"    );
    CCSpriteBatchNode *spreetsheet = CCSpriteBatchNode::create("AnimBear.png");
    this->addChild(spreetsheet);

    CCArray *bearArray = new CCArray();
    for(int i = 1; i <= 8; i++)
    {
        char name[32] = {0};
        sprintf(name, "bear%d.png",i);
        bearArray->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name));
    }

    CCAnimation *walkAnim = CCAnimation::createWithSpriteFrames(bearArray, 0.1f);
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    CCSprite *bear = CCSprite::createWithSpriteFrameName("bear1.png");
    bear->setPosition(ccp(size.width/2, size.height/2));
    CCAction *walkAction = CCRepeatForever::create(CCAnimate::create(walkAnim));
    bear->runAction(walkAction);
    spreetsheet->addChild(bear);

```

---
Tags: c++, cocos2d-x
---


title: OpenGL Get Rotated X and Y of quad

text:
# Question
Title: OpenGL Get Rotated X and Y of quad
I am developing a game in 2D using LWJGL library.

So far I have a rotating box. I have done basic Rectangle collision, but it doesn't work for rotated rectangles.

Does OpenGL have a function that returns the vertices of rotated rectangle? Or is there another way of doing this using trigonometry?

I had researched how to do this and everything I found was using some matrix that I don't understand so I am asking if there is another way of doing this.

For clarification, I am trying to find out the true (rotated) X,Y of each point of the rectangle. Let's say, the first point of a rectangle (top,left) has x=10 y=10.. Width and height is 100 pixels. When I rotate the rectangle using glRotatef() the x and y stay the same. The rotation is happening inside OpenGL. I need to extract the x,y of the rectangle so I can detect collisions properly.

# Answer
> 3 votes
OpenGL just does the displaying, it doesn't do these kind of jobs for you.

One way to rotate points is to calculate the angle and distance to the point around which it should be rotated, applying the rotation to the angle and then converting the angle and distance back to a coordinate with sin and cos.

x and y are relative to the center of the object.

```
angle = atan2(y, x);
distance = sqrt(x*x + y*y);
angle += rotation;
rotatedX = sin(angle)*distance;
rotatedY = cos(angle)*distance;

```

# Answer
> 2 votes
The hard answer is that it involves matrix multiplication. I sat here trying to think of a way to answer it otherwise, but I don't know of a way. This said, the good news is that basic vector mathematics is not hard at all. In fact, I have a great resource: 3D Math Primer for Graphics and Game Development

It is not only a good book on math, but a great book on game development in general. The foundation of all 2D and 3D games using objects involves basic vectors and angles, so it's very good to know.

Lecture aside (I know I hate when people do this to me!) this is what you have to do in broad strokes:

Moving objects have to be accounted for before they collide and before its viewable on the screen. There is something called the swap chain, during which images are rendered and then posted. What you'll have to do is create a bound sphere or some sort of collision detection mechanism that checks whether or not the rectangle is nearby. Unfortunately again, I cannot explain binding spheres or anything else about it without some math.

On a side note, it's part of the business. And it's not like it is in school! Check out the book, I think it will answer all your questions. And if it doesn't, the book Real-Time Collision Detection sure will.

# Answer
> 1 votes
OpenGL has something called transform feedback, it allows you to capture output returned from the vertex/geometry shaders into a buffer.

Transform feedback is somewhat new, it has been in OpenGL since 3.0 so it might not be usable for you if you require compatibility with older systems (such as Mac OSX from a few versions ago).

Also you should note that glRotatef is now an outdated function, you are doing things in a deprecated inefficiant way.

I recommend you look at this post I made that goes into more detail about OpenGL 3.x+.

Having said that, this seems like a poor way to do collision detection. Might I suggest you look at embedding a proper physics engine, I recommend Bullet. You will get much more than collision detection out of it.

---
Tags: opengl, java, collision-detection, rotation, lwjgl
---


# Question
Title: Trying to Draw a 2D Triangle in OpenGL ES 2.0
I'm trying to convert a code from OpenGL to OpenGL ES 2.0 (for the BlackBerry PlayBook). So far what I got is this (just the part of the code that should draw the triangle):

```
void setupScene() {
    glClearColor(250, 250, 250, 1);
    glViewport(0, 0, 600, 1024);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void drawScene() {
    setupScene();

    glColorMask(0, 0, 0, 1);

    const GLfloat triangleVertices[] = {
        100,   100,
        150,  0,
        200,   100
    };

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, triangleVertices);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 2);
}

void render() {
    drawScene();
    bbutil_swap();
}

```

The problem is that when I launch the app instead of showing me the triangle the screen just flickers (very fast) from white to gray. Any idea what I'm doing wrong?

Also, here is the entire code if you need: **Full source code**

# Answer
> 4 votes
What you are trying to do is available in the project: http://code.google.com/p/opengles-book-samples/

The OpenGL ES 2.0 does not support the fixed rendering pipeline, so you will need to come up with your own shaders. Take a closer look at the utility functions to compile and load shaders, also, the "Hello Triangle" sample... Very good way to get started if you already know your way around OpenGL.

# Answer
> 1 votes
You have to use shaders. And I also believe the arguments of glDrawArrays are wrong - you need to pass the number of indices as the last one.

Oh, and you're using fairly large values for the triangle's position, but you have no view and projection matrix set up, so they will be way outside the screen.

As for the flickering, you need to call glClear per draw, not just once.

---
Tags: 2d, opengl-es, opengl-es2
---


# Question
Title: How can you run events after a set amount of time in SFML 2.0?
I've been using SFML 1.6 for a while and recently upgraded to 2.0, apparently there's a new sf::Time type however I'm clueless as to how I can achieve running of a certain function after a set amount of time.

How would you go about doing this? Say you want something to execute after 5 seconds, how would you do it in SFML?

# Answer
> 3 votes
SFML provides a delta time function.

```
sf::Clock deltaClock;
for (;;)
{
    // ...
    sf::Time dt = deltaClock.Restart();
}

```

from : http://en.sfml-dev.org/forums/index.php?topic=7068.0

Time class:
http://www.sfml-dev.org/documentation/2.0/classsf\_1\_1Time.php

Basically what you could do is create a class that holds pointers to functions you want to call. And for each function you have a "clock" ( a simple float or int ) in a time table(Array/Vector) that is iterated over in combination with the delta time to see if x amount of seconds have passed. If so you do a callback on the associated function.

I'm not that much deep into C++ and there is probably a clever way to do it. There is also this : http://www.bromeon.ch/libraries/thor/

Which is build ontop of SFML but it requires C++11. It's an unofficial extension library that has some great event triggering functionality.

On the upside of C++11, it supports "function" objects. Which help ease out some function referencing.

Also google for events and C++ if you really want to dive deep into it.

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


# Question
Title: Getting velocity in only one plane (X) in Kismet (UDK)
I'm trying to make a character in 2.5 platformer (in UDK) to "climb" a giant tree trunk by walking on a spiral staircase enveloped around the tree. When character goes right the tree rotates thru matinee sequence so it seems that the character is moving while in reality it is the tree that moves.

I connected the matinee sequence playrate to the velocity of the character and its all good as long the character just moves left or right. When it jumps though, the velocity still affects the playrate - it should not as character moves up/down, not right/left.

How do I set it up in Kismet so I get a float variable with velocity only in the X plane (horizontal)?

# Answer
**Option 1.** A 2D or 3D velocity vector's X component is exactly the velocity in the X plane.

**Option 2.** If you can't access the Vector.X property's value (again, I'm not sure how Kismet works), then just multiply the original velocity vector with a **new Vector(1,0)**, where 1 is the X component and Y is 0. This is gonna give you the velocity in the X plane as a vector.
> 1 votes

# Answer
"@anna1987 A 2D or 3D velocity vector's X component is exactly the velocity in the X plane. If you can't access the Vector.X property's value (again, I'm not sure how Kismet works), then just multiply the original velocity vector with a new Vector(1,0), where 1 is the X component and Y is 0. This is gonna give you the velocity in the X plane as a vector. – Marton"

Of course it is! I'm such a retard stupid blonde! Thanks guys! xoxo
> 1 votes

---
Tags: udk
---


title: Smooth pixels while rotating sprite

text:
# Question
Title: Smooth pixels while rotating sprite
I just started with andengine, so this maybe gonna be silly question. How to make my sprites more smooth while I rotate them? Or maybe it because this is screenshot from tablet?

Thanks JohnEye it works:

Just need to change my BitmapTextureAtlas from:

```
BitmapTextureAtlas carAtlas = new BitmapTextureAtlas(this.getTextureManager(),100, 63);

```

to:

```
BitmapTextureAtlas carAtlas = new BitmapTextureAtlas(this.getTextureManager(),100, 63, TextureOptions.BILINEAR);

```

# Answer
> 4 votes
Your TextureOptions settings are likely to be the cause, see the call that you use for creating your TextureAtlas. Try the different TextureOptions and see which one you like the most. For more information, see the related thread on the AndEngine forum.

---
Tags: android, sprites, andengine, antialiasing
---


title: Advice needed for a physics engine

text:
# Question
Title: Advice needed for a physics engine
I've recently started a project, building a physics engine. I was hoping you could give me some advice related to some documentation and/or best technologies for this.

First of all, I've seen that Game-Physics-Engine-Development is highly recommended for the task at hand, and I was wondering if you could give me a second opinion.Should I get it? Also, while browsing Amazon, I've stumbled onto Game Engine Architecture and since I want to build my physics engine for games, I thought this might be a good read aswell.

Second, I know that simulating physics is highly computation intensive so I would like to use either CUDA or OpenCL.Right now I'm leaning towards OpenCL, because it would work on both NVIDIA and ATI chipsets.What do you guys suggest?

PS: I will be implementing this in C++ on Linux.

# Answer
> 11 votes
Here is how I learned to write a physics engine, its all free and highly recommendable:

1. David Baraff's papers particulary An Introduction to Physically Based Modeling
2. Brian Vincent Mirtich's Thesis Impulse-based Dynamic Simulation of Rigid Body Systems
3. Kacic/Bullock "A practical dynamics system" SIGRAPH 2003, *EDIT: Link added*.

Those papers were mentioned in another great article from Nick Porcino (LucasArts) in one of the gems-books Gems 4 "Writing a Verlet-Based Physics Engine". Its not free, but its worth every penny.
Also have a look at other engines, here is the source for the Bullet Physics Engine.
About the CUDA/OpenCL implementation: make it run on the CPU first, it's complicated enough :)
Be aware that most likely you will throw your engine away after a while, since its just too hard to make a stable and well integrated physics engine with a competitive feature-list on your own, however it's a great learning experience!
As soon as you have a simple engine running, my advice is: make test-scenarios where you compare the result of your engine with the result of another engine. This helped me find a lot of errors and it will improve your interface; something like appling a similar force for 1 second at the same body in both engines.
Last but not least: Ignore collisions when you start, focus on a stable simulation first.

# Answer
> 6 votes
Maik is right, Baraff's papers are an excellent start, but don't forget Chris Heckers write-up on rigid body dynamics: http://chrishecker.com/Rigid\_Body\_Dynamics !

Also his advice on "\[..\] you will throw your engine away" is entirely true. But you will learn a lot!

Regarding the CUDA/OpenCL part of your question: If you know CUDA then switching to OpenCL becomes very easy. I'd recommend learning CUDA first, because there are so many good tutorials, example code and computation libraries out there. For example:

But be aware: Getting started on CUDA is easy, getting started on physics simulation is a good bit harder, but combining both is quite a challenge!

# Answer
> 6 votes
I started out with Baraff too but it's a bit dated by now. What you need is iterative solvers and the best paper imo on that is Erin Catto's Iterative Dyanmics. You have all you need in there to implement your physics engine. You can dig a bit into Erleben's PhD thesis if you need more details (like joints and more math stuff), but that's pretty much it. I wish I had found it from the start - go through the Bullet forum a bit, there's plenty information in there (maybe too much).

As for books many of the books out there are disappointing, but I do recommend Physics Based Animation by Kenny Erleben or Game Physics Pearls.

Don't know much CUDA/OpenCL (although I always wanted to do it) but you should definitely check out Takahiro Harada's work.

---
Tags: c++, physics-engine
---


# Question
Title: How to apply numerical integration on a graph layout
I've done some basic 1 D integration, but i can't wrap my head around things and apply it to my graph layout. So, consider the picture below:

* if i drag the red node to the right, i'm forcing his position to my mouse position
* the other nodes will "follow" him, but how ?

For Verlet, to compute the newPosition, i need the acceleration for every node and the currentPosition. That is what i don't understand.

How to i compute the acceleration and the currentPosition ?

The currentPosition will be the position of the RedNode ? If yes, doesn't that means that they will all overlap ?

https://i.stack.imgur.com/NCKmO.jpg

# Answer
If I understand your question right and you want to connect the nodes by springs, that apply forces when the spring is not at its rest-length (in other words when you drag it), then look at Hook's Law, it explains the mechanics and forces of springs.

But you will need any kind of physics-engine.

> > How to i compute the acceleration and the currentPosition ?

Using Hook's Law:

```
F = -kx
A = F/m

```

Here you can find a nice tutorial about springs using Hook's Law.
> 2 votes

# Answer
The question is indeed not very clear. But you did mention Verlet so I guess what you want is to enforce some constraints on those links - read Jakobsen's paper, you've got all you need in there, no need for springs.
> 2 votes

---
Tags: physics, graphs
---


# Question
Title: Rotating a child shape relative to its parent's orientation
When rotating a shape using a quaternion value I also wish rotate its child shape.

The parent and child shapes both start with different orientations but their relative orientations should always be the same.

How can I use the difference between the previous and current quaternions of the parent shape in order to transform the child segment and rotate it relative to its parent shape?

```
    public Quaternion Orientation
    {
        get { return entity.Orientation; }
        set
        {
            Quaternion previousValue = entity.Orientation;
            entity.Orientation = value;

            // Use the difference between the quaternion values to update child orientation
        }
    }

```

EDIT:

If I have understood `teodron` correctly then this is what I must do

```
// Qc' = Qp' * Inv(Qp) * Qc
//
// Where:
// Qp   = Parent orientation last frame
// Qp'  = Parent orientation this frame
// Qc   = Child orientation last frame
// Qc'  = Child orientation this frame

set
{
    Quaternion previousValue = entity.Orientation;

    entity.Orientation = value;

    Quaternion childOrienation = value * Quaternion.Inverse(previousValue) * childOrientationPrev;
    //Quaternion childOrienation = childOrientationPrev * Quaternion.Inverse(previousValue) * value;
}

```

I have tried both multiplication orders but neither method rotates the child object correctly and instead it spins very quickly.

# Answer
> 1 votes
Just store the static orientation difference between parent and child once at startup, lets call it qDiff.

Whenever you set the new parent orientation, set child's orientation like this:

```
qChild = qNewParentOrientation * qDiff

```

# Answer
> 0 votes
Update:

Tested and confirmed to work:

Say you have two objects: a *source* and a *target* object.

The target must keep a certain relative orientation with respect to a source object. This is really the case with most fundamental camera tracking scenarios (e.g. camera behind a flying entity - plane, spaceship, etc.).

If a given reference pose of this binary system is given, say at start-up, then we must grab hold on the orientations of the source and target objects:

* **Qtgt0** = the quaternion describing how the frame of the target relates to the world frame
* **Qsrc0** = the quaternion describing how the frame of the source object relates to the world frame

The 0 suffix denotes the initial state. These two quats shouldn't change from now on, they remain untouched. The *relative* orientation of a target with respect to a source is **not** the difference of the quaternions, but this guy: **Qsrc0.inverse** * **Qtgt0** (something similar to a division operator for quaternions - but since the quaternion multiplication does not commute, such an operator is "left or right handed").

At a certain time instance, the source has the **Qsrc** orientation. To couple the orientation of the target to that of the source, *set* the orientation of the target to be:

**Qtgt** = **Qsrc** * **Qrelative** = **Qsrc** * **Qsrc0.inverse** * **Qtgt0**

The picture below illustrates an experiment where a cube gets the camera's quat and a parabolic tube springing from one of the cube's faces rotates with the cube **although** they are *not* attached to the same scene node, nor is the cube's node a child of the cube's node (talking hierarchical node transformations in a scene graph). Both objects are linked to the world independently, but when the scene is created, their relative orientation is stored separately for future updates.

##

*An example:*

Say you have a *ship* and a *camera* object in a simple scene.

Let **Qs** be the ship's current quat and **Qc** the camera's current quaternion. Let this configuration **Qs,Qc** be the initial, reference position you are talking about.

If the ship changes its orientation from **Qs** to **Qs'**, then you could write:

**Qs'** = **Qs'** * **inv(Qs)** * **Qs**

**Qs'** * **Qs** is a *relative* rotation transformation. If you apply it to the camera's initial orientation, you get a new camera orientation that should be in tune to your ship's change in orientation, as desired. The **inv(Qs)** factor tells us that there is an intricate orientation coupling that is initially set, between our camera and ship objects.

**inv(q)** denotes the inverse of a quat, which is the same as its conjugate **q\*** if the quat is normalized.

Further explanation:

To get a result, the camera's orientation, when the ship changes heading, should look like:

**Qc'** = **Qs'** * **inv(Qs)** * **Qc**

Be aware that the ***_*** *operator is the quaternion multiplication. When rotating vectors, you will multiply the orientation quat **q** with (0,\_v\_) and then right multiply it by **q***.

---
Tags: 3d, mathematics, matrix, rotation, quaternion
---


# Question
Title: Drawing application on OpenGL for iOS (iPad)
Some help is needed. I'm developing drawing application on OpenGL (deployment target 4.0) for iOS (iPad). We have 3 drawing tools: pen, marker (with alfa) and eraser. I apply drawing with textures using blending in orthographic projection. I can't use z-ordering because in this case I have to face a lot of troubles with cutting and erasing. The thing that I need is to make the pen be always on the top. When I first use the marker and then the pen - it's ok. But if I use pen first and marker over the pen - I can't see the pen color under marker. I'd appreciate any help or advice.

# Answer
> 1 votes
I suggest you use opengl lines, since all you can draw are lines with a pen and a marker. That should be more efficient than textures and would eliminate the overlaps. Also keep track of the order in which the lines were drawn.

The thing of using opengl blending in this case is that these kind of problems arise a lot, and the only way to solve them is through trial and error. So I suggest you use opengl lines instead of textures with blending.

---
Tags: opengl, ios, hand-drawn
---


title: Draw multiple objects with textures

text:
# Question
Title: Draw multiple objects with textures
I want to draw cubes using textures.

```
void OperateWithMainMatrix(ESContext* esContext, GLfloat offsetX, GLfloat offsetY, GLfloat offsetZ) {

UserData *userData = (UserData*) esContext->userData;
ESMatrix modelview;
ESMatrix perspective;
    //Manipulation with matrix
    ...
    glVertexAttribPointer(userData->positionLoc, 3, GL_FLOAT, GL_FALSE, 0, cubeFaces);
    //in cubeFaces coordinates verticles cube
    glVertexAttribPointer(userData->normalLoc, 3, GL_FLOAT, GL_FALSE, 0, cubeFaces);
    //for normals (use in fragment shaider for textures)

    glEnableVertexAttribArray(userData->positionLoc);
    glEnableVertexAttribArray(userData->normalLoc);

    // Load the MVP matrix
    glUniformMatrix4fv(userData->mvpLoc, 1, GL_FALSE,
                       (GLfloat*)&userData->mvpMatrix.m[0][0]);

    //Bind base map
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, userData->baseMapTexId);

    //Set the base map sampler to texture unit to 0
    glUniform1i(userData->baseMapLoc, 0);

   // Draw the cube
    glDrawArrays(GL_TRIANGLES, 0, 36);
   }

```

(coordinates transformation is in OperateWithMainMatrix() ) Then Draw() function is called:

```
void Draw(ESContext *esContext)
{
   UserData *userData = esContext->userData;
   // Set the viewport
   glViewport(0, 0, esContext->width, esContext->height);

   // Clear the color buffer
   glClear(GL_COLOR_BUFFER_BIT);

   // Use the program object
   glUseProgram(userData->programObject);

  OperateWithMainMatrix(esContext, 0.0f, 0.0f, 0.0f);

  eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
}

```

This work fine, but if I try to draw multiple cubes (next code for example):

```
void Draw(ESContext *esContext)
{ ...

    // Use the program object
    glUseProgram(userData->programObject);

    OperateWithMainMatrix(esContext, 2.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, 1.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, 0.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, -1.0f, 0.0f, 0.0f);
    OperateWithMainMatrix(esContext, -2.0f, 0.0f, 0.0f);
    eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
}

```

A side faces overlapes frontal face. The side face of the right cube overlaps frontal face of the center cube. How can i remove this effect and display miltiple cubes without it?

# Answer
> 0 votes
You need to turn on depth testing:

```
    gl.glClearDepth(1.0f); // Set depth's clear-value to farthest
    gl.glEnable(GL2.GL_DEPTH_TEST); // Enables depth-buffer for hidden
                                    // surface removal
    gl.glDepthFunc(GL2.GL_LEQUAL); // The type of depth testing to do

```

---
Tags: opengl-es2
---


title: How does one save a procedural world?

text:
# Question
Title: How does one save a procedural world?
I have recently read about how to create procedural worlds... but how do I save one?

In games like Terraria or Minecraft users can freely modify the landscape, but that world can't be recreated from the start seed. What techniques are used to save procedural but modifiable worlds?

# Answer
Save the seed which you used to generate the world, and the modifications either as atomic "commands" or the results of those.

Then when loading the saved game, you do the following:

1. Procedurally generate the part of the world you're currently visiting.
2. Apply the saved commands, or overwrite the generated elements with the saved ones.

Update: And of course, there's the option of saving your generated world just like a normal world, if the resources are available (as seen in Minecraft). In this case, you should save only the parts of the world that have already been visited (otherwise the procedural generation would be pretty much pointless), tile by tile. This eats up more HDD and / or database resources, but will require less CPU power when loading a game.
> 21 votes

# Answer
Saving a procedurally generated world is the same as saving any tile map data.

You would likely want to save the world in binary format, assuming the world is built out of different types of tiles, you will have to:

1. Decide on the total number of different tile types.(depending on that you will need more or less bits to represent each tile)
2. Define the width and height of the visited(modified) world.
3. Represent the world tile by tile from the top-most left tile (including sky) row by row to the bottom-most right tile.
4. If you wish to save up on space, use DEFLATE or a similar algorithm to compress this 2d-array(represented as 1-d) http://en.wikipedia.org/wiki/DEFLATE
5. Use appropriate file I/O for your API to store the data on disk.

You can use the same method to save a voxel based map too.

Storing a vertices based map model is more complex.

Would you like me to elaborate on that subject?
> 8 votes

# Answer
About Minecraft, the world uses voxels so it's quite easy to save, more informations here :

http://www.minecraftwiki.net/wiki/Region\_file\_format

http://www.minecraftwiki.net/wiki/Level\_Format

As already said, save a seed used to generate the world, and adapt your save format to what your world is made of (cubes, atoms, etc...).
> 5 votes

# Answer
Whatever data structure you're using to store the world in memory can be used as a template for writing and reading from disk. The procedural portion of your game will fill these data structures the first time, if no data is available from disk. Then, when you're ready to unload an area from memory, write it to disk as it has been generated or modified.

Whenever you're ready to load a new area into memory, first check to see if it's been generated before and saved to disk. If it has, load it from disk instead of from your procedural generation algorithms.

Typically this would be done with chunks of terrain. You can either save each chunk to it's own file, or create a more complex on disk structure that contains data in a single file with a look-up table. There are other questions about good ways to save your data to disk.
> 4 votes

---
Tags: architecture, procedural, savegame
---


# Question
Title: Cocos2d v2.0 and OpenGL 2.0/1.0: where to start
I started developing my very first game 3 months ago using Cocos2d 2.0 for iPhone. I am now in the stage where I'd like to add some cool effects to the bullets and some special weapons (see my waveforms question here). I got a good answer in the cocos2d-iphone forum (see this one).

Unfortunately I am a bit paralized now. I don't know if I will be overdoing by learning OpengGL 2.0 or if I should just stick ot the old 1.0. There is a good intro on various tutorial's written in Steffen Itterheims blog (see this post).

I would like to add to my game:

* a blur effect to the bullets (here is a tutorial for OpenGL 1.0)
* a waveform (see above)
* some realistic water ripples (here is a nice sample code)

So now, given that I don't want to overdo things but at the same time I want to achieve those effects, from where should I start? Should I discard the OpenGL 1.0 tutorials? OR should I use only OpenGL 1.0 code?

How can I avoid confusion? I mean, it seems that the compiler recognizes both, but that there are some conflictual calls in some circumnstances, I am fairly sure this has some explanation, is there some reference to this somewhere?

# Answer
> 2 votes
Look at the "Shader Test" in the Cocos2d samples.

https://github.com/cocos2d/cocos2d-iphone/blob/master-v2/tests/ShaderTest.m

This applies a Blur fragment shader to a CCTexture2D object from your CCSprite.

As for the other shaders you can find a bunch of running samples here:

http://www.iquilezles.org/apps/shadertoy/

This should get you started.

# Answer
> 2 votes
Have you tried looking at particle emitters?

http://particledesigner.71squared.com

Download that and check out the particle emitters on there, they do what you're after (blur effects and water ripples).

You add the files to your game like so:

http://www.cocos2d-iphone.org/forum/topic/7777

Add them to your resources folder and add them like that.

---
Tags: opengl-es, cocos2d-iphone
---


# Question
Title: How to monetize and protect a engine's and its framework's copyrights and patents?
I created a game engine that handles:

* Rendering levels with 2d textured curved surfaces
* Collisions with curved surfaces
* Animationn paths on and navigation in 2d-sapce

I have also made a framework for:

* Procedural organic level generation with round surfaces
* Level editing
* Light weight sprite design

The engine and framework are written in AS3 and I am in the process of translating the code into HaXe to better support other platforms.

I am also interested in adding

* Animated curved platforms
* More advanced level editing features

Currently, I have a part time job and any time I spend on this engine is either taken out of my limited free time (I'm a student working to support myself through school) or out my time working at my job.

I really believe this engine can make life much easier for people designing Tower Defence games, Shooters and and Platformers while also possibly improving their results. It could also support RTS, RPGs and racing games very well.

It continains original algorithms that could be used for procedural generation of organic round and smooth levels. The algorithms I used are new and are not available in any other level editor I've seen.

In order to constantly improve the Engine and have it tested thoroughly I think the best route is releasing it to the public.

What are the best ways to benefit myself and others with my new framework?

I want to have some lisence, allowing me to share the framework and still benefit from it.

Any advice would be appreciated. This issue has been on my mind a lot this year. I am hoping to find a solution that will bring me some relief.

I am thinking of designing three sample games, releasing them and starting a kickstarter, any advice and thoughts on the matter would be valuable.

My goal is like Markus von Broady suggested, to get people involved in developing the engine and let people use it for games for either a symbolic fee or for free and charge for support. That or use some form of croud sourcing.

Do I need to hire a lawyer to get some sort of legal document to protect my work?

# Answer
> 10 votes
## Licensing

You can try to monetize your game engine & framework from licensing. This most probably means that you will make your software proprietary and closed source to fight piracy (obfuscated AS3 code in your case, maybe you have some external tools that can be protected a bit more), but not necessarily.

There are mostly two types of license that can help in making money from the software itself: commercial and/or freeware/shareware.

**Commercial software**

> Commercial software, or less commonly, payware, is computer software that is produced for sale or that serves commercial purposes.

This is the good ol' paying license, still a very strong proposition and the basis of most of the mainstream video games middleware. You're probably not in a position of offering only that, as you need a very strong and proven product to convince clients to pay directly for it.

*Examples: Unreal Engine, Autodesk Scaleform, Havok Physics.*

**Freeware, Shareware**

> Freeware is software that is available for use at no cost or for an optional fee, but usually with one or more restricted usage rights.
>
> Shareware is software that is provided to users without payment on a trial basis and is often limited by any combination of functionality, availability (it may be functional for a limited time period only), or convenience.

Here you're basically giving away licenses for free. This can be to gain some attention for a "pro version" with extended features that is released under a commercial license (i.e. costs money). It can also be that the license is granted against a royalty share on commercialized games.

*Examples: Unity, UDK, GameMaker.*

## Other options

Now if you want to try out some alternatives to the software-as-a-product strategy, you have plenty of options. Those might fit more with open source software, but once again, not necessarily.

**Freemium**, **Donationware**, **Pay what you want**

Those are all variants of the traditional fixed price model. Licenses will be free or almost free, and you'll be try to get a variable amount of money from generous donators, or from micro-transactions (e.g. plugins app store?)

This isn't something commonly used in games middleware, but maybe that's a model to try.

*Example: Humble Indie Bundle.*

**Crowd funding**

> Crowd funding describes the collective effort of individuals who network and pool their resources, usually via the Internet, to support efforts initiated by other people or organizations. Crowd funding is used in support of a wide variety of activities, including (...) free software development.

Kickstarter and similar are all the hype at the moment, as you stated yourself you could try taking advantage of that, but be aware that this isn't an easy path to follow.

*Examples: OUYA, Occulus Rift (not middleware, but game-related).*

**Charge for support**

This might be a good option. Release your engine & framework as freeware or even free software, and charge for advice or troubleshooting.

*Example: Torus Knot Software for the Ogre project.*

---

## Conclusion

Pick the option (or a mix of options) you feel will work for you, this really is a bet and the final choice is entirely up to you. The "right" choice depends on your expectations in terms of audience, revenue, personal tastes...

> Do I need to hire a lawyer to get some sort of legal document to protect my work?

If you're really serious about all this, yes, this is probably a good idea to seek for proper legal advice. IANAL, as they say.

# Answer
> 6 votes
Engine without support is nothing. You should sell license for your engine with support. You should expect that you will help people to make game with your engine.

There are many open source, free, etc engines and code samples. It is hard to select one.

You should build community around your engine. It is not simple even if engine is free.

If people will make great games with your engine and they will make money then they would be ready to share profits.

Or you should show how easy and fast they can build something.

There is no sense to obfuscate. It is very easy to decompile flash. Even top facebook games are decompilable.

# Answer
> 3 votes
I have no experience, but I imagine there's only one good solution in your case:

1. Obfuscate, in my experience Kindi's Protect SWF works best (actually obfuscates, I'm able to obfuscate most complex of my projects without errors)
2. Don't aim in crowds. Even if you obfuscate or compile your framework, the more unreliable clients you have, the bigger probability it will get pirated. If it get pirated, it gets popular, if it gets popular, serious clients won't be interested - they want their game to be rare, with fresh mechanism.
3. Aim in "whales". If you can advertise your product as professional, deluxe, then maybe you can get some serious clients. This should lower the risk of pirating your framework, both because the clients are serious and have face to lose, and because they're not many. Also the prices get really high, there are companies like Warner Bros advertising their new movies with games, or banks that like to spend a lot of money for a low quality ad (at least from my friends experience in working with banks). You can even get a regular income for technical support (especially if you don't giveaway your sources).
4. Change your code slightly for every client, and put high fees for product leaking in your contracts. I have no idea if companies will agree on such terms, though.
5. When "whales" are no longer interested in your framework, make it free, paid only for commercial use. Developers may start to create amateur games, but when (if) they start to profit, you can push them and they will rather pay you, than create a new game from scratch. Unless you would want a monthly profit share from them, that could be quite demotivating.

Edit: In description of your bounty you said you want to earn money in similar way that FlashDevelop does. Flashdevelop is an opensource project under MIT license. Simply giveaway everything you have, not obfuscated; if people like it, they will donate, both to thank you and support the framework they use. I would be glad to both use and contribute to your project.

But maybe you want something more similar to Greensock license instead.

Edit2: Also, to fight piracy, I suggest registering some keywords on Google Alerts, as well as searching manually on some warez sites yourself (because as far as I know, currently Google's bots don't visit thepiratebay.org)

---
Tags: game-industry, copyright, licensing
---


title: Embed IF text parser in another game?

text:
# Question
Title: Embed IF text parser in another game?
Are there any existing interactive fiction text parsing engines that I can embed in another game or application?

I'm looking to use something as a library. I can pass it the available objects and verbs from my own side. It will parse the sentences from the user and give me back some sort of structure/AST describing what the user asked for. Then my own code can then act upon that request.

I don't need something SIRI level. The simple sentences and actions that current IF games support is fine. But I'm not looking to write a whole text/sentence parser myself.

This isn't an If game and I can't write it entirely in an interactive-fiction language like inform 7. Unfortunatly, I can't seem to find any examples of anyone using the text parsing capabilities of these engines without writing the entire game in that engine's language.

# Answer
> 4 votes
This is a tricky question. It's possible to extract the text parsing functionality from one of a number of IF engines written in general-purpose programming languages (i.e. not something like Inform). Some possibilities might be Pyf, and the Aunt and Butler's engine. If you expand your search to muds you'll have an order of magnitude more choices (here are lists of open source muds and Python muds specifically).

However the tricky part, and from your question you understand this, is resolving the parse in the context of the game world. This is the hard part, and something like OpenNLP won't get you there unfortunately. The problem is that these IF engines and muds each have their own way of doing that and it may be difficult to reconcile with how you're designed your world model.

Luckily there are many resources to writing an effective parser and resolver. I'm just going to throw some links at you,

http://www.mudbytes.net/topic-1838

http://www.mudbytes.net/topic-2962

http://www.mudbytes.net/topic-2038

http://www.mud.co.uk/richard/commpars.htm

http://groups.google.com/group/rec.arts.int-fiction/msg/f545963efb72ec7b?dmode=source

http://www.intfiction.org/forum/viewtopic.php?f=38&t=4205#p30260

http://www.tads.org/t3doc/doc/libref/source/parser.t.html

http://www.tads.org/t2doc/doc/prsseq.htm

http://www.dnd.utwente.nl/~krimud/Docs/NMAdmin/Parser/

https://groups.google.com/forum/?fromgroups#!searchin/rec.arts.int-fiction/writing$20a$20parser/rec.arts.int-fiction/VpsWZdWRnlA/2mf5y25xk7MJ

https://groups.google.com/forum/?fromgroups#!searchin/rec.arts.int-fiction/writing$20a$20parser/rec.arts.int-fiction/EfxdLAc5Tmo/Fn5CEQvZCGsJ

http://ifwiki.org/index.php/Past\_raif\_topics:\_Development:\_part\_2#Parsing

https://groups.google.com/forum/?fromgroups#!topic/rec.arts.int-fiction/HJPrqQ8l9u0

http://www.kotancode.com/2012/02/15/scalamud-scala-java-nlp/

https://groups.google.com/forum/?fromgroups#!topic/rec.arts.int-fiction/to4Ut4r\_qCs

http://effbot.org/zone/simple-top-down-parsing.htm

http://www.skotos.net/articles/dawnof09.shtml

http://www.skotos.net/articles/dawnof22.shtml

http://discworld.starturtle.net/lpc/playing/documentation.c?path=/concepts/parser

http://disinterest.org/resource/MUD-Dev/1999q2/010160.html

# Answer
> 1 votes
Would this be useful to your project? I believe what you are asking for is NLP and IF is just a specific use case.

http://opennlp.apache.org/

Well, if you wish to check that the correct combination of a noun and a verb was found in the sentence and not so much about structure, grammar and other aspects:

I suggest downloading this http://wordnet.princeton.edu/wordnet/

You could use it to basically check if a synonym exists for both the verb and the noun you are looking for in a sentence without having to manually type in all the viable synonyms for each word.

If you wish to see text adventure game source code that was recently released, you could find some games here (just hit Ctrl + F) and type text

http://en.wikipedia.org/wiki/List\_of\_open-source\_video\_games

There is also a list of Text Adventure game engines here:

http://en.wikipedia.org/wiki/Category:Text\_adventure\_game\_engines

If you require something more, please elaborate.

---
Tags: text-based, interactive-fiction
---


title: Is OpenGL 1.x deprecated?

text:
# Question
Title: Is OpenGL 1.x deprecated?
I'm familiar with OpenGL 1.x. I typically use SDL with OpenGL 1.4 on Linux, and I've never run into problems, even on my modern system.

I've read on the OpenGL site about deprecation and compatibility contexts, but I'm still unclear as to whether it's safe to continue to use old *versions* of OpenGL, as opposed to using old *features* in newer versions.

> When functionality is marked deprecated ... future versions of OpenGL may remove it.

Does deprecation simply imply that those functions can't be used alongside newer features?

More specifically, are there any systems today (other than embedded) where OpenGL 1.x isn't available? The old-skool stuff like, `glBegin`, `glEnd`, `glDrawPixels`, etc.

Note: I'm not a professional games developer, so you'll have to excuse my ignorance. I'm working on a mostly 2D game that I would like to keep multi-platform, supporting at least Linux, Mac, and Windows.

# Answer
> 7 votes
First of all you need to establish the split between desktop GL and mobile GL. Mobile GL (OpenGL ES) is in fact quite a different animal; it has a separate specification, different levels of functionality, different versioning, and can better be viewed as a separate API that is modelled after desktop GL, shares similar naming, but is just not the same thing. That's going to have implications for your plans to go multiplatform beyond the "big 3" in the desktop space.

For the purposes of discussing deprecation in desktop GL, OpenGL ES is irrelevant.

In desktop GL deprecation is complex and not fully implemented (if at all) by any GPU vendor. NVIDIA have publicly stated that they have no intention of removing anything at all.

In summary though, the deprecation model is chosen at context creation time and essentially boils down to one of two choices: a "core context" (i.e. one with all of the deprecated functionality removed) or some other form of context that still implements the deprecated functionality.

If you want a core context you must explicitly ask for one, otherwise you still get all of the old stuff. I *believe* that OSX is however different here and will *only* give you a core context, but don't quote me on that (**edit** \- confirmed; see comment below).

The older (deprecated) functionality may or may not coexist cleanly with newer GL functionality; in some cases it makes absolutely no sense whatsoever (VAOs with glBegin/glEnd calls are nonsensical; that should be obvious to all), in some cases it just won't work (a modern shader requires generic attribs but you can't provide them unless you use the generic attrib calls), in others it just continues to work fine.

What all of that means is that if you want to mix-and-match functionality you need to get down and start reading the documentation, figure what works and what doesn't, and make decisions about what you can keep and what you need to change. That's *if* you want to mix-and-match; if not, then you can just continue as you are and everything should still work.

Fortunately there are some easy migration paths available. You can for example use glVertexAttrib3f instead of glVertex3f (and friends) and begin using generic attribs in modern shaders right now, while retaining your old glBegin/glEnd style code. From the other side, you can migrate your glBegin/glEnd code to vertex arrays (glVertexPointer and friends) without having to cope with the additional upset of also needing to implement shaders and generic attribs all at once.

In other words making the move can be quite a pain-free experience since you only need to change one thing at a time (and have only one place to go looking for problems if you break anything).

OK, so I've digressed a little from the specific question in the last part there, but I believe that it's relevant given your cross-platform ambitions and given the more limited functionality provided by OpenGL ES.

# Answer
> 2 votes
WebGL and embedded are both based on OpenGL 2 and don't support any of the immediate-mode or fixed-pipeline OpenGL 1.4 operations. So you can forget anything on mobile - those vendors are not likely to add obsolete OpenGL support.

On desktops, I doubt very much whether OGL 1.4 is going to disappear, but you should probably not use it for new work.

In general you will want to use a higher level library to do useful stuff, which will make the OpenGL 2 / OpenGL ES stuff essentially transparent, you won't notice it at all.

---
Tags: opengl
---