title: Best practices of texture size

text:
# Question
Title: Best practices of texture size
I wanted to know how should I determine a good texture size ? Currently, I always create UV texture that are 1024x1024px but if I create for example, a big house with a 1024px texture size, it will looks pretty bad.

So, should I create different texture size (512, 1024, ...) for different mesh size like this ? :

or is it better to always do high-resolution texture and then reduce it in the software (ie : increase the LODBias settings in UDK reduce the size of the texture) ?

Thanks for your answer.

ps : sorry for my english !

# Answer
One way to choose texture sizes is to have a target texel density relative to the size of an object. For instance, if you wanted 128 texels per meter, then an object 4 meters in size should have a 512x512 texture, an object 8 meters in size should have a 1024x1024 texture, etc. The same guideline can be applied to tiling textures as well.

Another thing to take into account is how close the camera can get to a particular object. If the camera can get very close, for example to a character, you would want a higher texel density. A character might only be 2 meters tall but you would probably want a lot more than 256x256 for her textures. Conversely, a mountain in the distance will never be seen up close, so it doesn't need a very high texel density.

> is it better to always do high-resolution texture and then reduce it in the software (ie : increase the LODBias settings in UDK...)

I wouldn't use LOD bias settings to reduce textures. If you do that, you're still paying for the cost of the high-res texture in memory and loading time. Instead, reduce the texture in a preprocess, and only load the smaller version of it. It's still good to author the original textures at a high resolution so you have the extra detail in case you need it later.
> 21 votes

---
Tags: 3d, textures, udk
---


# Question
Title: Physics Loop in a NodeJS/Socket.IO Environment
I'm developing a 2D HTML5 Canvas Game, and I am trying to think of the most efficient way to implement a Physics Loop on the server-end of things, running NodeJS and Socket.IO.

The only method I've thought of is using `setTimeout/Interval`, is there any better way? Any examples would be appreciated.

EDIT: The Game is a top-down Game, like Zelda and older Pokemon Games. Most of the physics done in the loop will be simple intersects.

# Answer
I believe `setTimeout` is good enough for your needs. I am, myself, facing a similar situation and I am going with `setTimeout`. This awesome article on **BNG** helped me better understand what a I have to do (or, at least, try): Real Time Multiplayer in HTML5.

About the link: It talks mostly about the multiple game loops and networking them. It's pretty cool. Below, an excerpt.

> When it comes to a real time game, we want to run the game logic itself on the server AND the client. This is due to the fact that the server needs to be the authority on the state of the game at all times, but the client needs to run the game locally too. Each frame on the server, input from the network will be processed and applied to players, and that change is sent to the other players at a fixed rate. On the client, input will be collected and sent to the server, and positions can be updated while waiting for the messages to come back from the server (client prediction).

It's a highly recommended read. At least by me. =P
> 6 votes

# Answer
For server-side stuff you have a couple of options. The first is to entirely extrapolate all your collisions working off of the assumption that you will have frequent-enough messages from clients, communicating all meaningful state change through the server, which then will run validation on game events only as it receives IO callbacks from the client connections.

The second way, which you seem to prefer, is to run your own loop while whilst you process IO callbacks. Although setInterval and setTimeout will accomplish this, you have a much more fine-grained set of tools to control this: `setImmediate(callbacks, [[arg], ...])` and `process.nextTick(callback)`.

Process.nextTick will run your callback before other IO events, so long as you haven't stacked up a recursively infinite stack of callbacks (if it exceeds a certain number, process.maxTickDepth, then it will yield to the IO callbacks).

SetImmediateCallback is similar to process.nextTick in that it acts every tick, but only one of the queued callbacks gets executed on every tick, rather than all queued callbacks.

Using these will look similar to setTimeout or requestAnimationFrame.

```
function gameLoop() {
  updateCollisions();
  process.nextTick(gameLoop);
}

process.nextTick(gameLoop);

```

The advantage of these is that you're not dependent on V8's implementation of setTimeout and setInterval. These are more of a direct line to Node's event loop. Just be sure you don't starve the IO if you are using process.nextTick. updateCollisions should be guaranteed to not take that long at all.
> 2 votes

---
Tags: node.js
---


title: Advantages and disadvantages of libgdx

text:
# Question
Title: Advantages and disadvantages of libgdx
I've been an android developer for a while and am thinking about getting into gaming. While looking for a game dev framework, I thought libgdx provides very friendly documentation and functionality. So I would like to use it if there is no big obstacle.

But when I tried to see how many developers employ this library, I could find not that many. Is there anything wrong with this library? In other words, I would like to know its advantages or disadvantages from any experienced developer.

UPDATE: After reviewing its documentations and trying to build simple games with libgdx, I decided to go with it as its documentations are good enough and its community is very active. What I liked the most is that it provides a bunch of demo games that I can learn a lot from.

# Answer
I decided to go with libGDX for similar reasons. To expound on my comment, I will mention what I find are the pros and cons.

Pros:

* Works on Android and desktop (no need for emulator)
* Active user community on forums
* Lots of robust functionality
* Works on iOS too (via RoboVM =\> free)

Cons:

* Lack of documentation and information
* Quite low-level (I prefer writing less code to get things done)

All in all, if you're sticking to just Android, it's great. But if you want to do iOS too, I would move to something else, like Unity or Corona SDK.
> 10 votes

# Answer
I just started in libgdx (i have 2 weeks developing there).

The pros, its that you dont need the emulator and you can test everything you do in the real speed, also if you know Java it would be easy (i know Android apps uses Java, but this is more easy, in my point of view), the architecture of libgdx for the game development is too well built.

The Disadvantage is the lack of documentation as all the people say, there are sample codes but it doesnt implement all libgdx so its no complete, and there are some methods that doesnt have documentation and you have to test it yourself and know how does it work :/

Its a good library, its easy to use but you have to google it a lot if you want to use at 100%
> 7 votes

# Answer
I'm the author of the book "Learning Libgdx Game Development".

This book might fill the gap of lacking documentation and aggregated information for beginners.

I've already posted more over here: Where are all the tutorials for libGDX?
> 3 votes

---
Tags: android, libgdx
---


# Question
Title: Homemaking a 2d soft body physics engine
hey so I've decided to Code my own 2D soft-body physics engine in C++ since apparently none exist and I'm starting only with a general idea/understanding on how physics work and could be simulated:

**by giving points and connections between points properties such as elasticity, density, mass, shape retention, friction, stickiness, etc.**

**What I want is a starting point**: resources and helpful examples/sites that could give me the specifics needed to actually make this such as equations and required physics knowledge. It would be great if anyone out there also would give me their attempts or ideas.

finally I was wondering if it was possible to...

* use the source code of an existing **3D** engine such as Bullet and transform it to be **2D** based?
* use the source code of a 2D **Rigid body** physics engine such as box2d as a starting point?

# Answer
> 2 votes
No softbody solvers in C++ exist?

https://stackoverflow.com/questions/3269212/non-rigid-body-2d-physics-engines-in-c

# Answer
> 0 votes
You should start with the basics of tensors. A soft body is but an instance of a continuous environment. So, each point is subbject to a deformation matrix, depending on the local tension, such as traction, pressure, and shearing. It's a complex matter. For the computational cost is to be insured at each phisical itteration. It's makeable, but should be made by a powerful processor in real time. by the way, I'm working on such a project, but I sheat on the physics. My feature is a round bactery subject to a reduced gravyity. So I emulate the deformations with morphing, shearing matrixes and scaling. The algoritmics is way harder, but it runs alright on an I5 with 1M RAM graphic card. The art of video game is illusion, not a real simulation.

But if you provide an open source soft body engine, you would make me way happier :-)

http://en.wikipedia.org/wiki/Continuum\_mechanics

# Answer
> -1 votes
You should start with the basics of tensors. A soft body is but an instance of a continuous environment. So, each point is subbject to a deformation matrix, depending on the local tension, such as traction, pressure, and shearing. It's a complex matter. For the computational cost is to be insured at each phisical itteration. It's makeable, but should be made by a powerful processor in real time. by the way, I'm working on such a project, but I sheat on the physics. My feature is a round bactery subject to a reduced gravyity. So I emulate the deformations with morphing, shearing matrixes and scaling. The algoritmics is way harder, but it runs alright on an I5 with 1M RAM graphic card. The art of video game is illusion, not a real simulation.

But if you provide an open source soft body engine, you would make me way happier :-)

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


# Question
Title: iOS Game that Runs Continuously in Background
I'm trying to understand the most logical way of creating an iOS game that runs continuously in the background.

For example.. you have tower and enemy waves. The game has endless enemy waves even when the game exits. When you open the game again, it will retrieve the data that occurred when the app was closed.

I assume a database on a server would be the best solution. The values continuously increment on the server. The game connects to the server and retrieves the specific user's updated game data.

# Answer
If the enemy waves only effect one player (the one that plays the game), then I really see no need to put this logic on an external server. Having a server would also require an internet connection which can't be taken for granted (especially on iPods and iPads).

You could simply store the time when your game exits or goes to the background. Upon relaunch get the time that passed and fast-forward your game by that time-amount. Of course you need to implement your game in a way that will allow you to run the simulation at a much higher speeds so that the user doesn't have to wait for ages until your simulation is up to speed.
> 4 votes

---
Tags: c++, c#, ios, iphone, cocos2d-iphone
---


# Question
Title: Correct order of tasks in each frame for a Physics simulation
I'm playing a bit around with 2D physics. I created now some physic blocks which should collide with each other. This works fine "mostly" but sometimes one of the blocks does not react to a collision and i think that's because of my order of tasks done in each frame.

At the moment it looks something like this:

```
function GameFrame(){
    foreach physicObject do
        AddVelocityToPosition();

        DoCollisionStuff();      // Only for this object not to forget!

        AddGravitationToVelocity();
    end

    RedrawScene();
}

```

Is this the correct order of tasks in each frame?

# Answer
> 5 votes
A simple flow, based on experimentation and intuition/common sense:

This simply means:

* integrate the acceleration and velocity from the current step to recover the predicted, next step position and velocity
* perform collision queries and derive any penalty impulses, forces, friction or whatever
* resolve the collisions in terms of positions (projected iterations to move the bodies iteratively out of conflicting poses)
* feed the penalty response (impulse and force) back to the integrator to use at the next step
* now you can use the output pos and velocities as they're corrected and updated/in synch.

---
Tags: physics, architecture
---


# Question
Title: How to use multiple textures in OpenGL ES 2.0?
I am working in OpenGL ES 2.0.

I load two png images as my textures with the libSOIL. I need to use one of them as the texture for the background and another one as the texture of a rotating cube.

In OpenGL ES 2.0, the adding texture operation is in the shader. I don't know how to add the different textures to the different places in a shader. How do I do that?

# Answer
> 3 votes
Simplest way is multiple draw calls.

> In OpenGL ES 2.0, the adding texture operation is in the shader

Not really. How does shaders know where to take texture pixels? You must bind texture outside shader too.

Basic algorithm for drawing multiple objects is:

```
for(each object obj)
{
    SetPipelineState(obj);
    Draw(obj);
}

```

In your case:

```
void RenderFrame()
{
    ClearBackBuffer();
    ClearDepthBuffer();

    // Draw cube
    glUseProgram(programForCube);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textureOfCube);  // Texture for cube
    glBindBuffer(...) // Vertex buffer for cube
    // other states go here
    Draw(...);

    // Draw background
    glUseProgram(programForBackground);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textureOfBackground); // Texture for background
    glBindBuffer(...) // Vertex buffer for background
    // other states go here
    Draw(...);
}

```

Don't forget to set up depth state and depth buffer.

There are advanced techniques to reduce draw calls number.

Even better and more general solution will be to google up complete OpenGL tutorial course. There are plenty on the web.

---
Tags: textures, opengl-es2
---


# Question
Title: How does a game developer get feedback from gamers (not developers) or start a forum community without paying for advertising or hiring Q&A teams?
I am familiar with a lot of game developer forums, but I'd assume this is much less likely to attract more casual commentators. I also fear that feedback from a gamer's perspective would often be tainted by their game dev perspective.

For example, if I were making a RTS game and wanted to get feedback from "The RTS gamers" where would I go? Is there a general idea of what type of website or forum to go to? Do you go to specific game websites, to try to "steal" attention? Would this not equate to spam or inappropriate posting? What is considered appropriate and inappropriate?

I am not asking for specifics. I am asking how one "starts a community", or how one "gets feedback from gamers" without resorting to spamming forums or 'advertising' just to see what sticks. What TYPE OF PLACE does one go? Are there already sites designed for this purpose?

I tried going to what was once a very popular forum for feedback from what I believed was a niche hardcore group of gamers in the genre, but its popularity seemed to have died significantly; Leaving only trolls and very young teenagers. The resulting feedback was quite disappointing, mainly for how little feedback it resulted. Many years ago, feedback would flood in by the hundreds so quickly.

Without this website, I am at a loss as to where to go to see what people think of ideas, gather feedback from a gamer's perspective (not a developer's perspective), or where to pull from to start my own site's forum. I am out of ideas of what to do, short of going to various game forums to post in the off-topic sections there.

# Answer
> What TYPE OF PLACE does one go?

**Forums or social media sites**. There are already sites designed for that purpose.

The type of places you want to go are the ones where these gamers are. Search the web for similar indie RTS games. Find out where people are talking about those games and start with that community. Don't spam. Just partake in the discussions, and inject your own questions when appropriate.

Without paying for anything your options are limited. But, if you're allowing people to play your game for free, you'll likely get feedback from those willing to play. Ensure the players have a place to respond, and ask them to share their thoughts. There are a number of free blogging sites, a Facebook page, Twitter, etc.
> 3 votes

---
Tags: game-design, social, community-management
---


# Question
Title: What light attenuation function does UDK use?
I'm a big fan of the light attenuation in UDK. Traditionally I've always used the constant-linear-quadratic falloff function to control how "soft" the falloff is, which gives three values to play with. In UDK you can get similar results, but you only need to tweak one value: FalloffExponent.

I'm interested in what the actual mathematical function here is. The UDK lighting reference describes it as follows:

> FalloffExponent: This allows you to modify the falloff of a light. The default falloff is 2. The smaller the number, the sharper the falloff and the more the brightness is maintained until the radius is reached.

Does anyone know what it's doing behind the scenes?

# Answer
The default equation for attenuation

> f(x) = 1/( distance ^(exponent) )

from the images doesn't seem UDK is doing anything differently.
> 6 votes

---
Tags: hlsl, udk, lighting
---


# Question
Title: How do I detect collision with isometric walls?
I will use game called "Project Zomboid" as an example. Here is a pic how does it look \>

How should I handle player's collision with walls constructed like that? It's easy to handle walkable and not walkable tiles for player, but this is different and I have no ideas how to solve this problem. Any tips?

# Answer
Store flags for the edges of tiles, not the whole tiles. For instance, the "Southeast Wall" tile might have the flags `SouthWall` and `EastWall` set. When doing collision tests, check the boundaries you're crossing, not the whole tile.

Alternatively, for even more flexibility, store both tiles (floors) and the boundaries/walls in separate or interleaved arrays. If interleaved, you'd have walls/boundaries in the even spaces (0, 2, 4, 6, etc.) and tiles in the odd spaces (1, 3, etc.) with every map being an even size (every tile is surrounded by boundaries). This works if your tiles and boundaries are roughly the same in terms of data. Separate structures works just fine, too. The advantage to this approach is that you can have tile/floor data separate from wall data and each wall is its own entry, so you can more easily mix-and-match walls and floors.

A further simplification is to still have tiles, with each tile now have two wall fields, say upper-left and upper-right (the other two sides are the walls from the tiles below).

This approach has been used in some non-isometric 3D tile-based games as well (think Dungeon Master, Grimrock, Stonekeep, etc.) that wanted to encode data in the walls in addition to data in the floors, e.g. to have a cubby in the north wall and a separate cubby in the east wall but no cubby and walkable floor on the other side of the walls.
> 4 votes

---
Tags: collision-detection, isometric
---


# Question
Title: How can I determine where objects can be seen from a given perspective?
I'm wrapping my head around OpenGL ES 2.0 and I think I'm trying to do something very simple, but I think the math may be eluding me.

I created a simple, flat-ish cylinder in Blender that is 2 units in diameter. I want to create an arbitrary grid of these edge to edge (think of a checker board).

I'm using a 3D perspective with GLKit:

```
    CGSize size = [[self view] bounds].size;
    _projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(45.0f), size.width/size.height, 0.1f, 100.0f);

```

So, I managed to manually get all of these cylinders drawn on the screen just fine. However, I would like to understand how I can programmatically "fit" all of these cylinders on the screen at the same time given the camera location, screen size, cylinder diameter, and the number of rows/columns.

So the net effect is that for small grids (i.e., 5x5) the objects are closer to the camera, but for large grids (i.e., 30x30) the objects are farther away. In either case, all of the cylinders are visible.

# Answer
> 1 votes
There are two ways in which your scene (a grid of cylinders) will outgrow your view port.

* It can extend beyond the vertical field of view.
* It can extend beyond the horizontal field of view.

Which one happens first (or is the most restrictive) will depend on:

* window aspect ratio.
* camera field of view.
* ratio of grid dimensions.
* camera tilt (45 deg in your case.)

If you can make a basic assumption that it will always be the horizontal field-of-view that gets transgressed first, you can skip determining this.

Let's assume we will fit for width (or horizontal field of view.) The relationship between distance-to-camera and appearant-size is a very simple one: linear.

Camera twice as far, means the object will cover half as much of the viewport. The camera needs to be at a distance equal to the width of the grid multiplied by some constant value.

So why not simply set the camera at a distance MAX(C1\*w, C2\*h) from the front row of cylinders?

With w=grid width, h=grid-height, C1 and C2 are empirically determined constants.

Note: C2 will no longer be a fixed constant if you start varying the camera tilt. In that case, you will need a sin(tilt-angle) component in there.

---
Tags: opengl-es2
---


# Question
Title: Incorrect lighting results with deferred rendering
I am trying to render a light-pass to a texture which I will later apply on the scene. But I seem to calculate the light position wrong. I am working on view-space.

In the image above, I am outputting the attenuation of a point light which is currently covering the whole screen. The light is at 0,10,0 position, and I transform it to view-space first:

```
Vector4 pos;
Vector4 tmp = new Vector4 (light.Position, 1);
// Transform light position for shader
Vector4.Transform (ref tmp, ref Camera.ViewMatrix, out pos);
shader.SendUniform ("LightViewPosition", ref pos);

```

Now to me that does not look as it should. What I think it should look like is that the white area should be on the center of the scene. The camera is at the corner of the scene, and it seems as if the light would move along with the camera.

Here's the fragment shader code:

```
void main(){

    // default black color
    vec3 color = vec3(0);

    // Pixel coordinates on screen without depth
    vec2 PixelCoordinates = gl_FragCoord.xy / ScreenSize;

    // Get pixel position using depth from texture
    vec4 depthtexel = texture( DepthTexture, PixelCoordinates );
    float depthSample = unpack_depth(depthtexel);

    // Get pixel coordinates on camera-space by multiplying the
    // coordinate on screen-space by inverse projection matrix
    vec4 world = (ImP * RemapMatrix * vec4(PixelCoordinates, depthSample, 1.0));

    // Undo the perspective calculations
    vec3 pixelPosition = (world.xyz / world.w) * 3;

    // How far the light should reach from it's point of origin
    float lightReach = LightColor.a / 2;

    // Vector in between light and pixel
    vec3 lightDir = (LightViewPosition.xyz - pixelPosition);
    float lightDistance = length(lightDir);
    vec3 lightDirN = normalize(lightDir);

    // Discard pixels too far from light source
    //if(lightReach < lightDistance) discard;

    // Get normal from texture
    vec3 normal = normalize((texture( NormalTexture, PixelCoordinates ).xyz * 2) - 1);

    // Half vector between the light direction and eye, used for specular component
    vec3 halfVector = normalize(lightDirN + normalize(-pixelPosition));

    // Dot product of normal and light direction
    float NdotL = dot(normal, lightDirN);

    float attenuation = pow(lightReach / lightDistance, LightFalloff);

    // If pixel is lit by the light
    if(NdotL > 0) {

        // I have moved stuff from here to above so I can debug them.

        // Diffuse light color
        color += LightColor.rgb * NdotL * attenuation;

        // Specular light color
        color += LightColor.xyz * pow(max(dot(halfVector, normal), 0.0), 4.0) * attenuation;

    }

    RT0 = vec4(color, 1);

    //RT0 = vec4(pixelPosition, 1);
    //RT0 = vec4(depthSample, depthSample, depthSample, 1);
    //RT0 = vec4(NdotL, NdotL, NdotL, 1);
    RT0 = vec4(attenuation, attenuation, attenuation, 1);
    //RT0 = vec4(lightReach, lightReach, lightReach, 1);
    //RT0 = depthtexel;
    //RT0 = 100 / vec4(lightDistance, lightDistance, lightDistance, 1);
    //RT0 = vec4(lightDirN, 1);
    //RT0 = vec4(halfVector, 1);
    //RT0 = vec4(LightColor.xyz,1);
    //RT0 = vec4(LightViewPosition.xyz/100, 1);
    //RT0 = vec4(LightPosition.xyz, 1);
    //RT0 = vec4(normal,1);
}

```

What am I doing wrong here?

# Answer
> 1 votes
How stupid of me. Problem was here:

```
vec3 pixelPosition = (world.xyz / world.w) * 3;

```

What I was previously doing with that, I was experimenting as I seemed to have wrong pixel coordinates in view space. This is correct:

```
vec3 pixelPosition = (world.xyz / world.w);

```

---
Tags: glsl, lighting, opentk
---


title: HTML5 without a framework

text:
# Question
Title: HTML5 without a framework
I am looking to get into game development, after a lot of searching I have decided to try with html5 and, while I can see the advantages of frameworks, I would like to learn the basics without a "crutch".

Is it realistic to even try and start learning game development without using a framework? Also, if I decide to use one, what should I consider when deciding on one?

# Answer
> 10 votes
I think you're making a mistake thinking of a framework as a crutch. Surely when you want to build your own computer, you don't make all your own circuit boards? Mine and smelt the copper yourself?

Frameworks are not crutches. They're tools that make your job much easier. If you truly want to want to get into game development, you'll want to use frameworks. Otherwise you'll be getting into framework development (maybe someday you'll get to making games).

When deciding on a framework to use, you only need make a few lists. The first list is what kind of functionality you'll need to complete your game. The remaining lists are one for each framework you're considering. Each of those lists should be filled with the functionality that that framework provides. Once you have a set of framework lists whose items fulfills your requirements list, you have a set of frameworks to use.

# Answer
> 4 votes
I began in early 2010 using just Box2D.js (optional) + Canvas -- you can play around and start to get a feel for the sort of headaches a framework would ultimately spare you. You can also get a better grip on JS fundamentals, and HTML5 fundamentals and pitfalls (e.g. what parts of the standard *aren't* implemented yet).

If you're more content using traditional OOP for building games, it's also a good time to learn to replicate that structure in JS, building your own architecture up from scratch without any frameworks getting in your way. This is an excellent question explaining why keyword `new` works well for instantiating objects, rather than the manual cloning that many gravitate toward in JS.

Under no circumstances would I suggest *not* using jQuery, even if it's just for managing your viewport (but you will always end up using it for much more than that). Then again, jQuery's not so much a framework as a cross-browser toolset.

# Answer
> 3 votes
I would argue that it depends on your immediate goals. A framework might be helpful, or it might be an extra layer of complexity over the extremely simple canvas API.

### Helpful

1. A 2d physics simulation
2. An efficient particle system
3. A scene graph full of objects that "know" where they are.

If you want these features, you need a framework. They aren't present in the canvas API.

### Not helpful

When I say not helpful, I mean that it may not provide much advantage over simply using the built-in canvas methods. For example, if you want to draw something onto the screen:

```
canvasContext.drawImage(imageElement, positionX, positionY);

```

Or a make a game loop:

```
window.requestAnimationFrame(function(){ // do loop code});

```

Naturally, these can get more complex as you require more details. But it is not automatically true that the framework will require fewer lines of code or simpler method calls. The canvas API is already pretty simple; a framework will incur some overhead.

A framework will have its own learning curve. You'll need to spend some time reading up, probably following a tutorial. The deciding question is, will you be up and running faster by reading those docs rather than reading this framework-less canvas tutorial?

A framework may only wrap up more powerful features in a cohesive interface. If you are extremely green to game development, that "simpler" interface won't be any benefit if you don't understand what it does for you. Maybe it will provide a translation and a rotation and a unique coordinate system per sprite...but do you need that?

I would say that at their worst, frameworks will cheat you of some of those small details of understanding. That's hardly a reason to avoid them (you'll learn the details anyway), but learning some fundamentals the hard way also has merit.

# Answer
> 3 votes
Every Framework is an abstractions. And as Joel Spolsky has mentioned that every abstraction in Computer Science is a leaky abstraction. What this means is that which ever framework you pick up, there would some form of limitations. And one would have to understand these limitation before stressing those framework. Understanding of these limitations demands lots of reading, experience and design knowledge.

To answer your question, if you are planning to learn HTML5 then its preferable to go with the basics without framework. If you are looking to make a production ready app, then i would ask you to research on frameworks and pick one to get your hand dirty while learning HTML5. This way you would realize some of the limitations of that particular framework.

---
Tags: html5
---


# Question
Title: How can I set a system's emission rate using Particle Designer 2.0?
In cocos2d-iphone (2.1), `CCParticleSystem` has a property called `emissionRate`.

Is there any way to set it using Particle Designer 2.0? I've tried all the various settings but there doesn't seem to be anything achieving that effect. Perhaps I'm overlooking something?

# Answer
Emission rate is mainly a combination of Max Particles and their Lifespan.

If you change emissionRate in code and make it faster, what happens is that the emitter stops emitting particles for a while when it reaches "max particles" and will continue only when the "lifespan" of enough particles have reached so that the number of active particles falls below "max particles".
> 0 votes

---
Tags: iphone, cocos2d, particles
---


title: Polygon count budget

text:
# Question
Title: Polygon count budget
Is there any smart way to think about polygon budget relating to PC gaming today? My game will have one static 3d background scene and two fighters. No more enemies. I am thinking about having animated 3d models in the background for atmosphere, like spectators.

So how could i find out what the polygon count for the player models and background scenarios could be. I guess the question is, what is a for today typical polygon count that most PCs can handle?

# Answer
> What is a for today typical polygon count that most PCs can handle

I would say according to current generation consoles -ps3/xbox360- and not counting next-gen it's usually around 10k for the main characters which is reasonable taking into account quality/performance in the current gen. For enemies it's around 2k-5k, depending on how important they are. Given that PS3/XBOX 360 are 7 years old\** I can safely say *most* today's PCs can handle that.

### The problem though

Polygon count is a tangible number (and FPS per se) yet alone is not really an accurate or even good indication of the overall game performance. There is much more in your game than poly count; fillrate, draw batches, fragment shaders, rendering passes, culling..etc the best way is to profile your application and find your bottleneck. Real time rendering is a great book for different visual appearance and optimization techniques it even has a full chapter dedicated for pipeline optimization

\**I didn't take into account that PS3/XBOX 360 are optimized for rendering/games.

> I am thinking about having animated 3d models in the background for atmosphere, like spectators.

Well, depending on your game; but the question is, why use fully detailed 3D models while they may not really add much to the game because they are not actually at the very center? Most games don't use real 3D models for spectator look at Fifa for example, they use 2d images without losing much of the atmosphere.
> 1 votes

---
Tags: unity, 3d
---


# Question
Title: How to play many sounds at once in OpenAL
I'm developing an RTS game and I would like to add sounds to it. My choice has landed on OpenAL. I have plenty of units which from time to time make sounds: fSound.Play(sfx\_shoot, location). Sounds often repeat, e.g. when squad of archers shoots arrows, but they are not synced with each other.

My questions are:

* What is the common design pattern to play multiple sounds in OpenAL, when some of them are duplicate?
* What are the hardware limitations on sounds count and tricks to overcome them?

# Answer
For every sound you'll have a buffer. Multiple sources can reference the same buffer.

So for example you'd have a buffer that was loaded from 'archerShot.wav' and all the archers can reference this.

In terms of design patterns there's a variety of solutions. One is the Publisher/subscriber pattern (wikipedia). The individual game objects can contain a sound enumeration variable (that can represent a variety of sounds) which would be picked up by the sound system and played after every frame. The advantage of doing it this way is that the sound system is not coupled to the entities - just like how you can separate the rendering of an entity from its logic.

This link may be of use (a thread on gamedev.net forums).

Hardware Limitations: This is very dependant on your target hardware and I don't think there is a general answer. The iPad and iPhone can only play one compressed buffer at a time. If you allow the users to play their music on the device this means you can't rely on being able to play any compressed sound buffers.
> 3 votes

# Answer
I use a **Pool** pattern.

On iOS there is a maximum of 32 sound sources playing at one time. So at program start, I create 32 ALSources (the `ALSourcePool`), and when a new sound needs to play, it asks the Pool for a SoundSource to use.

If there are no free sources, one of the playing sources is stopped and that source is given to the caller.

Another level of management is to classify the pool into groups. Voice-over should never be *cut off* by an archer's bow being let, so I am going to designate, say sources 1-8 for "unit sfx", 8-12 for explosions ... and reserve sources 30-31 for *voice comments* (so in game voice notices are never overridden by any other sound).
> 3 votes

---
Tags: design-patterns, openal
---


title: Variable number of GUI Buttons

text:
# Question
Title: Variable number of GUI Buttons
I have a generic HTML5 Canvas GUI `Button` class and a `Scene` class. The `Scene` class has a method called `createButton()`, which will create a new `Button` with onclick parameter and store it in a list of buttons. I call `createButton()` for all UI buttons when initializing the `Scene`. Because buttons can appear and disappear very often during rendering, `Scene` would first deactivate all buttons (temporarily remove their onclick, onmouseover etc property) before each render frame. During rendering, the renderer would then activate the required buttons for that frame.

The problem is that part of the UI requires a **variable number of buttons**, and their **onclick, onmouseover etc properties change frequently**. An example is a buffs system. The UI will list all buffs as square sprites for the current unit selected, and mousing over each square will bring up a tooltip with some information on the buff. But the number of buffs is variable thus I won't know how many buttons to create at the start. What's the best way to solve this problem? P.S. My game is in Javascript, and I know I can use HTML buttons, but would like to make my game purely Canvas-based.

1. Create buttons on-the-fly during rendering. Thus I will only have buttons when I require them. After the render frame these buttons would be useless and removed.
2. Create a fixed set of buttons that I'm going to assume the number of buffs per unit won't exceed. During each render frame activate the buttons accordingly and set their onmouseover property.
3. Assign a button to each `Buff` instance. This sounds wrong as the buff button is a part of the GUI which can only have one unit selected. Assigning a button to every single `Buff` in the game seems to be overkill. Also, I would need to change the button's position every render frame since its order in the unit's list of buffs matter.
4. Any other solutions?

I'm actually quite for idea (1) but am worried about the memory/time issues of creating a `new Button()` object every render frame. But this is in Javascript where object creation is oh-so-common (`{}` mainly) due to automatic garbage collection. What is your take on this? Thanks!

# Answer
1) is roughly what many games do. You don't need to create whole new objects each frame, but rather recycle a pool of the objects. You don't even need a Button object at all. If your buttons are in the usual kind of placement in most UIs, you can calculate the rectangle extents programatically during rendering. You simply need a `DrawBuffButtons(list_of_buffs)` function that draws each button in order, placing it appropriately. Your canvas mouse handler, upon a click or movement, can use a basic math expression to determine which button's bounds are hovered/clicked and set an integer appropriately (e.g. `current_hover_index = index` or `use_buff(index)` as appropriate). Absolutely no need for data, objects, or any runtime data to be kept arround. This is more generally known as an *immediate mode GUI*. There are potential issues with it, but it works for most in-game HUD stuff I've worked with (main menus and complex inventory screens and the like are another story).

If you want objects, just use a pool. Note that a fixed number of buttons probably works - do you really want to encourage or support units with 1000 buff buttons the user has to muck around with? Figure out what fits on your UI. Limit the buffs to that number. Now, the first button selects the first buff, second button the second buff, etc. No need to ever change event bindings. As the selected unit changes you just set the button names and enable/disable according to number in use.

Note that both approaches allow a little more intelligence in your buffs such as separating the different types (attack vs defense, hot-keyed vs open list, etc.) for the creation of a better UI, which you should concentrate on before worrying about architecture or performance issues you might not even ever have.
> 0 votes

---
Tags: javascript, gui, control
---


# Question
Title: Understanding implementation of glu.PickMatrix()
I am working on an OpenGL project which requires object selection feature. I use OpenTK framework to do this; however OpenTK doesn't support glu.PickMatrix() method to define the picking region. I ended up googling its implementation and here is what i got:

```
    void GluPickMatrix(double x, double y, double deltax, double deltay, int[] viewport)
    {
        if (deltax <= 0 || deltay <= 0)
        {
            return;
        }

        GL.Translate((viewport[2] - 2 * (x - viewport[0])) / deltax, (viewport[3] - 2 * (y - viewport[1])) / deltay, 0);
        GL.Scale(viewport[2] / deltax, viewport[3] / deltay, 1.0);
    }

```

I totally fail to understand this piece of code. Moreover, this doesn't work with my following code sample:

```
    //selectbuffer
    private int[] _selectBuffer = new int[512];

    private void Init()
    {
        float[] triangleVertices = new float[] { 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f };
        float[] _triangleColors = new float[] { 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f };

        GL.GenBuffers(2, _vBO);
        GL.BindBuffer(BufferTarget.ArrayBuffer, _vBO[0]);
        GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(sizeof(float) * _triangleVertices.Length), _triangleVertices, BufferUsageHint.StaticDraw);
        GL.VertexPointer(3, VertexPointerType.Float, 0, 0);
        GL.BindBuffer(BufferTarget.ArrayBuffer, _vBO[1]);
        GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(sizeof(float) * _triangleColors.Length), _triangleColors, BufferUsageHint.StaticDraw);
        GL.ColorPointer(3, ColorPointerType.Float, 0, 0);
        GL.EnableClientState(ArrayCap.VertexArray);
        GL.EnableClientState(ArrayCap.ColorArray);

        //Selectbuffer set up
        GL.SelectBuffer(512, _selectBuffer);
    }

    private void glControlWindow_Paint(object sender, PaintEventArgs e)
    {

        GL.Clear(ClearBufferMask.ColorBufferBit);
        GL.Clear(ClearBufferMask.DepthBufferBit);

        float[] eyes = { 0.0f, 0.0f, -10.0f };
        float[] target = { 0.0f, 0.0f, 0.0f };
        Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(0.785398163f, 4.0f / 3.0f, 0.1f, 100f);  //45 degree = 0.785398163 rads
        Matrix4 view = Matrix4.LookAt(eyes[0], eyes[1], eyes[2], target[0], target[1], target[2], 0, 1, 0);
        Matrix4 model = Matrix4.Identity;
        Matrix4 MV = view * model;

        //First Clear Buffers
        GL.Clear(ClearBufferMask.ColorBufferBit);
        GL.Clear(ClearBufferMask.DepthBufferBit);

        GL.MatrixMode(MatrixMode.Projection);
        GL.LoadIdentity();
        GL.LoadMatrix(ref projection);

        GL.MatrixMode(MatrixMode.Modelview);
        GL.LoadIdentity();
        GL.LoadMatrix(ref MV);

        GL.Viewport(0, 0, glControlWindow.Width, glControlWindow.Height);
        GL.Enable(EnableCap.DepthTest); //Enable correct Z Drawings
        GL.DepthFunc(DepthFunction.Less); //Enable correct Z Drawings
        GL.MatrixMode(MatrixMode.Modelview);

        GL.PushMatrix();
        GL.Translate(3.0f, 0.0f, 0.0f);
        DrawTriangle();
        GL.PopMatrix();

        GL.PushMatrix();
        GL.Translate(-3.0f, 0.0f, 0.0f);
        DrawTriangle();
        GL.PopMatrix();

        //Finally...
        GraphicsContext.CurrentContext.VSync = true; //Caps frame rate as to not over run GPU
        glControlWindow.SwapBuffers(); //Takes from the 'GL' and puts into control
    }

    private void DrawTriangle()
    {
        GL.BindBuffer(BufferTarget.ArrayBuffer, _vBO[0]);
        GL.VertexPointer(3, VertexPointerType.Float, 0, 0);
        GL.EnableClientState(ArrayCap.VertexArray);
        GL.DrawArrays(BeginMode.Triangles, 0, 3);
        GL.DisableClientState(ArrayCap.VertexArray);
    }

    //mouse click event implementation
    private void glControlWindow_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
    {

        //Enter Select mode. Pretend drawing.
        GL.RenderMode(RenderingMode.Select);

        int[] viewport = new int[4];
        GL.GetInteger(GetPName.Viewport, viewport);
        GL.PushMatrix();
        GL.MatrixMode(MatrixMode.Projection);

        GL.LoadIdentity();

        GluPickMatrix(e.X, e.Y, 5, 5, viewport);

        Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(0.785398163f, 4.0f / 3.0f, 0.1f, 100f);  // this projection matrix is the same as one in glControlWindow_Paint method.

        GL.LoadMatrix(ref projection);
        GL.MatrixMode(MatrixMode.Modelview);

        int i = 0;
        int hits;

        GL.PushMatrix();
        GL.Translate(3.0f, 0.0f, 0.0f);
        GL.PushName(i);
        DrawTriangle();
        GL.PopName();
        GL.PopMatrix();

        i++;

        GL.PushMatrix();
        GL.Translate(-3.0f, 0.0f, 0.0f);
        GL.PushName(i);
        DrawTriangle();
        GL.PopName();
        GL.PopMatrix();

        hits = GL.RenderMode(RenderingMode.Render);

        .....hits processing code goes here...

        GL.PopMatrix();

        glControlWindow.Invalidate();
    }

```

I expect to get only one hit everytime i click inside a triangle, but i always get 2 no matter where i click. I suspect there is something wrong with the implementation of the GluPickMatrix, I haven't figured out yet.

# Answer
> 0 votes
I found out the bug. It should be:
`GL.MulMatrix(ref projection)`
instead of
`GL.LoadMatrix(ref projection)`

---
Tags: opengl, picking, opentk, selection
---


# Question
Title: Multiple ( V- / I- ) Buffers, is it sane?
Currently I am developing an RTS game using XNA ( / ANX.Framework ). There is one thing bothers me. I am not sure in what way or how to organise Buffers. Should I use a new Vertexbuffer for any object ( e.g. a Char, a Table, an model ) or is it better to use ONE HUGE/ BIG Buffer to store any geometry in?

I am still new to 3D Programming though I finished yet couple games using DirectX 9.

Well, I hope this question qin't a duplicate and I appreciate any answer leading me into the right direction.

# Answer
As long as performance isn't a concern, you can do whatever's convenient - which probably means a separate vertex/index buffer for each mesh.

If you sort your meshes when drawing, so that all instances of the same mesh are drawn together (e.g. all units of type A are drawn, then all units of type B, etc.), you can reduce state changes and also set yourself up well for adding geometry instancing later if it becomes necessary for performance. This will be a good pattern if you don't have too many different meshes, but potentially many instances of each mesh - which seems likely for an RTS (not too many unit/terrain types, but potentially a lot of units/tiles on screen).

The "one huge buffer" approach can reduce the number of state changes / draw calls still further if necessary, but it takes more code to manage, and requires a few other things like texture atlasing in order to actually realize the performance gains. I wouldn't worry about it unless and until performance analysis indicates that you truly need it.
> 4 votes

# Answer
There are certain guidelines you can use, but keep in mind that they may not always apply (or even matter) depending on the application:

* **Less draw calls is usually better for performance**, hence less VBOs, this will reduce state changes. This is usually possible for objects that share the same material.
* **Use interleaved vertex attributes**, for example store {V1,N1,V2,N2} instead of {V1,V2} {N1,N2}, as this will increase cache coherency.
* **Don't use misaligned vertex data**. It is better to have data that are 4-bytes aligned for example:

> V1{ half, half, half, half } --\> Next vertex starts at 8 which is a multiple of 4-bytes

Better than

> V1{ half, half, half } --\> Next vertex starts at 6 which is **not** a multiple of \> 4-bytes.

Because the driver is going to take more time aligning your data. It's even a good practice to add padding to force data alignment.

* **Draw from index buffers instead of vertex buffers**, this will minimize computations performed on vertices (e.g. transformation) as there will be less vertices,
* When using index buffer **keep in mind not to de-reference vertices that are far away from each other** in the vertex buffer as this will not help the cache coherency, for example de-referencing Index1=1 then Index2=3000 is usually a bad idea.
> 2 votes

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


title: Libgdx Palette Swap

text:
# Question
Title: Libgdx Palette Swap
I'm developing a game using the Libgdx library.

I'm trying to implement a very simple palette swap functionality (basically just complete recolouring of some areas, I don't even need to have various shades), but I don't have any idea where to begin.

The closest I've come is trying to draw the picture myself using a Pixmap, but that appears to be horrible unmaintainable and produces oodles of code.

# Answer
> 2 votes
I'm not sure if this is what you have already tried, but you can simply get the Pixmap of the Texture and draw over it:

```
texture.getTextureData().prepare();
Pixmap pixmap = texture.getTextureData().consumePixmap();
for(int i=0; i < pixmap.getWidth(); i++)
{
  for(int j =0; j < pixmap.getHeight(); j++)
  {
    if(pixmap.getPixel(i,j) == colorToReplace)
    {
      pixmap.drawPixel(i,j,newColor);
    }
  }
}

```

---
Tags: libgdx, palette
---


# Question
Title: How should I model an economy-based game in code?
I'd like to create an economy game based on an ancient civilization. I'm not sure how to design it. If I were working on a smaller game, like a copy of "Space Invaders," I'd have no problem structuring it like this:

* Main Control Class
* Graphics Class
* Player Class
* Enemy class

I don't understand how I'd do this for larger projects like my economy game. Do I create a country class that contains a bunch of towns? Do the towns contain a lot building class, most contain classes of people? Do I make a path finding class that the player can access to get around?

# Answer
> Do I create a country class that contains a bunch of towns?

Sure.

> Do the towns contain a lot building class, most contain classes of people?

Sure.

> Do I make a path finding class that the player can access to get around?

Sure.

Everything you have suggested above seems reasonable. It may not be the best way for you in the long run, but that's fine. It obviously makes sense to you know since it's the organizational model that first came to you. It's important that you take that and begin an implementation from it. It will both get you started, getting you over this initial "design paralysis" that often plagues developers at the beginning of a task, and (if it proves to be flawed in some way) teach you a thing or two about the pros and cons of that particular approach to design.

You've naturally taken the concepts in your head and grouped them into code according to some simple rules:

* Does this concept differ significantly in behavior or in data from other objects I already have? (Countries and people share very little, if any, meaningful data or behavior, so they should be represented by distinct types in-game).
* Will I even need to manipulate this concept in the code in a significant fashion (if your game deals with individual people, you may need that `Person` class, but if the game only cares about them in the aggregate, as in earlier versions of SimCity, you may not need that type nor instances of that type to create a 1:1 mapping of a town's population. `int populationCount` may be enough).
* Does this concept require *state*? If so it should be encapsulated somehow that allows me to store this state (a class) rather than a bunch of free functions. (A pathfinding implementation doesn't have an analogous real-world object, but it does require keeping track of data such as which nodes in the map it has already considered, and that is better done through a class than by storing it in a bunch of hidden globals and making freestanding functions).

While simple, answering those questions can benefit you a great deal when trying to decide if and how to transform a mental concept into source code. You may also want to read up on the SOLID principles of object-oriented design.

Note that the suggestion of an entity/component system made in the comments is also a valid approach, though I would eschew it here unless you re-scope your project to be smaller (simply because taking on two new, large challenges in one project may be too daunting and may dilute the educational benefit you would otherwise receive from focusing only on one). In a component-oriented model, the "type" in the questions above becomes more implicit: not the concrete type in code, but the implicit type defined by the collection of components that form an entity. The same guiding principles can apply.
> 5 votes

# Answer
What you have described (a class for every main type of logical game object) makes perfect sense for as simple game. If this is your first time writing a game of this type, I would suggest doing it this way.

Just a couple of tips:

* Is a **Player** really different from an **Enemy**? A lot of the functionality is likely to be the same, so these should normally be the same class or extended from the same base class. Consider an **AbstractPlayer** base class with two subclasses **HumanPlayer** and **AIPlayer** \- all the common functionality can go in **AbstractPlayer**.
* Prefer configuring objects with **composition** rather than inheritance. Don't make your inheritance hierarchies too deep. If you start calling a class **ForgeWithSteelAnvil** then you should be worried: A **Forge** might be a subclass of **Building**, but the type of anvil used should be an object contained within the building.
* Likewise prefer **properties** that enable you to configure objects rather than adding hundreds of slightly different object classes.

In more complex games, there are more advanced techniques you can use, but I suggest *not* using these until you are very comfortable with the basic OOP approach (i.e. have made a couple of completed games successfully). More advanced approaches might include:

* **Prototype based object models** \- use a single class for all game objects, and model all your objects through properties / attributes and composition. Much more flexible/dynamic than standard OOP, but trickier to manage (in particular, the compiler won't help you much if you do something stupid). I used this to good effect in my little Roguelike game Tyrant (https://github.com/mikera/tyrant)
* **Entity component systems** \- good if you have lots of complex behaviours that you want to mix and match in many different types of game objects. Very powerful, but hard to get right.
> 1 votes

# Answer
There are few methods that you can use to approach organizing your entities and data sets. I prefer to write a spreadsheet document and test data moving back and forth to make sure I am being efficient. If you are making the game yourself remember that it needs to make sense to you. Sometimes the most efficient route is to be slightly less efficient in code to make the project simpler.

If you want to have more help on structuring your content then find a old game source code that uses a similar structure or style and find their solution. Then refine it and fix it to your liking.
> 0 votes

---
Tags: java, architecture
---


title: Texture errors in CubeMap

text:
# Question
Title: Texture errors in CubeMap
I am trying to apply this texture as a cubemap. This is my result:

Clearly I am doing something with my texture coordinates, but I cannot for the life of me figure out what. I don't even see a pattern to the texture fragments. They just seem like a jumble of different faces. Can anyone shed some light on this?

Vertex shader:

```
#version 400
in  vec4 vPosition;
in  vec3 inTexCoord;

smooth out vec3 texCoord;

uniform mat4 projMatrix;

void main()
{
   texCoord = inTexCoord;
   gl_Position = projMatrix * vPosition;
}

```

My fragment shader:

```
#version 400
smooth in vec3 texCoord;

out vec4 fColor;

uniform samplerCube textures

void main()
{
           fColor = texture(textures,texCoord);
}

```

Vertices of cube:

```
point4 worldVerts[8] = {
    vec4(  15,  15,  15, 1 ),
    vec4( -15,  15,  15, 1 ),
    vec4( -15,  15, -15, 1 ),
    vec4(  15,  15, -15, 1 ),
    vec4( -15, -15,  15, 1 ),
    vec4(  15, -15,  15, 1 ),
    vec4(  15, -15, -15, 1 ),
    vec4( -15, -15, -15, 1 )
};

```

Cube rendering:

```
void
worldCube(point4* verts, int& Index, point4* points, vec3* texVerts)
{

    quadInv( verts[0], verts[1], verts[2], verts[3], 1, Index, points, texVerts);
    quadInv( verts[6], verts[3], verts[2], verts[7], 2, Index, points, texVerts);
    quadInv( verts[4], verts[5], verts[6], verts[7], 3, Index, points, texVerts);
    quadInv( verts[4], verts[1], verts[0], verts[5], 4, Index, points, texVerts);
    quadInv( verts[5], verts[0], verts[3], verts[6], 5, Index, points, texVerts);
    quadInv( verts[4], verts[7], verts[2], verts[1], 6, Index, points, texVerts);
}

```

Backface function (since this is the inside of the cube):

```
void quadInv( const point4& a, const point4& b, const point4& c, const point4& d ,
      int& Index, point4* points, vec3* texVerts)

{
    quad( a, d, c, b, Index, points, texVerts, a.to_3(), d.to_3(), c.to_3(), b.to_3());
}

```

And the quad drawing function:

```
void quad( const point4& a, const point4& b, const point4& c, const point4& d,
      int& Index, point4* points, vec3* texVerts, const vec3& tex_a, const vec3& tex_b, const vec3& tex_c, const vec3& tex_d)

{
    texVerts[Index] = tex_a.normalized(); points[Index] = a; Index++;
    texVerts[Index] = tex_b.normalized(); points[Index] = b; Index++;
    texVerts[Index] = tex_c.normalized(); points[Index] = c; Index++;
    texVerts[Index] = tex_a.normalized(); points[Index] = a; Index++;
    texVerts[Index] = tex_c.normalized(); points[Index] = c; Index++;
    texVerts[Index] = tex_d.normalized(); points[Index] = d; Index++;
}

```

Edit: I forgot to mention, in the image, the camera is pointed directly at the back face of the cube. You can kind of see the diagonals leading out of the corners, if you squint.

I tried writing the texture coordinates as colors as Nathan Reed suggested, and still got random values from the fragment shader, so I tried replacing all texture coordinates with (0,1,0) (so as colors, all faces should be green). Instead, I got this:

Old result with b and d vertices swapped in texture:

# Answer
Ok, I figured it out! glVertexAttribPointer() needs size set to 4 for cubemaps, even though only 3 coordinates are passed.

Thank you to everyone who helped me on this. I have to say I never would have thought of writing the texture coordinates as color data!
> 1 votes

---
Tags: c++, opengl, textures, cubemap
---


title: Help with timebased scoring algorithm

text:
# Question
Title: Help with timebased scoring algorithm
Im trying to devise an appropriate scoring system for my game. The game in essense has a finite number of tasks to complete (say 20) and the quicker you complete these task, the more points you get. I had devised a basic way of doing this using bands of time multiplied by a score for that band multiplied by the number of tasks solved within that time band i.e.

(Time Band) = (Points) 1-5 sec = 15, 5-10 secs = 10, 10-20 secs = 5, 20-30 secs = 3, 40 secs onwards = 1,

So for example if I did 3 tasks in the 1-5sec band i'd get 15\*3=45points, if i found 10 in the 20-30sec band i'd get 3\*10=30 points.

Im sure there is a more mathematical way of doing this using powers of some kind but I just can't think how and hoping someone has already done something smilar..

Many thanks in advance

# Answer
MickLH's suggestion of fitting a smooth function to your chosen point values is a good one. However, you do need to exercise some care in choosing the *kind* of function you want to fit.

For example, if, as I presume, you want the player's base score to remain above 1 (or at least above 0) no matter how much time he takes, then using a function of the form `a - b * log(x)` may be a poor choice, since the logarithm *will* eventually grow larger than `a/b`: you'd at least have to modify the calculation to always clamp the result above zero.

A better choice might be a function that naturally tends towards a limit, such as `a + b / (x + c)` or `a + b * exp(-x / c)`. Both of these tend towards the value `a` as `x` increases, so it may actually be best to fix `a` at the limit value we want (e.g. `a = 1`) and only vary `b` and `c` to achieve the best fit.

For example, I tried the following code in gnuplot (which has a nice non-linear fitting feature):

```
f(x) = a + b * exp(-x / c)           # define the function
a = 1; b = 15; c = 10                # initial guesses
fit f(x) '/tmp/data.dat' via b, c    # adjust b and c to fit the data

```

where the `/tmp/data.dat` file just contained the following values:

```
1   15
5   15
5   10
10  10
10  5
20  5
20  3
30  3
30  1
40  1
50  1
60  1
70  1
80  1
90  1
100 1

```

After a few milliseconds, gnuplot spat out the following adjusted values (which were pretty close to my initial guesses anyway, since I'd eyeballed it in advance):

```
b = 16.2064
c = 11.7286

```

Rounding these to `b = 16` and `c = 12`, here's what the final fit looks like, plotted with:

```
plot '/tmp/data.dat' with linespoints, f(x) with lines

```

Honestly, though, the initial guesses of `b = 15` and `c = 10` don't look bad either, they just tend to hug the lower corners of the data graph, whereas the fitted version runs closer to the middle of the range. In fact, if we drop the upper points from the data, `f(x) = 1 + 15 * exp(-x / 10)` starts to look like an *excellent* fit, at least at x = 1, x = 5 and x = 20 (the x = 10 and x = 30 points are a bit off, but in a pretty consistent fashion):

Just pick whichever one seems more reasonable to you, or tweak them yourself.
> 2 votes

# Answer
**Fitting** is the tool for the job. You can research least squares fitting for a more in-depth explanation.

is only a simplified example.

---

I plotted your input on Maxima with this command:

```
plot2d([discrete,[ [1,15],[5,15],[5,10],[10,10],[10,5],[20,5],[20,3],[30,3],[40,1] ]]);

```

It looked logarithmic to me so I went ahead and fitted the natural logarithm to your points, then plotted to verify (and adjust coefficients).

```
plot2d([[discrete,[ [1,15],[5,15],[5,10],[10,10],[10,5],[20,5],[20,3],[30,3],[40,1] ]],20-log(x)*5.2],[x,1,40]);

```

And the plot itself for fun and pleasure:

---

With all this said, you can just ask Wolfram Alpha to do it for you ;) http://www.wolframalpha.com/input/?i=fit+%5B1%2C15%5D%2C%5B5%2C15%5D%2C%5B5%2C10%5D%2C%5B10%2C10%5D%2C%5B10%2C5%5D%2C%5B20%2C5%5D%2C%5B20%2C3%5D%2C%5B30%2C3%5D%2C%5B40%2C1%5D
> 1 votes

---
Tags: mathematics, scoring
---


# Question
Title: How AlphaBlend Blendstate works in XNA 4 when accumulighting light into a RenderTarget?
I am using a Deferred Rendering engine from Catalin Zima's tutorial:

His lighting shader returns the color of the light in the rgb channels and the specular component in the alpha channel. Here is how light gets accumulated:

```
Game.GraphicsDevice.SetRenderTarget(LightRT);

Game.GraphicsDevice.Clear(Color.Transparent);

Game.GraphicsDevice.BlendState = BlendState.AlphaBlend;

// Continuously draw 3d spheres with lighting pixel shader.
...

Game.GraphicsDevice.BlendState = BlendState.Opaque;

```

MSDN states that AlphaBlend field of the BlendState class uses the next formula for alphablending:

(source × Blend.SourceAlpha) + (destination × Blend.InvSourceAlpha),

where "source" is the color of the pixel returned by the shader and "destination" is the color of the pixel in the rendertarget.

My question is why do my colors are accumulated correctly in the Light rendertarget even when the new pixels' alphas equal zero? As a quick sanity check I ran the following code in the light's pixel shader:

```
float specularLight = 0;

float4 light4 = attenuation * lightIntensity * float4(diffuseLight.rgb,specularLight);

if (light4.a == 0)
light4 = 0;

return light4;

```

This prevents lighting from getting accumulated and, subsequently, drawn on the screen. But when I do the following:

```
float specularLight = 0;

float4 light4 = attenuation * lightIntensity * float4(diffuseLight.rgb,specularLight);

return light4;

```

The light is accumulated and drawn exactly where it needs to be. What am I missing? According to the formula above:

(source x 0) + (destination x 1) should equal destination, so the "LightRT" rendertarget must not change when I draw light spheres into it!

It feels like the GPU is using the Additive blend instead:

(source × Blend.One) + (destination × Blend.One)

# Answer
Ok I figured this stuff out, was not obvious.

The reference MSDN page i talked about does state that "Blend type" "Alpha Blending" uses the following formula in XNA 4:

```
(source × Blend.SourceAlpha) + (destination × Blend.InvSourceAlpha)

```

But despite this, BlendState.AlphaBlend field has the following pre-set parameters:

```
ColorSourceBlend        Blend.One
AlphaSourceBlend        Blend.One
ColorDestinationBlend   Blend.InverseSourceAlpha
AlphaDestinationBlend   Blend.InverseSourceAlpha

```

So the correct formula the compiler uses is the following:

```
(source × Blend.One) + (destination × Blend.InvSourceAlpha)

```

And this is why my colors add up correctly even when SourceAlpha == 0. I guess the MSDN page has been incorrectly updated after they switched to premultiplied alpha in XNA 4.0:

http://blogs.msdn.com/b/shawnhar/archive/2009/11/06/premultiplied-alpha.aspx?Redirected=true

The BlendState.NonPremultiplied that exists in the library does exactly what the first formula suggests.

However, the lighting result under BlendState.AlphaBlend is incorrect for my deferred renderer as whenever any new pixel comes in with high alpha (specular) it would completely nullify all the colors in the destination texture.

Additive blend, despite human logic and despite its explanation has the following fields:

"A built-in state object with settings for additive blend that is adding the destination data to the source data without using alpha."

```
ColorSourceBlend        Blend.SourceAlpha
AlphaSourceBlend        Blend.SourceAlpha
ColorDestinationBlend   Blend.One
AlphaDestinationBlend   Blend.One

```

And this is why under this BlendState only those pixels where the alphas (specular) were more than zero were written into my cleared to (0,0,0,0) LightRT.

So in order for Catalin's Deferred Renderer to work properly I need a custom BlendState that would have the following parameters:

```
ColorSourceBlend        Blend.One
AlphaSourceBlend        Blend.One
ColorDestinationBlend   Blend.One
AlphaDestinationBlend   Blend.One

```
> 2 votes

# Answer
In that use case you should be (and are, I guess) using additive blending, not alpha transparency. This mode performs "source = source + destination"
> 0 votes

---
Tags: xna, hlsl, alpha-blending
---


title: Slick2D - Entities and rendering

text:
# Question
Title: Slick2D - Entities and rendering
I have been trying to create my very first game for quite a while, followed some tutorials and stuff, but I am stuck at creating my entity system. I have made a class that extends the Entity class and here it is:

```
  public class Lazer extends Entity{//Just say that it is some sort of bullet

private Play p;//Play class(State)
private float x;
private float y;
private int direction;

public Lazer(Play p, float x , float y, int direction){
    this.p = p;
    this.x = x;
    this.y = y;
    this.direction = direction;
    p.ent.add(this);
}

public int getDirection(){
    return direction; //this one specifies what value will be increased (x/y) at update
}
public float getX(){
    return x;
}
public float getY(){
    return y;
}
public void setY(float y){
    this.y = y;
}
public void setX(float x){
    this.x = x;
}
     }

```

The class seems pretty good , after speding some hours googling what would be the right thing. Now, on my Play class. I cant figure out how to draw them. (I have added them to an arraylist) On the update method , I update the lazers based on their direction:

```
public void moveLazers(int delta){
       for(int i=0;i<ent.size();i++){
           Lazer l = ent.get(i);
           if(l.getDirection() == 1){
               l.setX(l.getX() + delta * .1f);
           }else if(l.getDirection() == 2){
               l.setX(l.getX() - delta * .1f);
           }else if(l.getDirection() == 3){
               l.setY(l.getY() + delta * .1f);
           }else if(l.getDirection() == 4){
               l.setY(l.getY() - delta * .1f);
           }

       }
   }

```

Now , I am stuck at the render method. Anyway , is this the correct way of doing this or do I need to change stuff? Also I need to know if collision detection needs to be in the update method. Thanks in advance ~ Teo Ntakouris

# Answer
Using an entity system I would move the moveLasers method into the Lazer class. The idea of entities is that you got modular, kind of self managing objects and no 'super class'. You could implement a Draw and Update method in the Lazer class and just pass he calltoken from the main Update:

```
for(int i=0;i<ent.size();i++){
 ent.Update();
}

```

Update and Draw could be defined in the entity base class, then you main class would not even need to know what exact subtype of entity it is dealing with.

I would vote for a similar approach for your draw method. Just call each entities Draw method from the main method and pass the context into the function.
> 1 votes

# Answer
First you need an image to represent the laser. You're going to need to add another an field to your class that holds an Image. You can use almost any image file. Then in your game class just loop through the entity array and do something like

```
//rotate so visual representation of the laser is facing correct direction
entity[i].sprite.rotate(desiredAngle - currentAngle);

//draw visual representation of the laser
entity[i].sprite.draw(x, y);

```

And to answer your question on collision detection all game logic should go in your update method.
> 0 votes

---
Tags: java, lwjgl, slick, entity
---


# Question
Title: How to only render part of an image in lwjgl/openGL
I'm making a mining/building game in java using slick2D and I want to make it so you can only see a few blocks in any direction while you are underground. The best example I could find of what I want to do is the game miner dig deep.

One way I thought of doing it would be to have a large image and just draw transparent areas on it where you need to be able too see but even if that would be an efficient method I wouldn't be sure how to do that.

# Answer
I'd just make an image with a transparent circle in the middle and the rest entirely black. Then just render that over everything else in the game (except for the UI of course).
> 2 votes

---
Tags: opengl, java, slick, masking
---


# Question
Title: Creating a voxel world with 3D arrays using threads
I am making a voxel game (a bit like Minecraft) in C++(11), and I've come across an issue with creating a world efficiently.

In my program, I have a World class, which holds a 3D array of Region class pointers. When I initialize the world, I give it a width, height, and depth so it knows how large of a world to create. Each Region is split up into a 32x32x32 area of blocks, so as you may guess, it takes a while to initialize the world once the world gets to be above 8x4x8 Regions. In order to alleviate this issue, I thought that using threads to generate different levels of the world concurrently would make it go faster.

Having not used threads much before this, and being still relatively new to C++, I'm not entirely sure how to go about implementing one thread per level (level being a xz plane with a height of 1), when there is a variable number of levels.

I tried this:

```
for(int i = 0; i < height; i++)
{
    std::thread th(std::bind(&World::load, this, width, height, depth));
    th.join();
}

```

Where load() just loads all Regions at height "height". But that executes the threads one at a time (which makes sense, looking back), and that of course takes as long as generating all Regions in one loop.

I then tried:

```
std::thread t1(std::bind(&World::load, this, w, h1, h2 - 1, d));
std::thread t2(std::bind(&World::load, this, w, h2, h3 - 1, d));
std::thread t3(std::bind(&World::load, this, w, h3, h4 - 1, d));
std::thread t4(std::bind(&World::load, this, w, h4, h - 1, d));

t1.join();
t2.join();
t3.join();
t4.join();

```

This works in that the world loads about 3-3.5 times faster, but this forces the height to be a multiple of 4, ~~and it also gives the same exact VAO object to every single Region, which need individual VAOs in order to render properly. The VAO of each Region is set in the constructor, so I'm assuming that somehow the VAO number is not thread safe or something (again, unfamiliar with threads).~~

So basically, my question is ~~two~~ one-part:

1. How to I implement a variable number of threads that all execute at the same time, and force the main thread to wait for them using join() without stopping the other threads?
2. ~~How do I make the VAO objects thread safe, so when a bunch of Regions are being created at the same time across multiple threads, they don't all get the exact same VAO?~~ ~~Turns out it has to do with GL contexts not working across multiple threads. I moved the VAO/VBO creation back to the main thread.~~ Fixed!

Here is the code for block.h/.cpp, region.h/.cpp, and CVBObject.h/.cpp which controls VBOs and VAOs, in case you need it.

If you need to see anything else just ask.

EDIT: Also, I'd prefer not to have answers that are like "you should have used boost". I'm trying to do this without boost to get used to threads before moving onto other libraries.

# Answer
Re your first question - you could create your variable number of threads and store each one in a container (eg a vector).

When you need all the data, you can do a join on each one - a for loop perhaps. See the answer to this question. It uses boost but the idea is similar.
> 1 votes

# Answer
> How to I implement a variable number of threads that all execute at the same time?

Build/use a container class (I would call it a ThreadPool) for holding threads or thread references (note that std::thread is only movable and not copyable), each time one of the threads is started it **is not joined by default**. Wehn ThreadPool is going to be destructed you need to join each thread until it's finished.

> How to force the main thread to wait for them using join() without stopping the other threads?

It seems you need a way to **communicate between threads**, joining one will let you wait for it. A better idea would be not to join any thread and let the main thread block (or do other things) and wait for a signal/event from the ThreadPool when all worker threads finished their work.
> 4 votes

# Answer
1. I do not understand the problem. If you do not call the `join()`, they won't be waited for. You should call the join() only right before you absolutely need the data they produce. The other threads wont be stopped if you call `join()` on one of them. See the `join()` reference: http://www.cplusplus.com/reference/thread/thread/join/
2. VAOs are not shared in between contexts. You need to pass the VBOs to the drawing thread where you will create the VAOs and bind the VBOs in them.
> 2 votes

# Answer
No one seems to have told you what the mistake in your first approach was:

Calling join() right after each threads creation means your main thread waits for each thread **before** he creates the next one. Obviously this results in a sequential execution, not a parallel one. You need to maintain a list or something of the threads, and call join() on each of them **after** the creation loop.

Expressed in pseudocode, this is what i mean:

```
for(...){ createThreads }
for(...){ joinThreads }

```
> 1 votes

---
Tags: opengl, multithreading, c++, vao
---


# Question
Title: RGB values from image into a one dimension array in c#
I was wondering if there is a was a way to read rgb values from an image into a one dimensional array in C#. If it doesnt make sense, in java I would do something like this.

```
int[] pixels;
BufferedImage image = getClass().getResourceAsStream("asdfghjkl.png");

int w = image.getWidth();
int h = image.getHeight();

pixels = new int[w * h];
image.getRGB(0, 0, w, h, pixels, 0, w) ;

```

So any help would be great, or if you can point me in the right direction, that'd be great

# Answer
In Memory, 2d Arrays are still linear 1d arrays. they are just stored after each other, so accesing a position at XY would be the following :
pixel = width * y + x;

And reading images in C# is wery much possible. it would be just to read a file with a streamreader, and then you have to take account with the header describing the images. from there you can easily read pixels. Bare in mind that PNG is a pretty HARD format to read, and there are helpers all around the internet if you google some.

Reading a TGA is much easier where the structure is just like the following :
Header ( about 32b )
Pixels

This site tells you how to read a text file, the principle is the same, you just have to know the structure of the image type. Loading an textfile

this site also explains the layout for a .tga file : TGA structure
Itś not PNG as your example code, but it will give you a good start.
> 1 votes

# Answer
Here is the general idea :

* Create a `System.Drawing.Bitmap` from your image file/stream.
* Use `LockBits` on the bitmap to access unmanaged image data.
* Call `System.Runtime.InteropServices.Marshal.Copy` to copy unmanaged data to your array.
* Call `UnlockBits` on the bitmap to clean up a little.

Do not use `GetPixel` if performance matters as it's slow as hell.
> 0 votes

---
Tags: c#, image, pixel
---


# Question
Title: UDP non-blocking or a separate thread for receiving?
I am creating a multiplayer game (for under 64 players). I already decided to have a separate thread for the network loop, but I was wondering if it would be better to create an extra thread for receiving UDP or set the receiving socket on non-blocking (without extra thread).

Or is it better to use another method like Asynchronous Sockets? Better methods are always welcome!

# Answer
> 7 votes
Okay, first of all, if you have something and it's working, it's usually a good idea to leave it like that. Why fix what's not broken?

But if you're having trouble, and would really like to rewrite your networking code, I think you have four main choices:

1. Multithreaded blocking code (what you're doing right now)
2. Non-blocking sockets with level-triggered notification
3. Non-blocking sockets with readiness change notification
4. Asynchronous sockets

Having written lots of multiplayer (from peer-to-peer to massively multiplayer) clients and servers, I like to think that option 2 leads to the least complexity, with pretty good performance, both for the server and client parts of the game. As a close second, I would go with option 4, but that usually requires you to rethink your entire program, and I mostly find it useful for servers and not clients.

In particular, I would like to advise against blocking sockets in a multithreaded environment, as doing so usually leads to locking and other synchronization features which not only greatly increase the complexity of the code, but may also degrade its performance, as some threads wait for others.

But above all that, most socket implementations (and most I/O implementations at that) are non-blocking at the lowest level. Blocking operations are simply provided to simplify the development of trivial programs. When a socket is blocking, the CPU in that thread is completely idle, so why build a non-blocking abstraction over the blocking abstraction over an already non-blocking task?

Non-blocking socket programming is a bit daunting if you haven't tried it, but it turns out it is quite simple, and if you're already doing input polling, you already have the mindset to do non-blocking sockets.

The first thing you want to do is to set the socket to non-blocking. You do that with `fcntl()`.

After that, before you do `send()`, `recv()`, `sendto()`, `recvfrom()`, `accept()` (`connect()` is a bit different) or other calls that could block the thread, you call `select()` on the socket. `select()` tells you whether or not a subsequent read or write operation can be performed on the socket without it blocking. If that is the case, you can safely do the operation you want, and the socket won't block.

Including this in a game is quite simple. If you already have a game loop, for example like this:

```
while game_is_running do
    poll_input()
    update_world()
    do_sounds()
    draw_world()
end

```

you could change it to look like this:

```
while game_is_running do
    poll_input()
    read_network()
    update_world()
    do_sounds()
    write_network()
    draw_world()
end

```

where

```
function read_network()
    while select(socket, READ) do
        game.net_input.enqueue(recv(socket))
    end
end

```

and

```
function write_network()
    while not game.net_output.empty and select(socket, WRITE) do
        send(socket, game.net_output.dequeue())
    end
end

```

In terms of resources, the only book I think everybody must have in their bookshelves, even if it's the only book they have, is "Unix Network Programming, Vol 1." by the late Richard Stevens. It doesn't matter if you do Windows or other OS or language socket programming. Do not think you understand sockets until you read this book.

Another resource where you can find a general overview of the available solutions in terms of multiple socket programming (mostly relevant for server programming) is this page.

# Answer
> -1 votes
You didn't write which programming-language you are using, but most languages provide good asynchronous socket frameworks which often utilize features of the underlying operating system.

When you write your own threaded implementation based on blocking sockets (remember: when you have multiple clients, you need a thread for every single socket), you are just going to reinvent what the asynchronous socket framework already provides.

So I would recommend you to use asynchronous sockets.

---
Tags: networking, multiplayer, multithreading, udp
---


# Question
Title: Feasability of mobile 2D multiplayer RPG game with interactive bitmap background
I'm looking to develop a 2D multiplayer RPG game for Android, with a bird's eye view similar to that of zelda/pokemon. The game is very simple in all ways since my intent is for thousands of players to occupy the same world which I imagine requires good performance. However, I am unsure about the performance requirements of two properties:

1. the tile map that is used as a background is dynamic (interactive). For example, a player steps in the water, and the water turns black. Every tile in the game does this.
2. the tile map is the same object used for all players, but it is displayed differently on each user's mobile device, even though the players exist in the same world. For example, the water that turned black is displayed as red on all other players' screens.

I have knowledge of java, but almost none regarding game dev. tools. Is there a best process for these requirements? Should I develop in pure java, or use some tool like Slick2D etc.? How performance intensive are these properties, if even possible?

Edit: There are no collisions in the game or difficult animations, I am imagining simply changing the colors of the tiles (like in the examples), and a client-server architecture

# Answer
You should be fine doing all of this (tiles with states, various players, etc) as long as you maintain your world state (i.e. the state of each tile, player, etc) on the server. Each client would then receive the current world state from your server at some interval - which you should tweak according to your specific requirements and testing.

Performance wise, none of the things you want to do would specifically be an issue on mobile (or in java). As long as your design is sound and your server is up to the task of supporting your intended number of players. As for this last point (thousands of players in your world) it will again mostly be up to your server, not the mobile client to do the heavy lifting - the mobile will only need to display the visible number of players at any one time so there should not be a performance problem.

As a performance test you could render your required number of tiles and characters as static images and measure the performance. This would give you a baseline of render performance, which will of course be higher than the final implementation, but should provide you with the assurance that your mobile device(s) will be capable of handling it - and if not you could play around with ways to optimize the rendering in order to achieve decent performance.

I would personally first create a prototype to test your ideas out, instead of designing the whole thing outright. You will gain many insights into what needs to be done if you play with a live implementation, instead of theorizing about it. There are other considerations once you implement the final version (such as texture organization and render ordering, etc) but these are best handled once you have a working system.

Don't design with too much optimization in mind, but rather solve your problem first (i.e. get it working). You might then "see" better ways to optimize than you could theorize without a working implementation.
> 1 votes

---
Tags: java, 2d, android, multiplayer
---


# Question
Title: Need ideas for an algorithm to draw irregular blotchy shapes
I'm looking to draw irregular shapes on an x,y grid, and I'd like to come up with a simple, fast method if possible. My only idea so far is to draw a bunch of circles of random sizes very near each other, but at a random distance apart from a more or less central coordinate, then fill in any blank spaces. I realize this is a clunky, inelegant method, hopefully it will give you a rough idea of the kinds of rounded, random blotchy shapesI'm shooting for. Please suggest methods to accomplish this, I'm not so much interested in code. I can noodle that part out myself. Thanks!

# Answer
> 1 votes
You might want to choose some points, choose a vector at each point and draw a spline through them. See this wikipedia page for a simple description of a cubic spline (aka Irwin-Hall spline). It's been a while since I used them, but if I remember correctly, this was the one that I found to be the easiest to understand and use. If you know the pen tool from photoshop, this works very similar (I'm convinced photoshop uses splines too, but I'm not sure if it is a cubic spline).

If you're interested, there are many more splines: for example, Bezier splines and B-splines are interesting.

Another thing that comes to mind are level sets, although that would probably require a little more research from your side (to find functions that satisfy your requirements).

Level sets are inequalities in the form
f(x, y) = c
where f is some function and c is some constant.
This is a very general description. You might want to fill out some shape, and draw all pixels where
f(x, y) \<= c
with some color. For example, for a perfectly round 2d shape, you have the well-known equation:
x^2 + y^2 \<= r^2
You can scale the x and y components to get an ellipsoid With a little experimentation and research, it will be possible to find some funkier shapes (I suppose).

Edit: a little experimentation on wolframalpha.com gave me this. (created with the command 'plot abs((x+sin(x)\*y/3)^3)+y^2\<=7'). I have no idea if this is anything like what you want, but it's just to give you an idea.

# Answer
> 1 votes
Another straightforward approach is by using your own *low-frequency* noise to draw (or define) a figure in polar coordinates.

Suppose you want a blob centered at the origin, of average radius 1; this can easily be scaled and translated to other positions and sizes. Imagine with the simple equation r=1 — this would define a circle of radius one at the origin. To add a little variation to it, you can change the radius sinusoidally - add a term of the form w1\*sin(θ+θ1), where w1 and θ1 are constants I'll get back to in a bit. One sin term won't make a whole lot of difference, but having several *different* sines of different frequencies will start to add exactly the sort of 'soft' variation I suspect you're after. The overall form would be along the lines of r=1+w1\*sin(θ+θ1)+w2\*sin(2θ+θ2)+w3\*sin(3θ+θ3)+w4\*sin(4θ+θ4)+w5\*sin(5θ+θ5) - or more terms if you want, of course.

So how do we pick the values for wi and θi? Well, the θs should just be picked randomly from (0,2π) - in other words, each 'wave' on the surface's shape should start at a different point around the shape. As for the w's, there are several different choices. Choosing wi at random from (0, w) (for some fixed w that represents the 'overall variation' to give the shape; I might start with w=0.25 but experiment with w=0.1) for every i will lead to so-called *white noise*, where all the frequencies have equal weight — this will be by far the 'blobbiest', with wide variations at all frequencies. Choosing wi at random from (0, w\*(1/i)) — in other words, dividing each random weight by i — gives *pink* noise, where the weight trails off, but slowly. This is also known as *1/f* noise, and it's the most famous 'fractal' noise. Finally, choosing the weights randomly from (0, w\*(1/i^2)) (in other words, dividing each random weight by i^2) gives *brownian* noise - this is the 'softest' of the three, with the least variation from a circle - it'll generally be an oval-ish shape.

Here are examples of the three, using a 'total weight' of w=0.25, and using the same set of random values for the wi and θi pulled from random.org:

"White Noise" blob:

"Pink Noise" blob:

"Brownian Noise" blob:

Note that these blobs won't be perfect; in particular, it's impossible for them to curl back on themselves (since for every θ — in other words, for every angle from the origin — there's a single r value), and if you don't choose your weights right they might self-intersect (if r is allowed to go negative). But they do a decent job of being convincingly blobby, and for most games applications users won't notice any issues.

# Answer
> 0 votes
Aside from the other answers, you could use a Perlin noise with a round falloff, if you tweak the settings a little, you could easily create some nice varying shapes.

If you want your code to be fast, you could just use a noise-generation library like libnoise(Assuming you are using c++), which is a noise-generation library, that makes similar tasks very simple, as it provides you with a node-based approach on noise-based procedural generation. It has bindings to other languages too.

---
Tags: 2d, algorithm, random, procedural
---


# Question
Title: Changing State in PlayerControler from PlayerInput
In my player input I wanna change the the "State" of my player controller but I have some trouble to do it

my player input is declared like that :

```
class ResistancePlayerInput extends PlayerInput within ResistancePlayerController
    config(ResistancePlayerInput);

```

and in my playerControler I have that :

```
class ResistancePlayerController extends GamePlayerController;

var name PreviousState;

DefaultProperties
{
    CameraClass = class 'ResistanceCamera' //Telling the player controller to use your custom camera script
    InputClass = class'ResistanceGame.ResistancePlayerInput'
    DefaultFOV = 90.f //Telling the player controller what the default field of view (FOV) should be
}

simulated event PostBeginPlay()
{
    Super.PostBeginPlay();
}

auto state Walking {
    event BeginState(name PreviousStateName) {
        Pawn.GroundSpeed = 200;
        `log("Player Walking");
    }
}

state Running extends Walking {
    event BeginState(name PreviousStateName) {
        Pawn.GroundSpeed = 350;
        `log("Player Running");
    }
}

state Sprinting extends Walking {
    event BeginState(name PreviousStateName) {
        Pawn.GroundSpeed = 800;
        `log("Player Sprinting");
    }
}

```

I have tried to use

`PCOwner.GotoState();` and `ResistancePlayerController(PCOwner).GotoState();` but won't work.

I have also tried a simple GotoState, and nothing happen

how can I call GotoState for the PC Class from my player input ?

# Answer
If you are in the player controller class trying to change state the code works as

```
 GoToState('Fleeing');

```

If in Pawn, what I have gotten to work is

```
Controller.GotoState('PlayerClimbing');

```

because you are in the controller state you don't need to repeat it.

Hope that helps.
> 1 votes

---
Tags: udk, unreal
---


title: Looking to render video in game?

text:
# Question
Title: Looking to render video in game?
I have recently been looking to add a feature which will allow me to render a movie\video into my game. I.e, something pre-rendered and played as the game starts.

I am using Java2D purely so I am curious if there are any frameworks out there that will allow me to do this in an active rendering environment.

Thanks.

# Answer
> 2 votes
Here's a StackOverflow question asking a similar thing. Video playback in Java ( JMF, Fobs4JMF, Xuggler, FMJ )

The answers seem recommend http://www.xuggle.com/xuggler, though its more for encoding/decoding work, or VLCJ. VLCJ appears to specifically work with AWT and Swing.

This answer to the question above says it's possible to use VLCJ get BufferedImages - you'll then be able to draw directly with Java2D:

> The other caveat is that the embedded media player won't work with a swing component... you can use the direct media player to get a bufferedimage and display that on whatever you choose, but it will eat into your CPU a bit more (though no more than other players that take this approach.)

**EDIT:** Googling around a bit, I've found this example (from the VLCJ test code infact): DirectTestPlayer.java. This seems to do almost exactly what you need.

---
Tags: java
---