# Question
Title: Soccer national teams uniforms and copyright when developing a soccer game
I have a project to be accomplished in a distant future about a soccer game.
I´ve read that you can´t feature the actual national teams uniforms without getting permission from FIFA.
Is this only for special designs or for jerseys which are a single colour (most of them) too?
Can you copyright a color? From what I know, most copyright laws don´t allow for a single colour or color combinations to be registered, but maybe in the context of a specific sport and specific teams it is allowed.

PS: thanks, when and if this gets commercially serious, I will seek legal advice.
To be more precise, by presenting a team as *Germany* with a white shirt and black pants, no logo, no real player names and no real stadiums, do you think that would be considered a copyright infringement?

PS2: the RGB knob approach is what I thought of for teams created by each user. But also though it would be nice to have a special competition which would be a world cup.

# Answer
> 8 votes
(not a lawyer but have developed with licensed sports titles before)

Start with everything generic, but make the uniform patterns + colors + logos configurable. This way you can work for a long time and not care about uniforms at all, but be ready to change them when you get your licenses.

You will not only have to license the team colors and jersey patterns, but also the player names on the roster and it will get expensive. Beyond that if you use any recognizable stadiums you will have to license those too, this is very common in American Baseball where stadiums are different and recognizable. Beyond even those issues if you use any stadium music or team songs, yes those need licenses. And get this, if players are wearing recognizable shoes like Adidas stripes or Nike swooshes, licensed.

You will need a lawyer with knowledge of Intellectual Propery to help you figure all those issues out.

(this is in the US, your country may vary)

# Answer
> 1 votes
**A *possibly* safe approach...**

I suggest something along the lines of what is known as "paper dolling" in the MMORPG arena where your players can select the colours of the uniforms (and provide them with RGB knobs so they can get the exact colour they want), broken down to:

* Shirt colour
    + Background (the cloth colour)
    + Foreground (the player number)
* Short colour
* Sock colours (left and right could be different colours)
* Shoe colours (black, brown, grey, and white should be enough selection for this part)

Also, start out with a randomly selected colour combination (and indicate that it was randomly selected), then provide the player with an option to randomly select a colour for each item (right next to all the RGB knobs).

I believe this solution will provide you with the most unbiased approach possible, without violating any specific colour schemes (getting feedback from a properly qualified lawyer would be wise here though anyway), but also without limiting your players from selecting the colours of their favourite teams.

You could even provide them with an option to supply art to use as a logo, and then you wouldn't be providing the logos. Your game's user interface could even remember the 25 most recent paths to logo files (along with the colours) that players used so they can easily re-create their teams the next time they play.

**Dealing with logos...**

If you wish to place a particular logo on the shirts, then you'll definitely need to get permission from whoever owns the trademarks before including them with your game.

If you're good at writing letters, draft up a friendly one on your own first and then have a lawyer with experience in Intellectual Property to review it before you send it (don't be surprised if you are expected to pay royalties, as it is important not to lose the perspective that sports teams are businesses that provide a product in the ever-so-popular "entertainment" category).

Any correspondence you have with owners of the logos, for which it is safe to assume that they're all Registered Trademarks, should be done with the assistance of a properly qualified lawyer.

---
Tags: game-design, legal
---


# Question
Title: How to draw a 3D world with lines, more like a sketch drawing or cartoon
Consider making an ink drawing, with no shading and all lines having equal weight - such as you see in a strip comic like Dilbert. This represents an active 3 dimensional world, but objects do not have textures, yet you don't see tessellated triangles either.

For the sake of an example consider drawing the surface of the moon. The lines you might draw would be along the top edge of hills, down to where they meet the general level of the surface. Behind those you would do the same for larger hills, into the distance, and behind that what was visible of the horizon. For craters, you might draw a near circle for the outer edge, and partly masked, a circle for the lower edge. Boulders would have a line around the edge, and along major visible edges. The astronauts would have a line along their outer edge, and along major features of their space suit.

I'm an experienced programmer but new to 3D programming. I can't offhand think of a game that looks like this -- has it been done? And how would one do it? Two problems come to mind -- finding the significant edges, and drawing it. Would it need an "engine" coded from matrices up, based on lines, rather than a regular 3D engine?

# Answer
Fundamentally, what you're talking about is edge-finding, and there are a number of games that do it, in a variety of different ways.

Probably the first one was Jet Set Radio (released in the west as "Jet Grind Radio"). Released only a month or two after that was the game for which I'd developed a similar rendering technique: Looney Tunes: Space Race. (On Space Race, we did our best to maintain a uniform line thickness, while Jet Set Radio made the uneven line widths a big part of its visual style).

Both of these games worked the same way; for each object to be outlined, draw the object twice. First, render it with backfacing reversed, with a vertex push applied (that is, move each vertex by some distance along its normal vector), and in whatever color you want the 'lines' to appear to be. Then draw again, without the vertex push and with normal backfacing. This pair of operations gives you a colored silhouette edging around an object, and it's all that these first two games used. In Space Race, I maintained the illusion of constant line width by pushing vertices a varying distance, based upon how far the object was from the camera. In Jet Set Radio, they didn't (which led to lines becoming larger or smaller, as objects moved closer or further from the camera)

NVidia and ATI have several demos of other ways to achieve this effect, mostly revolving around pixel shaders looking for normals which are perpendicular to the camera-to-pixel vector for each pixel, but these all require very high-resolution meshes, and produce inconsistent line widths in practice. I don't know whether any games actually use this type of approach; I don't think I've seen any which look like the samples from these companies.

I'll also point you at Dragon's Lair 3D, which is the only game I know of which seems to really be doing this properly; taking the dot product of camera-to-polygon and the polygon's normal for each polygon in a model to see whether each polygon faces toward or away from the camera, and then checking all pairs of connected polygons; if any pair of polygons share an edge, and one polygon faces the camera and one polygon doesn't, then it draws a thin, constant-width line along that edge in screen-space. (I couldn't make this work fast enough on the Dreamcast for Space Race, or I'd have used it. Today, on modern computers, this is totally the way I'd be trying to do this effect, even though it's a bit processor-intensive to be checking every pair of polygons on every model every frame)

Dragon's Lair 3D is also the only game I'm aware of which actually draws lines between areas of different color or at vertex-normal discontinuities, even if there isn't a silhouette edge for it to find there. I suspect that they had a custom tool which allowed their artists to nominate polygon edges to always receive a line.

Okami, which has been mentioned by some other folks, appears to be using a double-render vertex-push approach, similar to Jet Set Radio and Space Race, but also uses textures which have been built using a brushed art style. (Hills in the distance, for example, are drawn as brush strokes into a texture which is drawn as a standard quad). Okami is lovely, but I don't think that it really touches on the tech that you're asking about; certainly, it's using the older approach for its effect.

Now, in your case, you're asking about doing this without a color fill, just drawing the world with lines only. That's easy to do; just draw all polygons without lighting, and in a single constant color that matches the background color. Any of these approaches should work using that approach without changing your game engine at all. It's important to actually draw those "same color as the background" polygons, as they'll keep background edges from showing through foreground objects, which could get confusing very quickly.
> 11 votes

# Answer
What you're talking about is non-photorealistic rendering (aka NPR). In a realtime 3D game that's done using fragment/pixel shaders.

Scroll through here to see a few examples: http://developer.download.nvidia.com/shaderlibrary/webpages/shader\_library.html
> 1 votes

---
Tags: 3d
---


# Question
Title: What math should all game programmers know?
Simple enough question: What math should all game programmers have a firm grasp of in order to be successful?

I'm not specifically talking about rendering math or anything in the niche areas of game programming, more specifically just things that even game programmers should know about, and if they don't they'll probably find it useful.

*Note:* as there is *no one correct answer*, this question (and its answers) is a community wiki.

Also, if you would like fancy latex math equations, feel free to use http://mathurl.com/.

# Answer
> 141 votes
There are *many* other forms of math that are useful, but at the absolute *minimum* you need to know these:

* **Algebra and Arithmetic**

These are pretty basic, but if you don't know these you won't have a chance at even being a programmer let alone a game developer.

Objects in a game world are represented with vectors. A vector represents things like an object's position, look direction and speed. Vector math calculations such as the Dot Product, Cross Product, and Vector normalisation are essential.

How do I move my game object? The novice might say:

"I know! I'll just do:" `object.position.x++`.

No no no. You need to use a vector calculation. The object needs a position, direction and acceleration vector which you can use to move the object. If you do the novice thing, you'll get stuck in an unmaintainable mess, and how do you make it move in a direction not aligned with the world's XYZ axis?

Main reason games use quaternions is because they represent rotations almost as space-efficiently as Euler angles, without suffering from Gimbal lock. Gimbal Lock begins when any Euler angle reaches a rotation of 90 degrees around any axis: you immediately lose a degree of freedom. Quaternions address this issue by adding a fourth dimension. If you stuck with Euler angles, you'd have to restrict one axis to never rotating more than ~89 degrees.

If you are going to be programming the math for physics responses in a game, then taking a physics class wouldn't have been a bad idea.

Reasons why you will need to know physics equations:

1. Making a ball bounce (see: co-efficient of restitution)
2. Make a ball move in a direction with 'x' newtons of force
3. Make something have more or less friction so it will slide at a different speed
4. Collision responses: What direction will the object rotate when I hit it 'here'?

If you use a physics engine (or a game engine which has the physics engine inbuilt) then you can get away with knowing very little about physics. Still, it's quite good to know when you need to get your hands dirty because the physics engine isn't performing properly.

# Answer
> 54 votes
I dream of the day when game development is as data driven as art production. I don't see it anywhere on the horizon so for now knowing some math appears to be a necessity.

Math is like technique, the more the better, as long as you can apply it.

Here is the order of importance I see.

* Arithmetic
* Linear Algebra (with geometric interpretations)
* Calculus (physics)
* Combinatorics (randomized levels)
* Probability (balancing)
* Statistics (Bayesian esp. for AI)

I could keep going. The more you know the better, but learning a bunch of math doesn't mean you will make a great game, but it can help.

# Answer
> 26 votes
A very basic one is the Pythagorean theorem. Also known as the distance formula.

where *`a`* and *`b`* are the edges of a right triangle and *`c`* is the hypotenuse. This means that in order to find the length of a vector, you do this:

Another note of interest is that if you're just *comparing* distances, you don't have to take the square root (which can be relatively costly). That's why most frameworks have a "distance squared" or "length squared" function for their vectors.

# Answer
> 21 votes
* Vectors both 3D and 4D, and what the W component should be set to
* Left-hand and right-hand coordinate systems, and which one your game is
* The dot product, and what it's useful for
* The cross product, and what it's useful for
* Matrices, how they represent orientation and position and how you can combine them
* Quaternions

Even if you're not The Graphics Guy, you're going to use vectors and vector maths 80% of the time. They're the onions of our fun bolognese.

# Answer
> 12 votes
A firm grasp of `+`, `-`, `*`, and `/`. Without them, you're completely screwed.

# Answer
> 11 votes
Yeah, game programming tends to be pretty math-intensive. What math you need depends on what you're working on. Basic arithmetic is a must, of course, just as it is in all programming. Beyond that:

Geometry is vital to any graphics work. If you want to display things on screen, you need to understand coordinate systems. And if you want to move them around in anything but the cardinal directions, you'll be completely lost without a solid grasp of sines, cosines and vectors (basic trig). And if you need to work in 3D, the geometry and trig requirements get a lot more complicated.

If you want to model any sort of remotely realistic physics, you need calculus for that. (It's what drove Newton to invent calculus, afterall.)

Any sort of probability calculations require knowledge of statistics and probability theory in order to get sane results without insane amounts of trial and error.

There's probably a lot more, but that's what comes to mind just off the top of my head.

# Answer
> 10 votes
**Binary** and **Hexadecimal** numbering systems, and how to convert them to/from decimal numbers.

Although you won't generally need to work with *raw* Binary numbers, they are frequently used for Flag variables, which require boolean logic and bit-shifting.

Hex isn't quite as important (unless you want to process 0xDEADBEEF), but at a minimum, you'd want to *recognize* when they're being used, and why.

# Answer
> 9 votes
At the very least you'll need.

* Algebra
* Basic Geometry
* Basic Trigonometry

You'll also want to have at least a working knowledge of Vector operations, and you'll want to know what a Matrix is and what it can be used for, although the details won't be strictly necessary.

If you'd like to get into graphics programming you'll need a hell of a lot more math knowledge, but doing general gameplay programming does not have to be so math intensive.

# Answer
> 7 votes
I think the payoff matrix is a pretty essential tool. Games are often more fun when they approach some interesting zero-sum fair play balance, and payoff matrices help you quantify that in complicated cases. I guess this wikipedia article is as good as any, and gets the basic necessary concept across: http://en.wikipedia.org/wiki/Normal-form\_game

# Answer
> 6 votes
No mentions of the foundational maths of computer programming? Graph theory, number theory, set theory, and concrete mathematics, usually all lumped together into painful and poorly-taught class called "discrete mathematics" at university.

"Stupid bit tricks" save every kind of program time (and they're also usually equivalent to some string tricks and set tricks), graph types and traversals are used all over the place (even if you're just picking STL containers), and algorithmic complexity is key to optimization as languages get to higher levels.

# Answer
> 4 votes
Understand the dot product: If two vectors have about same direction, (theta \< 90 deg), then the dot product is positive, or else, negative. It can be used to test whenever the player is in sight (assuming FOV is 90 deg).

And generalize your 2D game to higher dimensions. (use vector calculations)

If you can implement a 3D engine by yourself, you are good to go.

# Answer
> 4 votes
**It depends on what you're doing**.

**All** game programmers should know at least high school algebra. That means:

* A good sense of numbers
* Comfort with basic math (add, sub, mult, divide)
* Trigonometry (sin and cos)
* Vectors, angle between vectors, dot product, cross product

Your graphics programmers must know:

* All the above, and
* Matrix algebra (for transformation matrices)
* Polygon intersection methods / ray-polygon (see a book like Real-time collision detection

Your physics programmers must know:

* All of the above and
* Differential equations
* Numerical methods

# Answer
> 3 votes
Besides sines and cosines (which 50-75% of programmers I've met didn't know how to use), learn the magical arc-tan function and how it can be used to get the angle of any vector.

---
Tags: software-engineering, mathematics
---


title: Is Deferred Rendering The Future?

text:
# Question
Title: Is Deferred Rendering The Future?
Is deferred rendering the future of real-time 3d rendering on pc hardware (at least until raytracing becomes feasible)? I'm aware of the benefits (lots of lights, less state changes) and also trouble spots such as anti-aliasing, translucent items, and higher memory bandwidth.

But will the next-gen engines all be using deferred? Is forward rendering a thing of the past?

# Answer
> 14 votes
This is an old question, but I wanted to mention something.

Deferred rendering hits GPU bandwidth hard. The lighting passes fetches from anywhere from 3 to 5+ textures, for every pixel on the screen, for every light. That's a lot of bandwidth.

This hurts mobile GPUs, an increasingly important segment, more than others. Yes, they're low-power chips, but they still have some shader power behind them. Deferred rendering on such platforms is going to hurt. This is particularly true for PowerVR-based platforms (the current most popular mobile GPUs), as their tile-based rendering system already gets many of the advantages of deferred rendering.

But more than that is the current trend to putting GPUs on CPUs. Now, you may think that this would only work for low-end games, but AMD is talking about CPUs with up to 400 shader processors or so; that's some decent horsepower. Yes, you won't run the highest of the high-end games at full settings, but it would be a serviceable GPU.

For these GPUs, the lighting pass is going to suffer. These chips currently use the same bandwidth the CPU uses. Indeed, for such platforms you may want to start using fast noise functions to compute colors or normals instead of textures.

Deferred rendering is really tailored towards higher-end hardware. With the current "race to the bottom" in CPU/GPU chip design (lower-power, etc), deferred rendering may be the future only for those who still have discrete GPUs.

# Answer
> 6 votes
As you highlight yourself, deferred rendering isn't a silver-bullet which solves all problems, and it also introduces new issues.

So no, it's probably not the future, nor will it be used in all engines.

Instead I think you're going to see a mix of technologies, including forward and deferred rendering used for some time to come.

---
Tags: rendering, deferred-rendering
---


# Question
Title: Deferred lighting and projective texturing?
Is posible to use this technique with deferred lighting?

# Answer
> 3 votes
What does the projected texture represent? Projective texturing is a means of generating texture coordinates from vertex positions, to make it appear that the texture is projected over the scene like a film projector.

Can you still do these computations in deferred rendering? Yes. But when and how you do it depends on what the values in the texture represent?

Projective textures are often used to represent things like flashlights. In which case, the texel values are light intensities. And that means you need to do the projection during the lighting pass. Once you reconstruct the position of the particular screen pixel, just do the usual projection computation.

If the projective texture alters the albedo (diffuse reflectance, or diffuse color) of the object, then this must be done in the G-buffer pass. There, you can do the projection computations per-fragment or per-vertex, but you'll get better results per-fragment.

# Answer
> 2 votes
Yes, you just have to perform regular projective texturing in the GBuffer pass and add to the the albedo.

If wnat you want to do is shadow mapping, do it in the lighting pass when you reconstruct the pixel postion

---
Tags: xna, c#, deferred-rendering
---


# Question
Title: [2D] Finding largest possible straight lines around body
I've got a 2D-map, largely consisting of rectangular tiles, but with some none-rectangular objects mixed in as well (tilted lines on corners for example).

Take this image as an example:

I now need all the largest possible (straight) lines around the two bodies inside that map. There are no additional required attributes to the lines.

In this image, I've marked the lines that I'm trying to find, each one with a different color to make sure there are no confusions:

It's important however, that the algorithm doesn't produce lines inside those two objects, as it would be a waste of resources.

Are there algorithms suited for that or will I have to research an algorithm myself?

By the way, the algorithm will run at loading-time of the game, so it doesn't need to be optimized for runtime-speed. Also, principally, an algorithm that is just able to find the lines around bodies which consist only of square or rectangular tiles would suffice as well.

# Answer
If you're dealing with discrete positions (eg. a tile-map or pixel based map), then an easy way to find the contours would be the Marching Squares algorithm (Wikipedia).
> 1 votes

---
Tags: 2d, tilemap
---


# Question
Title: How to calculate falling and accelerating velocity?
I'm thinking of making a lander game, where you control a spaceship and need to land it without crashing. What is a simple formula to calculate speed of falling or acceleration with relation to working time to time engines?

# Answer
> 28 votes
The simplest way is the Euler integration. You have to store position vector and velocity vector. At each frame:

* measure the time passed since the last integration step: *dt*
* compute the force vecor due your engines: **F**
* compute the acceleration vector: **A** = **F**/*m* where m is the spaceship mass.
* add the gravity vector: **A** = **A** \+ **G** make sure that **G** points toward the planet's center
* update the velocity vector **V** = **V** \+ **A**·*dt*
* update the position vector **X** = **X** \+ **V**·*dt*

(*x* for scalars, **X** for vectors)

be sure that *dt* is small...

|**G**| is about 9.8 m/s² for earth and about 1.6 m/s² for moon

in general the actraction Force due the gravital interaction is:

It affects each body and it points toward the other one.

The *G* scalar is the very famous *Gravitational constant* it is about 6.67e-011 N(m/Kg)²

Since you are interested in acceleration:

You only need to know the planet's mass (m2) and radius (r) to compute your acceleration.

Typically the acceleration that moves the planet toward your spaceship is negligible because usually m1 is negligible compared to m2.

However, if you are trying to land to a small asteroid you probably have to use the general formula adding that force to the total force vector in the second step.

**EDIT:**

As required some hint on implementation. You will need:

* A vector library
* Engine Model
* Phisics Model
* Collision Detection
* User Interface (input and graphic rendering)

First of all the vector library: your game can be mono/bi/tree/four... dimentional, as far as you consider your case to be a projection of a 3D word, the physical roules hold.

If n is the dimension you choose (probably 2 or 3 in your case), the library must have:

* a vector storage entity (a list of n floating point numbers for each vector)
* a sum operator (sum component by component)
* a scalar multiplication operator (each component multiplied by a float)
* a dot-multiplication between vectors (multiplicate component by component and sum up all)
* the vector length (square root of a vector dot-mutiplied by itself)

You can use a library that does this or implement one by yourself; a vector can be a struct or a class, the choice is yours.

Each engine should be described by:

* a vector indicating its thrust strength and direction
* a scalar that indicates the fuel usage per second when on full power;

your user input will be used to provide to each engine a number that will be between 0 (unused engine) and 1 (full power): the engine (usage) factor.

Multiply the engine factor for its thrust vector to obtain the engine real trust and sum up all the results of all the available engines; this will give you the **F** of the second step.

Your engine factor can be used to know the real fuel usage for each engine: multiply the engine factor by the fuel usage and by *dt* to know the instantaneous fuel usage; you can substract this value from the total fuel capacity variable (this gives you the opportunity to update your total mass *m* if the fuel mass is considerable).

Now you can proceed using the integration to compute the new position, check for the collision with your planet surface; if any, use the length of the velocity vector to say if the landing was a success or a disaster.

Obviously other collision checks can/should be made, some surface entities cant be allowed as landing point so every collision is a fatal one.

I leave how to get input and how to render your spaceship to you; you can use the engine factor to render the engine status frame by frame, for example.

# Answer
> 7 votes
As the other excellent answer seems a bit theoretical, here's the simple code version:

```
// Position of the lander:
var positionX =  100.0;
var positionY = 100.0;

// Velocity of lander
var velocityX = 0.0;
var velocityY = 0.0;

// Acceleration due to gravity
var gravity = 1.0;

// If the player is pressing the thrust buttons
var isThrusting = false;
var isThrustingLeft = false;
var isThrustingRight = false;

// Thrust acceleration
var thrust = -2.0;

// Vertical position of the ground
var groundY = 200.0;

// Maximum landing velocity
var maxLandingVelocity = 3.00;

onUpdate()
{
    velocityY += gravity;

    positionX += velocityX;
    positionY += velocityY;

    if (isThrusting)
    {
        velocityY += thrust;
    }

    if (isThrustingLeft)
    {
        velocityX += thrust;
    }
    else if (isThrustingRight)
    {
        velocityX -= thrust;
    }

    if (positionY >= floorY)
    {
        if (velocityY > maxLandingVelocity)
        {
            // crashed!
        }
        else
        {
            // landed successfully!
        }
    }
}

```

# Answer
> 2 votes
Unfortunately, the math here gets hairy. FxIII's answer is fine for the general case of a falling object but you are talking about a rocket--and rockets burn off fuel.

I have seen code that does it but it was completely undocumented and I never managed to figure out the math behind it. Unless you're CPU-limited somehow I wouldn't bother and simply brute force it--FxIIIs approach applied on a quite short timescale and adjust the thrust (or fuel use if you figure the rocket throttles back as the fuel burns off to maintain the specified acceleration rather than the specified thrust) between each iteration as the rocket burns off fuel.

---
Tags: physics
---


# Question
Title: A solution for developing a web game client for iphone and ipad…
We have just finished developing a web game using flex + flash + python and now we want to make a client app for the iphone/ipad device just like this one

Since we have had no such experience I hope someone has done this might give us some hint or suggestions.

PS:I got some advice from other websites saying that I can do it as follows: 1.Re-write those as script (logic stuff) with objC (I agree with this) 2.Use html5 (which I do not understand quite well, does this mean that I need to re-write those MXML files with html5?)

Thanks in advance.

# Answer
Re-write the app in Objective-c would be a better choice, if you want performance.

If you want to port it to Android as well, then you might want to take a look at other solutions such as Corona SDK, Unity or Monkey.

If you are not comfortable using Objective-C, Corona SDK should be a better choice. The structure is similar to flash display object list, so it should be easier for Flash developer to understand. You also have a choice to deploy it to Android later if you want to.
> 2 votes

---
Tags: web
---


# Question
Title: Is there a way of using XNA+Xbox 360 with the current generation of 3D televisions?
I'm interested in playing around with 3D on a new Sony 3D television (polarized light rather than red/green/blue anaglyph glasses). Is this possible with XNA on the current XBox 360?

Alternatively, It doesn't look like there is a comparatively trivial PS3 dev. solution to XNA right now, hence my interest in XNA and the 360.

Regards,

# Answer
Check if you can manually set your 3D TV to the type of 3D input it's receiving. A quick look at one Sony 3D TV manual showed it could be manually set to generate the 3D image from either side-by-side or over-under images, where the content for the two eyes are provided in one extra wide or extra tall image.

It's possible if you can create a frontbuffer of the right size then you can just render two images in this way and set your TV to look for it (seem to recall this might be how Avatar the game did it on the 360). Your content would then potentially be rendered correctly, but the 360 guide or pop-ups that get overlaid by the system would be displayed incorrectly until XNA officially supported 3D.
> 3 votes

---
Tags: xna, 3d, xbox360
---


title: Aquaria-like graphics look in 3DS Max?

text:
# Question
Title: Aquaria-like graphics look in 3DS Max?
I'm making a 2D game and I'm starting to think about graphics. I'm pretty good at 3D modelling, but I'm not very good at drawing or painting. I was wondering if there were settings, or even a renderer that someone could recommend that could achieve the nice painted look found in Aquaria.

Thanks.

# Answer
What you're looking for is something along the lines of "painterly rendering" or "cel shading," probably. Both of these are subsets of the space of non-photorealistic rendering techniques. The majority of the information on these rendering techniques can be found in academic papers or books. There doesn't appear to be a wealth of Max plugins that provide NPR effects:

You can find more information by searching for "nonphotorealistic rendering," "painterly rendering," and "cel shading," although you're more likely to find academic papers discussing the techniques. There are a few threads on various CG forums talking about ways to use Max to do NPR, and Autodesk appears to have a few classes on the subject (behind paywalls, so you'll have to browse their site directly). There's also this YouTube video of a SIGGRAPH class from 2009 on the subject.
> 2 votes

# Answer
Unless you really want to have real 3D models, just convert them to 2D images. You could use an art pipeline something like this...

1. Create 3D models of desired objects
2. Take screenshots (save renders)
3. Post process via filters and other FX in Photoshop to create desired effect
> 1 votes

---
Tags: graphics, art, non-photorealistic
---


# Question
Title: How to design and implement turn-based system?
> **Possible Duplicate:**
> How to implement turn-based game engine?

I am considering making a game like Master of Orion but I don't know how to start with turn-based systems. If any of you played this game they know what I mean, same system is used in Civilization. 1. You give orders to your units and production queues 2. Click End Turn. 3. Everything moves, go to 1.

I know that some form of state machine is used, but maybe you could point me into some book or manual on the matter.

# Answer
> 21 votes
It's worth pointing out that there are really two kinds of "turn-based" systems. There's the true turn-based system, and there's the immediate-mode hybrid.

In a true turn-based system, you come up with a set of orders, but nothing actually *happens* until you push the "end turn" button. There's no combat, there's no production, there's just you laying out orders for what you think should happen during that turn. For examples, look at the PC game Dominions III, and the classic board game Diplomacy. In games like this you never have to ask questions like "which unit should attack first this turn" because there is no "attack first" concept - everything occurs simultaneously. This is also the genre that's amenable to play-by-email. Every player makes their orders, every player hits "go", every player looks at the new turn with dismay as their entire plan collapses due to everyone else interfering.

In the weird hybrid mode, generally unit movements and combat happen "immediately". Generally you can buy units, and that also happens immediately. You can say things like "I'll attack this force, and if I lose, I'll buy reinforcements before the next turn". Eventually you run out of action points and you have to hit end-turn, at which point it does end-of-turn effects like healing, resource gathering, and also lets other players take their turn. This is often known as "hot-seat play" because each person can do their turn in a row, but has to sit there waiting for the other players.

In the first case, it's pretty simple. Each unit, building, and city keeps information about what its next move is. When you hit end turn everyone carries out their orders - you just run the simulation, in whatever manner your simulation requires to run.

In the second case it's also pretty simple. Some units (generally buildings) have orders, but most units just do what you say, immediately, often with a pretty little animation. You'll need to keep track of when they have to stop doing things.

If you want more than that, you'll have to tell us what you're having trouble with. :)

---
Tags: turn-based-strategy
---


# Question
Title: Determine arc-length of a Catmull-Rom spline to move at a constant speed
I have a path that is defined by a concatenation of Catmull-Rom splines. I use the static method Vector2.CatmullRom in XNA that allows for interpolation between points with a value going from 0 to 1.

Not every spline in this path has the same length. This causes speed differences if I let the weight go at a constant speed for every spline while proceeding along the path. I can remedy this by letting the speed of the weight be dependent on the length of the spline. How can I determine the length of such a spline? Should I just approximate by cutting the spline into 10 straight lines and sum their lengths?

I'm using this for dynamic texture mapping on a generated mesh defined by splines.

# Answer
> 26 votes
It sounds like you want to keep the speed of the object at some constant value over the entire curve - knowing the arc-length won't help you do this. It will help you calculate at what time the object would reach its end-point *if* it were going at that speed, so it will be better than what you have now (the object will have the same average speed between all points), but the actual speed of the object will still vary as it moves around the curve.

A better solution would be to change our parametric parameter *(the parameter that goes from 0 to 1, which I'll call `s` to avoid confusion with `t = time`)* at a variable-rate `ds/dt`, which is determined by what speed you want the object to be moving at that point on the curve. So in other words, instead of changing `s` by 0.01 each frame, we might change it by 0.005 one frame, 0.02 the next, etc.

We do this by calculating the derivatives of `x` (`dx/ds`) and `y` (`dy/ds`) each frame, then setting

```
ds/dt = speed / sqrt( (dx/ds)<sup>2</sup> + (dy/ds)<sup>2</sup> )
```

That is, by taking the speed we want to go, and dividing by the speed we'd actually be going if we were changing `s` at a fixed increment.

---

## Proof

We want the speed of our object to be constant; let's give that constant the name `speed`.

We learn in second-year calculus that, for parametric equations `x(s)` and `y(s)`,

```
speed = sqrt( (dx/dt)<sup>2</sup> + (dy/dt)<sup>2</sup>)
```

We also learn that

```
dx/dt = dx/ds * ds/dt    *(chain rule)*
```

Thus,

```
speed = sqrt( (dx/ds)<sup>2</sup> (ds/dt)<sup>2</sup> + (dy/ds)<sup>2</sup> (ds/dt)<sup>2</sup> )
```

Solving for `ds/dt`, we get the stated equation.

---

### Calculating the derivatives

I've never worked with those particular splines, but I understand they just give `x(s)` and `y(s)` in terms of cubic-equations of `s`. Thus, we can find the derivative `dx/ds` easily: if

```
x(s) = a*s<sup>3</sup> + b*s<sup>2</sup> + c*s + e
```

then

```
dx/ds = 3a*s<sup>2</sup> + 2b*s + c
```

*(Same for `dy/ds`)* Of course, you'll need to know the exact values of `a`, `b`, and `c` to do this. According this this page, those values are easy to find.

---

Finally, to answer the question in the title: finding the arc-length equation of a parametric function involves solving a fairly complicated definite integral; even for the simple case of a cubic-equation, this can't generally be done.

Thus, you'll have to estimate the integral numerically. *"Cutting the spline into 10 straight lines and summing their lengths"* as you suggest is one very simple way of doing this; however, there are slightly more complicated methods that will give you much more accurate results using fewer line-segments.

---
Tags: xna, mathematics, vector, splines
---


# Question
Title: Obtaining a certain type of object with component based design
I'm trying to design my game to be component based rather than overly hierarchical. Essentially, every high level object in the game (like gun, or whatever) inherits and implements the interfaces that it needs. For example, IPhysics, IRenderable, IWeapon, etc.

There are a few cases where I'm uncertain how to obtain a specific interface from another.

For example. A Gun might inherit from IWeapon, IPhysics, and IRenderable. I then also have a player which inherits from IPlayer, IPhysics, and IRenderable. I need a way so that, when Player and Gun collide, if Player is not currently wielding a weapon, he should be able to wield the gun and hold a pointer to the IWeapon of the Gun.

Right now, when Box2D detects a collision between 2 fixtures, I use the UserData field to store the IPhysics pointer associated with the fixture, and therefore, the IPhysics.beginContact method is invoked.

From here, the Player needs to somehow be able to know that this is a weapon, and obtain an IWeapon\* . This is the part I really have no idea on.

Any advice on solving something like this is appreciated, even if it means some kind of design change on my part. I'm just looking for a clear way on how to solve this sort of problem.

Thanks

# Answer
> 5 votes
Updated to the new specifics of the question

> For example. A Gun might inherit from IWeapon, IPhysics, and IRenderable.

This is not a component system. This is not to say its not a bad system, but in this case you should be able to cast the pointer to any of the interfaces (or just cast it to a Gun object and it should Contain the interfaces) and then use it as appropriate.

As for determining what kind of object it is that the player has collided with, you can attempt to use the internal RTTI abilities like dynamic\_cast\<\>() or potentially implement your own RTTI (Run Time Type Information) system and add in an IType object to query if an object is of a specific type or to return the type that it is, etc. Once you validate the type you can safely cast it as desired.

If you do have a component system and we are just not meshing on nomenclature, then just leave me a comment and explain how the components are related to each other. Often this is done by an ID of the object they are a part of.

Hope this Helps

# Answer
> 2 votes
If all your objects implement interfaces (Rather than being a set of components), all you have to do to get the IWeapon from the IPhysics is cast it. In C++, a dynamic cast will return null if the object doesn't inherit from IWeapon. In C#, 'as' will return null if the object doesn't implement IWeapon. Your mileage will vary in other languages.

But I wouldn't call this method of creating game objects a component-based system.

---
Tags: c++, game-design, architecture
---


# Question
Title: How can I let a player post their score to Facebook at the end of the game?
I have an HTML5 game on my site, and at the end, I want the user to have the option of posting their score to their Facebook wall. Is there an easy way to ask to post something to Facebook?

# Answer
You don't kneed to place a log-in button, and you don't need to set permissions. I found this Stack Overflow question that explains a quick way to do it just in javascript. The user is asked post the item to their wall, and they can either add a message and post or just skip it.
> 4 votes

# Answer
You can use the Facebook Graph API for that purpose (there are several SDKs available).

These are roughly the things you need to do:

* Create an app on Facebook. You can do this here. There you'll get your APP and API Keys that are needed for you to communicate with the Graph API.
* If your app wants to post to somebodies wall, he/she needs to grant your app that permission. For that you'll need authentication, specifically your app needs to ask for permission to write the users stream (`publish_stream`)
* If the user granted you permission, your app can then publish to his wall using the Graph API (read the section titled *Publishing*). If the user doesn't grant you permission, don't nag any further :)
> 6 votes

# Answer
To post on the user's wall, first register the app with Facebook. Set it up as a webpage app, even though it will be on your website and not theirs.

Now you can put a button on your site that will log the player into Facebook and then the game can post messages on their wall.
> 1 votes

---
Tags: facebook, leaderboards
---


title: Most common 3D model format for opengl

text:
# Question
Title: Most common 3D model format for opengl
I'm a novice that is starting to play with OpenGL ES on Android devices. To practice OpenGL I wanted to create a small game engine and so I was wondering what the best 3D model file format would be.

I'm also interested in free models of the same format.

What do you suggest?

# Answer
> 11 votes
There are two that are really easy to use. First is wavefront (.obj) http://en.wikipedia.org/wiki/Wavefront\_.obj\_file and the second is stanford (.ply) http://en.wikipedia.org/wiki/PLY\_(file\_format)

Both store data in normal text/ascii format so you can read the content in a normal text editor which will help you understand the content and how to read it.

There are more advanced and methods that supports more functions (animation, skinning etc), one of those is the Collada which is developed by the khronos group

# Answer
> 2 votes
The file formats does not depend on the graphics API. For OpenGL, the simplest and most commonly used format is the \*.OBJ, or the \*.3DS. It's easy to find on the web loaders for these files. Free models (and even) commercial model packs use these formats. The 3D modeller softwares can export to these formats too. (3ds max, blender, milkshape, etc).

---
Tags: opengl, 3d, models
---


# Question
Title: How to extend Tiled and Cocos2d to create an Isometric map that supports elevation
I've been looking and looking and looking, and I cannot seem to find a solution out there for making a game that uses cocos2d and Tiled to make an isometric map that supports elevation.

I am not looking for anything super complex...

Just maybe 2 or 3 levels of elevation. (Think X-Com UFO Defense, or Final Fantasy Tactics)

I figure that since I've been unable to find a solution, I'll probably have to extend Tiled or something to support this.

For now I'll just stick with level of elevation, but I want to extend the game to support elevation eventually.

**Will you share with me any good resources that you know? Where should I read to better understand how to accomplish such a thing?**

# Answer
> 3 votes
I just opened Tiled and saw that there's support for multiple layers. So you could even build multiple ground-levels inside Tiled.

For different height-levels, you probably won't need the multiple layers at all. You could build that just by using special tiles, something like shown here or here. The type of tile would also denote the height. If you have special areas like a ramp that maybe spans across several tiles, you can use the "objects" in Tiled to add such metadata to your map.

It's basically the same approach as you would add walls in an isometric game.

---
Tags: cocos2d-iphone, isometric, tilemap
---


# Question
Title: Options available to a programmer on the Main Game Loop
Could someone please give me some insight into each one of the four topics listed below.

I have a good idea about what passive and active rendering are, and that the use of active rendering is more suitable for games programming.

I'm just not to sure about the rest.

---

The timing of the main game loop is an important component of any computer game, since it impacts on the frame rate and the real-time physics calculations needed to make the game run at a realistic (or at least playable) rate. You are required to read up on the programming issues that affect this timing, and write a report that covers the range of options available to a programmer. Your report should consider the following headings:

1. The distinction between active and passive rendering, and an explanation of the preferred mode for a game program.
2. The division of time between the physics (or game-model) update and graphics update stages, and an explanation and analysis of the relative importance of these in a game that involves real-time physics calculations.
3. Techniques for achieving accuracy in real-time physics, and an explanation of the trade-offs that may be necessary to do this.
4. Programming techniques that can be used to try to keep the frame-rate for graphics updates to some desired rate.

# Answer
> 2 votes
I've seen this question asked elsewhere; I can't remember where. A response gave this link:

http://gafferongames.com/game-physics/fix-your-timestep/

It describes the advantages and disadvantages of different techniques for calculating time, and how to sync graphics and physics updates when they run at different rates. It's very well written and provides code samples.

---
Tags: physics, graphics, game-loop, frame-rate
---


# Question
Title: Problems making my basketball bounce around horizontally
This is probably a very easy question, but I can't seem to understand why it's not working.

I want the basketball to bounce horizontally when it touches the borders on the right and left, but when it bounces on the right, it seems to go just a *little* bit further than it should.

Any suggestions?

```
protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    basketballPosition.X += ballSpeed;
    if (basketballPosition.X > Window.ClientBounds.Width - basketball.Width || basketballPosition.X < 0)
    {
        ballSpeed *= -1;
    }

    base.Update(gameTime);
}

```

And my Draw method:

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();

        spriteBatch.Draw(basketball,
                         basketballPosition,
                         null,
                         Color.White,
                         0,
                         Vector2.Zero,
                         1.5f,
                         SpriteEffects.None,
                         0);

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

---

**Edit** The problem was I was using a scale of 1.5f for drawing the image. Can someone explain how I would get the true border of the image if I were using scale? It seems the border stay as the original size, but the texture is drawn to whatever scale I choose.

# Answer
> 12 votes
Since your ball is scaled, it means that using the texture's width (`basketball.Width`) is not correct, since the *real* width is the texture's width times the scale.

Your code would change like this:

```
if (basketballPosition.X > Window.ClientBounds.Width - (basketball.Width * 1.5f) ||
    basketballPosition.X < 0)

```

This is because supplying a scale parameter different than `1.0f` to `spriteBatch.Draw` has the effect of modifying how the image is *drawn*, it does not change its stored width and height however.

So, you have to keep in mind when using the width of a texture that you're using the width of the original image, not the scaled one.

You simply need to scale the width and height whenever appropriate. In this case you want to know when the **drawn** right border of the image goes too far on the right, so you need the scaled width.

---

**A suggestion to clean the code a little bit...**

Keeping magic values isn't always nice, so you might want to make a class out of that basketball:

*Note: I have not tested the code below, but you get the general idea.*

```
public class BasketBall
{
    Texture2D texture;
    public Vector2 Position { get; set; }
    public float Scale { get; set; }
    float ballSpeed;

    Rectangle screenRectangle;

    /// <summary>
    /// Returns the scaled bounding rectangle of the basketball.
    /// </summary>
    public Rectangle BoundingRectangle
    {
        get
        {
            return new Rectangle((int)Position.X, (int)Position.Y,
                (int)(texture.Width * Scale), (int)(texture.Height * Scale));
        }
    }

    public BasketBall(string assetPath, Vector2 startPos, float scale, float startSpeed,
        Rectangle screenRectangle)
    {
        texture = Content.Load<Texture2D>(assetPath);
        Position = startPos;
        Scale = scale;
        ballSpeed = startSpeed;
        this.screenRectangle = screenRectangle;
    }

    public void Update(GameTime gameTime)
    {
        Position.X += ballSpeed * gameTime.ElapsedGameTime.TotalSeconds; // multiply by delta seconds for consistent behavior on different machines

        // Much more straightforward now. The scaling happens when calling BoundingRectangle
        if (BoundingRectangle.Left < 0f || BoundingRectangle.Right > screenRectangle.Right)
        {
            ballSpeed *= -1;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Begin();

        spriteBatch.Draw(texture,
                         Position,
                         null,
                         Color.White,
                         0,
                         Vector2.Zero,
                         Scale,
                         SpriteEffects.None,
                         0);

        spriteBatch.End();
    }
}

```

So much cleaner to use imho:

```
BasketBall basketBall;

```

When you load its content:

```
basketBall = new BasketBall("basketBall", Vector2.Zero, 1.5f, 50f,
                            new Rectangle(Window.ClientBounds.X,
                                          Window.ClientBounds.Y,
                                          Window.ClientBounds.Width,
                                          Window.ClientBounds.Height));

```

When you update it:

```
basketBall.update(gameTime);

```

When you draw it:

```
basketBall.draw(spriteBatch);

```

If you do prefer the no-class version, then I'd recommend at least keeping a `Vector2` showing the scaled measures of the sprite, for cleaner calculations. Also, a constant for the scale would be nice. Like so:

```
const float BALL_SCALE = 1.5f;
Vector2 basketBallMeasures = new Vector2(basketball.Width, basketball.Height) * BALL_SCALE;

```

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


# Question
Title: How to handle re-rendering a scene in my custom game engine?
I have a very simple game engine. A `GameObjectManager` stores a collection of all the `GameObjects`. When I want to render, I just call `GameObjectManager.render()` from the rendering context.

This works well for rendering most objects, but now I am looking to add a water shader to the scene where it takes in reflection and refraction textures. The reflection and refraction textures will be computed each frame by re-rendering the scene from a new perspective. Unfortunately, my design choice of having a single `GameObjectManager` to store all `GameObjects` just won't work for this - it wouldn't make sense to store a `GameObject` for the water in the `GameObjectManager`.

What is a good game engine design pattern to handle re-rendering the scene for an effect such as a reflection?

# Answer
> 2 votes
Your current approach should be fine for this.

All you need to do is to have the reflective object hide itself, before performing the reflection render. This is typically done by having it clear a "IsVisible" flag on itself, before starting the reflection render.

Now, if you wanted to have objects which didn't reflect their surroundings, but instead showed elements from a different scene (say, a television screen showing a part of the next level), at that point it might be worth thinking about not having only a single GameObjectManager, and instead having one per discrete scene. But if all you're considering are reflections within a single scene, then a single GameObjectManager should be able to do everything you need.

---
Tags: architecture, rendering
---


title: XNA and Matrix.<whatever>

text:
# Question
Title: XNA and Matrix.<whatever>
I am not new to XNA 2D programming, but have never done 3D. I am interested in learning, but always get lost once I get to creating a Matrix.

I am sad to say that I don't really get them. Can someone explain, (or even just point me to a good tutorial) on getting started with matricies?

I understand them from a math point of view, but I don't really get the API. How do you use the API? What is the difference in CreatePerspecitive, and CreatePerspectiveFieldOfView. I am really looking for information in understanding when to use the different members the API provides.

I know this question is a little vague, and large, so I will try to edit it as needed.

# Answer
Not sure which aspects of Matrix math you're having difficulties with, so I'll list two books that helped me get over the 3D math hump. Chances are, you'll need to work through more than one book to get everything to finally "click".

1. 3D Math Primer for Graphics and Game Development This is a great book, everything is explained thoroughly and in a language that's easy to understand. I would start here.
2. Mathematics for 3D Game Programming and Computer Graphics Another good 3D math textbook. Covers a wide range of material. It's concise and straight to the point.

I would start with these, even if you have to re-read the material a couple of times. I spent months going over 3D math topics before being comfortable with it.

EDIT: I posted this before you updated your question. If you're looking for help directly with how to use Matrices in XNA, check out XNA Game Studio 4.0 Programming: Developing for Windows Phone 7 and Xbox 360 by Tom Miller & Dean Johnson (can't link, due to spam prevention, but it's on Amazon). Chapter 4 goes into the very basics of 3D Math and directly relate to the math classes in XNA. You'll probably learn a lot from the code samples in the later chapters as well.

EDIT 2: Another book that I recommend as well is Microsoft XNA Game Studio Creator's Guide. While this only covers XNA 3.0, the majority of it is still applicable to XNA 4.0. It not only has a chapter on Matrix math, but on creating a graphics engine camera system that shows great use of Matrices in XNA. I think you'd take away a lot from that sample.
> 3 votes

# Answer
I found that Riemers 3D XNA tutorials were great for picking up the basics on the matrices and how to use them specifically in an XNA environment. The second tutorial makes a simple flight-sim so it also has a fair amount of instant gratification.

Here's a link to the first one, the navigation links are on the right side (something that threw me at first): http://www.riemers.net/eng/Tutorials/XNA/Csharp/series1.php
> 1 votes

# Answer
I wrote a tutorial to specifically help with this :-) It explains the concepts using Sunburn for XNA.

http://dsebj.evolvingsoftware.com/?p=211 \[Matrix Math is Hard?\]
> 1 votes

---
Tags: xna, 3d
---


# Question
Title: Why must the transpose value of glUniformMatrix4fv in webgl/OpenGL ES be false?
Why must the transpose value of glUniformMatrix4fv in webgl/OpenGL ES be false?

The OpenGL ES spec says that the transpose value must be false or an INVALID\_VALUE is generated. Why then have the parameter?

# Answer
> 7 votes
The parameter exists because the OpenGL ES spec conforms to the OpenGL spec : OpenGL ES 2.0 is defined relative to the OpenGL 2.0 specification

In the OpenGL spec, this parameter exists hence it also exists in the OpenGL ES spec, even if it is unused.

# Answer
> 11 votes
Because OES is a subset of standard OpenGL, and the functions must have the same parameters in both implementations. In OpenGL the parameter *transpose* is used to specify if the matrix is in row-major or column-major order, but since OES only supports column-major, it must be always false.

---
Tags: opengl-es, webgl
---


# Question
Title: Programming a climbing system like tomb raider
I was wondering if anyone knew or had knowledge of how to program a climbing system like the one found in tomb raider/uncharted.

I had thought of just having bounding boxes at all the climbable positions in the game world and then check for collision. If the player was inside the box then they would be "hanging" from the edge. Anyone have any better ideas/improvments?

I already have my rendering set up using directx9 and was going to worry about animation later on.

# Answer
> 4 votes
Valve's 2009 presentation on the AI systems behind Left4Dead goes into considerable detail on the system used for climbing, including ledge detection, obstacle height, animation selection etc.

It is mostly aimed at NPC animation, but most of the actual climbing code should be very similar.

---
Tags: c++, game-mechanics, level-design, game-design
---


title: Strategy Games Online Resources

text:
# Question
Title: Strategy Games Online Resources
I am looking for some good online (ebooks) resources about strategy games discussing the gameplay and the interactive aspects of strategy games, and how to design interesting and challenging strategy game.

I found this book (http://www.amazon.co.uk/Game-Guru-Strategy-Dave-Morris/dp/1904705456) and seems interesting by reading table of contents. Unfortunately, I did not find any way to buy an ebook version of it and I am in Middle East and ordering this book would take lots of time.

Any idea?

# Answer
> 2 votes
If you haven't read it already try The Art of Game Design by Jesse Schell. It's available for Kindle and very good, but not specific to strategy.

I publish books and ebooks for game developers so if you have a clear idea of what you want please post the idea here: http://www.google.com/moderator/#16/e=7d41d

# Answer
> 2 votes
You can try to contact the publisher, and ask them directly. Google Books states the publisher is "Thomson Course Technology".

This page says they were renamed to "Cengage Learning", it also has all contact information, so you can just call or send an email to ask them directly for their ebook offers.

---
Tags: game-design
---


title: Casual games market share distribution?

text:
# Question
Title: Casual games market share distribution?
I'm interested in how the market of casual games is split up between different platforms, both in terms of revenue as well as "amount of games published".

For example, I think that Facebook and iPhone games should make a quite large percentage of the market, Facebook alone due to the \*Ville games.

Does anyone of you know of one or several articles on market research in that area? Or some simple web page which lists statistics?

# Answer
> 5 votes
In general, this information is quite valuable and (for casual games in particular) difficult to extract via data mining. Unfortunately this means you will likely have to pay for it if you want any kind of real details.

The Casual Gaming Association has some market research available for purchase. The Park Associates group does game market research (example study available here). Here is a collection of video game market reports, some of which may be relevant.

The NPD group is one such market research firm that provides some of their data to the public for free (but they still sell a fair bit of it). This wiki has a nicely categorized collection of their sales figures for example (since the NPD site itself can be a chore to navigate for real data). But the freely-available stuff is likely not going to be as well-separated as you want, so you probably can't extract much in the way of data to answer your questions about casual games. The NPD group also focuses mainly on retail distribution, which will exclude most casual games entirely.

Casual games present a particularly difficult challenge for market analysts and researchers because many such games exist in proprietary channels that are difficult to do data mining on, especially in a homogenous fashion (Steam is different than Facebook is different than some Flash web portal; everybody may use slightly different payment processors; sales of some casual games go to individuals and not neccessarily companies, so access to information on those apparently-interpersonal transactions may be more restricted; et cetera).

You can try your luck searching for "casual game market research" or "casual game market share." If all you really want is a rough high-level breakdown, perusing some of the articles from the latter query may give you what you need.

---
Tags: casual-games
---


# Question
Title: Insert object at index, when two objects collide
I have two arrays: one for projectiles, and one for targets.

Every target and every projectile has tag, and a tag with color (source code I took from Ray Wanderlich).

In my small game, when a projectile collides with a target I compare their tags, if the tags are the same I delete the projectile and target, but if they are not I want to insert projectile at the position of the target (with which the projectile collided) and make the other targets shift right or left.

Some code:

```
NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
CCSprite * projectile;
for (projectile in _projectilesArray)
{
    CGRect projectileRect = [projectile boundingBox];

    NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
    CCSprite * target;
    for (target in _targetsArray)
    {
        CGRect targetRect = [target boundingBox];

        if (CGRectIntersectsRect(projectileRect, targetRect))
        {
            if([target tag]==[projectile tag])
            {
                [targetsToDelete addObject:target];
            }

            if([target tag]!=[projectile tag]) /* <-- _HERE IS MY PROBLEM_ */
            {
                NSLog(@"-");
                [targetsToDelete addObject:projectile];
            }
        }
    }

    for (CCSprite *target in targetsToDelete)
    {
        [_targetsArray removeObject:target];
        [self removeChild:target cleanup:YES];
    }

    if (targetsToDelete.count > 0)
    {
        [projectilesToDelete addObject:projectile];
    }
}

for (CCSprite *projectile in projectilesToDelete)
{
    [_projectilesArray removeObject:projectile];
    [self removeChild:projectile cleanup:YES];
}

```

# Answer
> 1 votes
Isn't this a simple programming problem?

Change your `for in` loop to a standard `for` loop, then in your problem area use `[targetsToDelete addObject:*something* atIndex:*i*]`

---
Tags: collision-detection, iphone, cocos2d
---


title: Steam Submission Times

text:
# Question
Title: Steam Submission Times
I was wondering if anyone has released or tried to release on Steam and how much time it took Steam to respond to your game submissions, I cant find any info about it on their website and its been over a month now since I have submitted and have yet to even get a confirmation email.

Is this to be expected from sources such as these? Ive sent them two emails so far at 3 weeks apart and have to make a decision on what to do with the game and can not wait much longer.

# Answer
I'm already on Steam and it can be hard to get a reply from Valve sometimes. They also have a LOT of turnaways - and their policy is to not tell you why. Which kind of sucks.
> 7 votes

---
Tags: steam
---


# Question
Title: Why should I not use glTools/glut when developing complete applications?
I've started learning how to use OpenGL a while back, using the *OpenGL SuperBible, Fifth Edition*, and I've had people arguing about the fact that the book doesn't really teach how to use OpenGL but instead it teaches how to use two of the wrapper libraries related to it, glut and glTools.

I've also been told that glut should never be used for full-blown projects, but there was no valid reason supplied with the argument.

My question is why, and when should I not use the glTools/glut libraries, and what should I use instead?

# Answer
GLTools and GLUT are not the same thing. GLUT is responsible for dealing with things outside of OpenGL. GLUT creates and manages a window and an OpenGL context; the actual stuff that goes on within that context (aka: OpenGL) is not GLUT's responsibility.

Maik already covered the reasons why you don't see GLUT in serious applications. GLTools is another matter.

GLTools is just a framework, a wrapper around OpenGL stuff. There are many reasons not to use it in serious work:

1. It's inefficient. If performance matters, you're going to want to sidestep it.
2. It's not very good. Take the GLShaderManager for example. It either loads the shaders or returns 0. If there is a compiler/linker error, it gives no information on this. Yes, it writes the log to stderr, but not everyone has stderr piped to somewhere that is visible. Exceptions are rather harder to ignore.

---

> I've had people arguing about the fact that the book doesn't really teach how to use OpenGL but instead it teaches how to use two of the wrapper libraries related to it

This is an aside, but generally the problem with regard to this is quite simple. 5th teaches you to use the framework *before* explaining what that framework is doing. So you learn how to use its mesh loading, how to use its perspective matrix generation code, its default shaders, etc, all *before* learning what a shader is, what vertex attributes are, and so forth.

It's basically fixed-function programming for the first part of the book. It just uses its own fixed-function code rather than OpenGL's.

It's not that it uses a framework that's the problem. The problem is that it uses the framework to hide details that haven't been explained, rather than to hide details that are unimportant to the current lesson. After you've seen the shader loading code a few times, you don't need to see it again, so it can be a library function.

A better way to structure the book would have been to use the pieces of the framework *after* showing the underlying OpenGL calls that the framework is doing. The standard set of shaders are fine, but it should use them only after the user has seen shaders in action manually. The same goes for mesh loading and handling, textures, etc.
> 8 votes

# Answer
The argument against glut in big projects is that you don't have access to the application loop, so you can't change it to fit your needs. All it has are some callbacks which are triggered from glut, but you don't have much control about it.

However, the purpose of glut is to create demos and test apps easily and cross platform, without the need to deal with ugly OS code to create windows, its just a question of some lines of code using glut.
> 3 votes

---
Tags: opengl, tools, glut
---


title: Minimum Hardware for iPhone Dev

text:
# Question
Title: Minimum Hardware for iPhone Dev
So I'm planning to get into iPhone dev (2D games). I understand that my only real option is to get a Mac. I'll probably go the MonoTouch route.

I'm not sure what hardware to buy; I just want the minimum that'll be "good enough" to develop with. Some posts recommend a Mac Mini, although it seems on the more expensive side; even on the iPhone front, I'm not sure what to look for.

Also, I may skip on the iPhone until I'm ready to launch my first game, since I can get away with the MonoTouch evaluation version. (Albeit that it's probably not the best idea.)

# Answer
> 2 votes
I think you can go with a pretty old & bare bones system. I'm currently using a 5 year old Mac Mini for iOS development with no issue. Currently running OS X 10.6.8.

# Answer
> 1 votes
The cheapest mac you can find that is capable of running Lion (somewhat future proof plan) will allow you to develop for iOS for years to come.

Look at the Apple refurb store if its available online in your country.

# Answer
> 1 votes
I'm doing more than fine with a mac mini 2.53 GHz, the simulator is a bit slow when the game gets bigger, but I recommend you testing on an IPhone anyway.

I remember reading on some forum that everyone recommended getting 4 GB of ram, because OS X use a lot or resources.

---
Tags: iphone, hardware, monogame
---


title: AI for solving a Match 3  game

text:
# Question
Title: AI for solving a Match 3  game
Is there a known good way to have a "computer" opponent play a Match 3 game? It doesn't have to be fancy, or even considered fair. If the AI always takes the best move on the board that would be OK with me. Note that a valid move is one that doesn't make a match.

*Edit:* What I am currently doing is a brute force approach. I look at every tile on the board, and see what the best move that tile can do. I add it to a collection and give it a score (based on how many it will match 3 or 4). Once I have traversed the entire board I use the move with the best score. In the event of a tie I pick one.

If a 5 match combo is found I short circuit out to that one. 5 is the highest combo you can get)

I may not be able to improve it, but it feels like this should have been solved already.

# Answer
> 4 votes
One approach would be a simple tree-search algorithm, similar to the methods used for many deterministic puzzles.

The first problem is that the new gems added with each move are non-deterministic. One way to handle that is to consider all the possibilities for each new gem. This gives a way to estimate probabilities.

The big problem is that the number of combinations to consider would be immense, even a small number of moves into the future. The solution to that is to use heuristics to prune the tree, and to guide the search. For the random gems, only consider a small random selection of the possibilities.

For more tips and more detail, Google for `tree search nondeterministic games`.

http://www.google.com/search?q=tree+search+nondeterministic+games

On second thoughts, try `tree search nondeterministic puzzles`.

http://www.google.com/search?q=tree+search+nondeterministic+puzzles

Also, remember to keep it simple - there's probably *very* rapidly diminishing returns in Bejewelled, either for deeper searching or for more sophisticated heuristics.

# Answer
> 4 votes
Considering Bejeweled doesn't allow you to make a move that doesn't involve a match, couldn't you just figure out all subset of legal moves (you should already have this functionality if you prevent the player from making non-matching moves) and just pick the one that would give you the most points? From my understanding there isn't a *ton* of skill in Bejeweled as you're mostly at the whim of what the random number generator picks for your filler blocks.

Are you trying to design something more complicated like Puzzle Quest where looking ahead actually matters?

---
Tags: algorithm, ai
---


# Question
Title: Efficient data packaging for a client-server network
Language: C++

My question is as follows: I would like to know what would be the best or at least a good way to pack and send data from client to server and the reverse. There will be a few data composing a single packet. A packet will have a "id", that defines what is it for, then the data in a pre- determined order for that "action" which the packet corresponds.

For less performance-dependant systems, i would just send strings, that would be separated by a space, being them the data of the "action"and the first "word" the packet identifier and just chain if statements checking when there is a match.

Now for a more critical system, what i tought so far was something like this:

Make a string with packet id and data, and send it. Then, to unpack, i could extract the first integer in the string, and by having an array of packet handlers, with indices corresponding to the packet id they handle, and just do something like packetHandlers\[packetID\].Process(packetData) .

What do you think of it, any suggestions? greatly apreciated!

# Answer
> 10 votes
First, confirm you actually need a a fancy, efficient protocol before wasting resources developing it. Don't forget debugging/modifying your game will be more difficult and time-consuming due to your fancy protocol. **I would just abstract the network communication away so the actual implementation can be easily swapped for a more efficient one if needed in the future.** Use the simplest protocol possible until you hit performance issues. Another advantage of designing your protocol later is the protocol can be optimized for actual data transported vs. what you predict will be transported.

After confirming you need a fancy protocol, look at protocols that others have spent considerable time developing. Some examples:

* **(update)** The original developer of Protocol Buffers (v2) developed a new protocol called Cap'n Proto. He explains his design decisions and compares to other similar libraries that have recently been released: Cap'n Proto, FlatBuffers, and SBE.
* Google's main bottleneck is network communication between computers, so they probably considered efficiency when developing Protocol Buffers. Gracefully handles forwards/backwards compatibility (*when* you decide to alter your data structures). Used by every major Google product (Gmail, Search, etc)
* Apache Thrift is a similar protocol used by Facebook.
* RakNet is an open-source network library specifically designed for game development.
* ZoidCom is another networking library geared towards game development. It's not open-source, but you can still study it for design hints.

---

> The First Rule of Program Optimization: Don't do it.
> The Second Rule of Program Optimization (for experts only!): Don't do it yet.
> \[Michael A. Jackson\]

In other words: your primary optimization parameter should be: life (years of life per program implementation). \[How to Program Independent Games. Slide 21. Jonathan Blow.\]

# Answer
> 0 votes
Why use two different encoding schemes? Just use the second one for every system. Just keep it simple.
Consider using delta compression. I.e. send one full value and after that only the things that changed. After a few game iterations send a full value again.
Another encodig you could consider is Base 128 Varint. Google Protobufs use it. Have a look at the "Encoding" page of their developer guide: Protocol Buffers Encoding Could save a few bytes.

# Answer
> 0 votes
What might be an example of the data you're sending? I don't see any reason to do anything overly fancy. Once the data is fully loaded into the receiver's buffer, inspect the first `int` based on its value, you then know how to process the rest of the data.

So a packet that has four data parts `id`, `val1`, `val2`, and `val2` might look like this:

```
// I'm using words (one byte) so my sample data is short
00000001 00101000 00010110 00010100

```

As you read the first byte (which you know will always be there) you decide how to process the next set of data. If the first word (id) is `00000001` you know there are three more dwords following, and that is the end of the packet. To continue the example, you might have id = `00000010` and your specification tells you that for id value 2, you process `float`, `float`, `float` in that order, which might specify a player position in world space.

Think of it as writing your own binary file system, you have a header value, which describes the rest of the data, where it is located (what position) and what type of data to treat it as.

---
Tags: c++, networking
---


title: Android Game Dev: Screen Scaling

text:
# Question
Title: Android Game Dev: Screen Scaling
This question is very closely related to a previous question of mine:

Scaling a game view with letterboxes?

My game runs at 480x800 right now but when the screen is smaller or bigger than that I want it to scale up/down the image while maintaining the aspect ratio to fit it as best as it can and then put black letterboxes on the top/bottom or left/right to fill in the left over space if it is of a different aspect ratio. The newly scaled game screen should be centered in the middle of the screen.

I don't know how to go about doing this at all since I want the playfield to be 480x800 because the touch controls use the X and Y coordinates of where the player touches the screen. So I have to figure out how to make it so if the display is centered then the (0,0) coordinate doesnt start in the middle of the letter box but in the top left corner of the playfield where it should be. Also I need to figure out how to make it so when the game is scaled up or down the touch screen controls still work relevant to the new position and scale of the scaled game screen.

I don't know which would be easier, having the game image rendered then scaled up or make it so the gameplay remains the same with object and item positioning but renders a higher resolution image and then have higher resolution image resources rendered on big screens and smaller ones on smaller screens so they're pre-scaled instead of scaled by the hardware or software.

I'm not sure what the best practice is or how to go about doing either method. Please help me out!

# Answer
Usually, when you create a game for multiple displays, you create your game logic with a unit system independant from your display size.

For example, to keep your aspect ratio you can have your game using a 6x10 units, and use the same scale for all you element. Then when moving a game object you always use the same unit system, independant from your display.

Then you have to make a bridge between the display and the game, both in the rendering system (convert game unit to pixels, according to screen size) and in the input system (convert the input in pixels to position in game unit).

Once you've done this, you can focus on your game logic, without having to touch the input and rendering to adapt to different scale.
> 8 votes

---
Tags: game-design, java, android, graphics
---


title: Orienting a model to face a target

text:
# Question
Title: Orienting a model to face a target
I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion). I want the target to rotate and be facing right at the player. The target, when it shoots something should shoot right at the player.

I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100%, and as long as it actually worked.

FYI - Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out.

Code samples run in the Target's class, Position = the targets position, Avatar = the player.

**EDIT**

Im now using Maik's c# code he has provided and it works great!

# Answer
> 21 votes
There are more than one ways to do it. You can calculate the absolute orientation or the rotation relative to your avatar, that means your new orientation = avatarOrientation * q. Here is the latter one:

1. Calculate the rotation axis by taking the cross product of your avatar's unit forward vector and the unit vector from avatar to target, the new forward vector:

```
vector newForwardUnit = vector::normalize(target - avatarPosition);
vector rotAxis = vector::cross(avatarForwardUnit, newForwardUnit);

```
2. Calculate the rotation angle using the dot-product

```
float rotAngle = acos(vector::dot(avatarForwardUnit, newForwardUnit));

```
3. Create the quaternion using rotAxis and rotAngle and multiply it with avatar's current orientation

```
quaternion q(rotAxis, rotAngle);
quaternion newRot = avatarRot * q;

```

If you need help finding the avatar's current forward vector, the input for 1. just shoot :)

**EDIT:** Calculating the absolute orientation is actually a bit easier, use the forward vector of the identity-matrix instead of avatars forward vector as input for 1) and 2). And don't multiply it in 3), instead use it directly as the new orientation: `newRot = q`

---

**Important to note:** The solution has 2 anomalies caused by the nature of the cross-product:

1. If the forward vectors are equal. Solution here is simply return the identity quaternion
2. If the vectors point exactly in the opposite direction. The solution here is to create the quaternion by using avatars up axis as rotation axis and the angle 180.0 degrees.

Here is the implementation in C++ that takes care of those edge cases. Converting it to C# should be easy.

```
// returns a quaternion that rotates vector a to vector b
quaternion get_rotation(const vector &a, const vector &b, const vector &up)
{
    ASSERT_VECTOR_NORMALIZED(a);
    ASSERT_VECTOR_NORMALIZED(b);

    float dot = vector::dot(a, b);
    // test for dot -1
    if(nearly_equal_eps_f(dot, -1.0f, 0.000001f))
    {
        // vector a and b point exactly in the opposite direction,
        // so it is a 180 degrees turn around the up-axis
        return quaternion(up, gdeg2rad(180.0f));
    }
    // test for dot 1
    else if(nearly_equal_eps_f(dot, 1.0f, 0.000001f))
    {
        // vector a and b point exactly in the same direction
        // so we return the identity quaternion
        return quaternion(0.0f, 0.0f, 0.0f, 1.0f);
    }

    float rotAngle = acos(dot);
    vector rotAxis = vector::cross(a, b);
    rotAxis = vector::normalize(rotAxis);
    return quaternion(rotAxis, rotAngle);
}

```

---

**EDIT:** Corrected version of Marc's XNA code

```
// the new forward vector, so the avatar faces the target
Vector3 newForward = Vector3.Normalize(Position - GameState.Avatar.Position);
// calc the rotation so the avatar faces the target
Rotation = Helpers.GetRotation(Vector3.Forward, newForward, Vector3.Up);
Cannon.Shoot(Position, Rotation, this);

public static Quaternion GetRotation(Vector3 source, Vector3 dest, Vector3 up)
{
    float dot = Vector3.Dot(source, dest);

    if (Math.Abs(dot - (-1.0f)) < 0.000001f)
    {
        // vector a and b point exactly in the opposite direction,
        // so it is a 180 degrees turn around the up-axis
        return new Quaternion(up, MathHelper.ToRadians(180.0f));
    }
    if (Math.Abs(dot - (1.0f)) < 0.000001f)
    {
        // vector a and b point exactly in the same direction
        // so we return the identity quaternion
        return Quaternion.Identity;
    }

    float rotAngle = (float)Math.Acos(dot);
    Vector3 rotAxis = Vector3.Cross(source, dest);
    rotAxis = Vector3.Normalize(rotAxis);
    return Quaternion.CreateFromAxisAngle(rotAxis, rotAngle);
}

```

---
Tags: xna, c#, 3d, models, quaternion
---


# Question
Title: what algorithms exist for combining multiple triangle meshes into one mesh
Let's say I have a terrain mesh of some triangles, and several smaller meshes which I want to add to that terrain mesh (think ground and some small mounds or berms for example). What would I look for to find algorithms to let me do this? I know it's like some kind of computational geometry but I wonder if anyone might know search terms or even better urls to look at. Ideally I would like to do this on the fly to simplify drawing of a terrain where the basic ground and the detailed "interesting" bits are stored separately. Right now we draw the ground and the other parts separately which is less than ideal.

# Answer
> 4 votes
I think the term you are look for is CSG, or constructive solid geometry. There are basically three different operations: boolean union, boolean intersection, and boolean difference. You need the boolean union to merge two overlapping meshes into one. I'm sure you'll be able find some useful information with those terms.

Some links to get you started:

---
Tags: opengl, 3d-meshes, geometry
---


# Question
Title: How to emulate PSX's graphics with OpenGL?
I want to know what options (or shaders) to set so that my OpenGL game looks like Playstation 1 game. I know it probably can not be achieved 100 % because PSX used television and television renders differently that monitor. Thanks. :)

# Answer
> 24 votes
In my opinion, the most important bits to make an OpenGL scene look like a PSX scene would be to make sure the filtering is turned off (PS1 only had nearest neighbour), and turn off Z buffering (there wasn't any) and render your scene with painters algorithm.

The lighting was only per vertex, in fact there actually wasn't any lighting hardware only gouraud shaded vertex colouring. The lighting was software driven so you could do anything within the limitations of the CPU time, of which there wasn't much spare for clever advanced things like "lighting". :) We managed to get specular at one point, but as it was per vertex it made the scene look sparkley so we dropped it. We never managed to get specular to work with skinned meshes as blending normals and then using them just took too much time.

The PS1 also had a bit of texture swim, I'm not sure how you'd implement that with OpenGL, but if you're after an authentic experience, maybe just trying to make the UVs breakdown when they're near the screen edge would give a reasonable approximation.

I'd also recommend you look at the vertex transforms: the PS1 didn't have floats, so the rendering took place with fixed point pipelines, this is the cause of the jittery motion when playing animations. There were only so many positions a vertex could be in, and at 16bit fixed point, that wasn't even all that many positions. Have a watch of a few PS1 youtube videos to get an idea for how it affected the game, http://www.youtube.com/watch?v=RSV4IBa1pMI you can see here that it means that straight lines jitter around when the camera is close to horizontal. I think a good way of emulating this would be to transform your world in software (just like the PS1 did) and always output whole number screen coordinates to the emulated screen size (which was one of the major reasons why the polys jittered around, they couldn't be rendered to sub-pixels).

EDIT

Texture swim was due to the PS1 having NO 3D interpolation at all. As mentioned by user712092, the affine renderer could only interpolate in screen space so we ended up with our diagonals all wrong. This can be implemented by turning on `noperspective` on your interpolation qualifiers, or emulated by hand transforming the scene, and discarding the final Z value in your vertex after you have divided the x and y screen coordinates by that z value

---
Tags: opengl, emulation
---


# Question
Title: Handling collision with 2D surfaces and player sprite
What's the best way of representing surfaces in a 2d top down racing game? I'd like paved and dirt surfaces in my game to have different friction properties. Would you break up the map into a grid and simply check where in the grid the car is to determine the friction? Or is there a better way of managing it?

The roads and dirt are not self contained all or nothing tiles either, so I'd have to handle a grid section that contained some road and some dirt.

# Answer
It sounds like the root of what you're asking for is a way of determining the friction of the ground at a given point in your map.

A simple way of doing this could be to create a one-channel (grayscale) texture that represents the friction of the ground. Sample this texture at the point of the car (or each of the four wheels if you're feeling fancy) to get friction at runtime.

These textures should make it relatively easy to author content for. You could probably whip up a debug mode that overlays the friction map on top of the visual texture to double check that things line up right. It allows you a lot of freedom in the friction gradient at the fringe of the road. You could probably come up with a data structure that uses less memory, but with a top down sprite based game I'm guessing that's not going to be much of an issue.
> 2 votes

# Answer
I think what you're asking is 2D polygon collision detection: detect that the car shape is over a certain road shape, and then apply some physics effect like slowing down to the car.

This site has pretty pictures and has code that does what you're asking for, although you could probably pull it off just with bounding box collision detection. It really depends on what your game will really look like; "The roads and dirt are not self contained all or nothing tiles either" is somewhat vague.
> 0 votes

---
Tags: 2d, collision-detection
---


# Question
Title: How could I do simple per-fragment lighting on BSP geometries?
I am programming a graphics engine for an old game. The game uses a BSP geometry which I have rendering perfectly. For it's lights however, it simply has light instances with the standard x, y, z, rgba, brightness, type. Now I know that OpenGL has an 8 light limit. How should I go about handling multiple lights.

I am learning per fragment light just to have the concepts under my belt. I know per pixel lighting is the standard and I will eventually move there, just want to learn how to get this concept put in play as well.

I assume I will just calculate which lights are the closest and render those 8. Does anyone have any other ideas?

# Answer
> 4 votes
*I expect that you are ok to use shaders*

---

There are two approaches:

* **Forward rendering**, one render pass per light and using additive blending between render targets. It works for "independent" number of lights.
* **Deferred rendering**, is something like screen space rendering. Using few textures containing world space information.

Forward rendering is probably easier to handle. Also you don't have to use one shader pass per light as i mentioned. You can do it in a cycle in one shader pass. The only reason to have more shader passes per light is when light contains information like color texture (projective texturing) or intensity curve (stored in texture) ... so you run out of the texture units.

So i suggest simple forward rendering of all lights in one shader pass.

Deferred rendering is way faster than forward rendering (because it is practically screen space), but harder to handle.

I'm sure that you will find lots of good resources by googling for those two key words.

Some question from this site:

---
Tags: opengl, c++, lighting
---


# Question
Title: How do you get textures out of a png file
I have 1 png of many different textures. I want to use these textures in my iphone game using cocos2d. I found the program "Zwoptex" where you can combine many textures to one png and create a plist file that you can use in your program.

But if you have already a png file how do you get all these textures out of this file automatically OR how do I create a plist file from this png file?

# Answer
Looks like Zwoptex uses XML files to define sprites in a file. Unless the program has some kind of wizard for creating a new XML file from an existing PNG, you'd have to create this XML file yourself. You can find the specifications for creating one here: http://zwoptexapp.com/documentation, which includes a sample file.

If there isn't a wizard, you're best bet is to break apart all your images to have Zwoptex put them back together (and in the process create it's XML sprite definition file). Gimp is a free photo editor if you need one, fairly simple to use. To break apart your images, just use the *Free Select Tool*, select a sprite, CTRL + C, then go to *File-\>Create-\>From Clipboard*. Then simply save the new image with an appropriate name.

Good luck!
> 2 votes

---
Tags: iphone, textures, sprites, cocos2d
---


# Question
Title: Blender 2.5 - Using a Bezier Circle to set Bezier Curve as the Bevel Object
I'm trying to follow the tutorial found here.

Around 5:40 (ish) in the video, he adds a Bezier Circle. He then adds the existing Bezier Curve as the Bevel Object on the Circle. This makes the Curve go around the circle creating the 3D chess piece.

I'm trying to do the exact same thing, but it's not working. I am using Blender 2.5 however too. When I set my curve to be the Bevel Object of the Circle, my Bezier Circle is just becoming a larger gray disc of goo. I was expecting it to be a 3D chess pawn.

You can see a screenshot of what mine looks like:

Before Bevel Object is Placed

After Bevel Object is Placed

For the record, the name of my Bezier Curve is "BezierCurve" and the name of my Bezier Circle is "BezierCircle".

Thanks in advance, Andy

**UPDATE 1**

I just added a plan unchanged Bezier Curve and unchanged Bezier Circle and performed the same steps and it does work. Something must be wrong with my Bezier Curve in that it isn't being projected correctly around the Circle.

**UPDATE 2**

Just realized that when I set the Bezier Curve handles to "Automatic" using the V shortcut (only for Blender 2.5), then my Circle no longer imitates the 3D curve. I need Automatic I think in order for the Bezier Curve to not be wavy. With Automatic, it does a slight curve directly from point to point. Thoughts?

# Answer
> 3 votes
Blender is really picky when it comes to curve orientations and mostly doesn't do what you would expect. Your chess piece should have the same orientation as the circle, eg. don't rotate the bevel shape in an upwards position, rather keep it on the same "plane" as the circle, as shown in this image:

Rotating your "BezierCurve" should already have a visual impact on your chess-piece. Then you just have to go to edit mode (chess-outline) and modify the offset of the curve to the origin, so that the chess piece actually begins to look like one :)

---
Tags: blender
---


# Question
Title: Render to Texture2DArray slices in DirectX11?
I would like to set a slice of a `Texture2DArray` as a render target in D3D/DirectX11. It's not clear how to do this.

What I'm looking for is the DirectX equivalent of `glFramebufferTextureLayer()`, which sets a slice of a `GL_TEXTURE_2D_ARRAY_EXT` as a texture resource of a Framebuffer Object.

In D3D11, you set a render target using `ID3D11DeviceContext::OMSetRenderTargets`, and you can set a `Texture2DArray` resource view as a render target. However, the only way I see to select which slice of the texture is painted is to use the `SV_RenderTargetArrayIndex` semantic in an HLSL geometry shader. (The semantic is only available in a geometry shader).

My pipeline doesn't have a geometry shader, and I don't know at compile time which primitive type I will be rendering - I'm reading models out of input files. It seems like, to add a passthrough geometry shader I would need one shader program for every possible primitive type (terrible).

The desired output slice will not change between rendering passes. Is there no way to set a slice of a `Texture2DArray` as a render target without using a geometry shader?

# Answer
You can create separate render target views for every slice and then set it using `ID3D11DeviceContext::OMSetRenderTargets`.

```
D3D11_RENDER_TARGET_VIEW_DESC desc;
desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
desc.Texture2D.MipSlice = D3D11CalcSubresource(0, arraySlice, mipLevels);

```

Information about subresources.
> 6 votes

---
Tags: directx, textures, directx11
---


# Question
Title: Box2D Platform body not moving player body along with it
I am creating a game using Box2D (Javascript implementation) - and I added the ability to have a static platform, that is moved along an axis as a function of a sine.

My problem is when the player lands on the platform, as the platform moves along the X axis - the player is not moved along with it, as you visually would expect.

The player can land on the object, and if it hits the side of the object, it does colide with it and is pushed.

This image might explain better than I did:
After jumping on to the red platform the player character will fall off as the platform moves to the right

**UPDATE:
Here is a live demo showing the problem:
http://onedayitwillmake.com/ChuClone/slideexample.php**

# Answer
> 5 votes
> I move the platform by calling SetPosition on the body

I think this is the problem. Box2D is not designed to be used this way. Is there any way you can simulate sine function movement by applying impulses/forces?

# Answer
> 3 votes
Solved!

For future people: The solution was to use *`b2_Kinematic`* bodies. Do not move it by calling *`SetPosition`* on the platform.

Call *`SetLinearVelocity`*, and then any body's "on top" will interact as you would expect.

Giving the answer credit to Den since he provided information that led me in the right direction.

---
Tags: 2d, physics, box2d, platformer
---