title: Calculating an experience formula

text:
# Question
Title: Calculating an experience formula
I'm having trouble working out a formula using this experience curve to get the total exp after each level. I bet it's easy and I'm just overthinking it.

```
maxlvl = 10;
increment = 28;
baseexp = 100;
function calc(){
    for (i = 0;i<(maxlvl*increment);i+=increment){
        expperlvl = baseexp + i;
        document.writeln(expperlvl);
    }
}

```

# Answer
I figured it out. I decided to attempt to work out the formula on paper first and success.

```
minlvl=1;
maxlvl=6;
base=200;
increment=56;
function total(){
    totalxp=(base*(maxlvl-minlvl))+(increment*(.5*(maxlvl-minlvl)*(maxlvl-minlvl-1)));
    document.write(totalxp);
}

```

(made alteration to the formula, now its correct)
> 1 votes

# Answer
If you're just trying to calculate the experience at `maxlvl` (10), and you want it so that each level requires `increment` (28) more experience than the last, you can just use this formula (without the loop):

```
var expperlvl = baseexp + ((maxlvl - 1) * increment);
//Note: I subtract 1 from max level so that level 1 = baseexp.

```

However, this is linear and not a "curve" so you'll have to be more specific about what you are trying to do.
> 1 votes

---
Tags: javascript, game-mechanics, rpg, mathematics
---


# Question
Title: How much does game development mathematics change over time?
This question is mainly aimed at this book, Essential Mathematics for Games and Interactive Applications, Second Edition which I have seen highly recommended all around the internet, so I'm sure there are people on here who own a copy.

What I want to know specifically is if any of the information would be out dated since the book was released on June 2, 2008?

Also interested to see how the mathematics behind game development has changed over time.

# Answer
You can pick up a 200 year old book on mathematics and it'll hold true for game development. Books on "math for game development" don't teach anything special.

The book is a great introduction if you don't know where to start, though it's not as much a book about mathematics as it is a book about 3D theory. Computer graphics do evolve, modeling especialy, faster than anything else it would seem, still mathematics don't change, a dot product is a dot product.

Even when it comes to computer graphics theory a book from 2008 isn't going to be outdated, so don't worry. The fact is that most solutions, models, etc. used these days, even the more advanced ones were developed decades ago, before we could use them on home computers.

Also, TBH if you want knowledge younger than 2008 then you have to look for things like GDC talks, articles, etc.
> 5 votes

# Answer
Unfortunately or fortunately for some, the physics and mathematics of game development does not change much and has not changed much in the last 20-30 years. I checked the table of contents of the book you linked and it seems cover most of everything you will need.

There may be more advanced mathematics and techniques especially in collision detection which make use of more abstract concepts like the Minkowski sum, but you will probably not need to cover these for some time.

As an example the series of books Graphics Gems was publish around 93' and they are still very relevant. I.e. I found it particularly helpful when I needed to do random vector sampling.
> 3 votes

---
Tags: mathematics
---


title: Grid pathfinding with a lot of entities

text:
# Question
Title: Grid pathfinding with a lot of entities
I'd like to explain this problem with a screenshot from a released game, DROD: Gunthro's Epic Blunder, by Caravel Games.

The game is turn-based and tile-based.

I'm trying to create something very similar (a clone of the game), and I've got most of the fundamentals done, but I'm having trouble implementing pathfinding.

Look at the screenshot. The guys in yellow are friendly, and want to kill the roaches. Every turn, every guy in yellow pathfinds to the closest roach, and every roach pathfinds to the closest guy in yellow.

By closest I mean the target with the shortest path, not a simple distance calculation.

All of this without any kind of slowdown when loading the level or when passing turns. And all of the entities change position every turn. Also (not shown in screenshot), there can be doors that open and close and change the level's layout.

Impressive.

---

I've tried implementing pathfinding in my clone.

First attempt was making every roach find a path to a yellow guy every turn, using a breadth-first search algorithm. Obviously incredibly slow with more than a single roach, and would get exponentially slower with more than a single yellow guy.

Second attempt was mas making every yellow guy generate a pathmap (still breadth-first search) every time he moved. Worked perfectly with multiple roaches and a single yellow guy, but adding more yellow guys made the game slow and unplayable.

Last attempt was implementing JPS (jump point search). Every entity would individually calculate a path to its target. Fast, but with a limited number of entities. Having less than half the entities in the screenshot would make the game slow. And also, I had to get the "closest" enemy by calculating distance, not shortest path.

---

I've asked on the DROD forums how they did it, and a user replied that it was breadth-first search. The game is open source, and I took a look at the source code, but it's C++ (I'm using C#) and I found it confusing.

I don't know how to do it. Every approach I tried isn't good enough. And I believe that DROD generates global pathmaps, somehow, but I can't understand how every entity find the best individual path to other entities that move every turn.

What's the trick?

---

This is a reply I just got on the DROD forums:

> Without having looked at the code I'd wager it's two (or so) pathmaps for the whole room:
>
> One to the nearest enemy, and one to the nearest friendly for every tile.
>
> There's no need to make a separate pathmap for every entity when the overall goal is "move towards nearest enemy/friendly"... just mark every tile with the number of moves it takes to the nearest target and have the entity chose the move that takes it to the tile with the lowest number.

To be honest, I don't understand it that well.

# Answer
> 2 votes
For this situation I would likely try pathfinding with potential fields. Your game would have two such fields, one for friendlies and one for enemies. Which is likely what the forum answer was talking about.

Each field will have tiles just like you game board. Each one of these tiles will point toward the nearest friend or enemy to that tile. Visualized in paint:

You'd use diagonals I suppose, but I didn't want to draw those :)

For obstacles you'd have rules like never point directly into a wall or maybe do some simple path finding in those cases. You'd have to fiddle with it to see what it needs.

Alternatively, instead of vectors to point the way, you can do as the forum people suggested and just put the number of moves required to get to the nearest entity, but it pretty much equates to the same thing.

# Answer
> 0 votes
There's no trick. It's just a simple problem to solve. Every character just runs a breadth-first search, starting from their own position, until they find what they're looking for. Since the map is so densely populated, the search will never have to run for long before finding a target, so it's cheap. Effective use of data structures helps too.

One way in which you can make searches like these cheaper is to calculate influence maps and/or potential fields in the level for each unit type. Then pathfinding can be easily done just by moving from each tile to the most attractive tile next to it. More information here: Using Potential Fields in a Real-time Strategy Game Scenario (Tutorial).

But if you're having specific problems, you will need to state clearly what exactly you're trying (probably showing some code) and in what way it doesn't work.

---
Tags: ai, tiles, path-finding, turn-based
---


title: Dynamically load images inside jar

text:
# Question
Title: Dynamically load images inside jar
I'm using Slick2d for a game, and while it runs fine in Eclipse, i'm trying to figure out how to make it work when exported to a runnable .jar. I have it set up to where I load every image located in the res/ directory. Here's the code

```
/**
 * Loads all .png images located in source folders.
 * @throws SlickException
 */
public static void init() throws SlickException {

    loadedImages = new HashMap<>();
    try
    {
        URI uri = new URI(ResourceLoader.getResource("res").toString());
        File[] files = new File(uri).listFiles(new FilenameFilter(){
            @Override
            public boolean accept(File dir, String name)
            {
                if(name.endsWith(".png"))
                    return true;
                return false;
            }

        });

        System.out.println("Naming filenames now.");

        for(File f:files)
        {
            System.out.println(f.getName());
            FileInputStream fis = new FileInputStream(f);
            Image image = new Image(fis, f.getName(), false);
            loadedImages.put(f.getName(), image);
        }
    } catch (URISyntaxException | FileNotFoundException e)
    {
        System.err.println("UNABLE TO LOAD IMAGES FROM RES FOLDER!");
        e.printStackTrace();
    }

    font = new AngelCodeFont("res/bitmapfont.fnt",Art.get("bitmapfont.png"));

}

```

Now the obvious problem is the line `URI uri = new URI(ResourceLoader.getResource("res").toString());` If I pack the res folder into the .jar there will not be a res folder on the filesystem. How can I iterate through all the images in the compiled .jar itself, or what is a better system to automatically load all images?

# Answer
> 3 votes
I had this same problem a week ago, and the solution is to use InputStreams. I don't know how ResourceLoader from Slick works, but files are correctly loaded both in filesystem and in JARs using this code:

```
String filepath = "/package1/package2/file.lol";

InputStream inputStream = ClassLoader.class.getResourceAsStream(filepath);

```

and in your code you can do for example:

```
FileInputStream fis = (FileInputStream) inputStream;

```

If - like in your code - you want to search for files in directories, you have to write different code for the two cases(filesystem and jar):

```
URL url = this.getClass().getResource(directoryPath);
File directory = new File(url.getFile());

if (directory.exists()) {
     // we are running this code from filesystem
} else {
     // we are running this code from jar
}

```

You can find my implementation here (line 130).

# Answer
> 0 votes
This one just does not work this way.

You can't list files by directory inside a JAR file. Those files are placed inside the classpath when running the JAR and you need to access every file directly by its name. Access based on the folder structure does not work when accessing files inside the classpath.

You don't "notice" the difference in loading in this case because you are using the ResourceLoader that comes with Slick. In general that is the correct thing to do, but in this case it "hides" the fact that the classpath data is load and not the filesystem data.

So you either need to write down explicit what files you want to load or you need to generate some sort of file list while building the JAR file. Or you need a naming conversation that allows you to load all images. Something like `image0000.png`, `image0001.png`, `image0002.png`, ...

In case you choose to use a filelist you may look at the ANT build system and at fileset, filelist and pathconverter in order to get the automated generation of those lists going.

---
Tags: java, image, loading, slick
---


title: How to detect GLSL warnings?

text:
# Question
Title: How to detect GLSL warnings?
After compiling a shader with glCompileShader, I can call glGetShaderiv with GL\_COMPILE\_STATUS to check if the shader compiled successfully. I can also call glGetShaderInfoLog to get information about possible errors, warnings or other info. The information log returned by this function is unspecified.

In a tool where users can write their own shaders, I would like to print all errors and warnings from the compilation, but nothing if no warnings or errors were found. The problem is that the GL\_COMPILE\_STATUS returns only false if the compilation failed and true otherwise. If no problems were found, some drivers return empty info log from glGetShaderInfoLog, but some drivers can return something else such as "No errors.", which I do not want to print to the user. How is this problem generally solved?

# Answer
> 12 votes
Well, the way I solve it is by *always* fetching the log (even if none is available) and after that check for success.

```
glGetShaderiv(m_HandleVertex, GL_INFO_LOG_LENGTH, &bufflen);
if (bufflen > 1)
{
    GLchar* log_string = new char[bufflen + 1];
    glGetShaderInfoLog(m_HandleVertex, bufflen, 0, log_string);
    LOG_TRACE("Log found for '%s.vert':\n%s", m_Name.GetData(), log_string);

    delete[] log_string;
}

glGetShaderiv(m_HandleVertex, GL_COMPILE_STATUS, &success);
if (success != GL_TRUE)
{
    LOG_ERROR("Failed to compile vertex shader.");
    return false;
}

```

I did it this way because you might otherwise miss the warnings a shader returns. If a shader has warnings, but no errors, `success` will be true so you won't print the log, but warnings can also give you a clue as to why a shader fails to behave the way you want it.

---
Tags: opengl, glsl
---


title: How do I approach this collision model?

text:
# Question
Title: How do I approach this collision model?
This is the game level prototype I have already implemented. It has few objects per room to allow me to finally add some collision detection/response code into it.

VIDEO

As you can probably see, every object inside has it's own AABB, even the room itself has AABB. Also my player is inside the Room's AABB.

My player will be exactly inside the room, so he would have to collide correctly with those AABBs, so that when he hits any of those objects inside he get's a proper collision response from those AABB's.

Now I would like to hear from you what kind of collision approach should I choose in here?

How do I approach this kind of stuff:

* AABB to AABB collision detection then when this is positive go with AABB - Try to find proper plane normal and calculate response ?
* AABB to AABB then when positive go with AABB - AABB Side check to find proper plane normal and calculate response?
* Anything else?

How do you do this ?

Many thanks.

# Answer
> 1 votes
Ok, here is how i approached this model: PSEUDOCODE

```
CVector3 vResponse(0,0,0);

// Find out the sector we're in ( player is inside )
pCurrentSector = GetCurrentSector();

// Here is how we do it:
// 1. Test player AABB against Sector AABB
// 2. Test player against sector Triangles (if above true)
//
// --iterate through all objects inside current sector--
// 3. Test player AABB against ObjectX AABB
// 4. Test player against ObjectX Triangles (if above true)
// -----------------------------------------------------
//
// add -response vector from all Tri tests to our velocity

// Check if Play AABB collides Sector(room) AABB ( which is normally true )
// AABB - AABB test
if( pPlayer->AABB()->HasCollided(pCurrentSector->GetAABB()) )
{

  // Test against this sector triangles, and return response vectra
  // Sphere - TRI test
  if(pPlayer->HasCollided(pCurrentSector->GetTrianglesList())==true)
  {
   vResponse += ...
  }

  // Now test against all objects inside this sector (room)
  for(all_objects_inside_this_sector)
  {

    // Check against this object AABB
    // AABB - AABB test
    if(pPlayer->AABB()->HasCollided(pObjectX->AABB())==true)
    {

      // Check against this object triangles and add response
      // Sphere - TRI test
      if(pPlayer->HasCollided(pObjectX->GetTriangles())==true)
      {
       vResponse += ...
      }

    }

 }

}

Player.SetVelocity(Player.GetVelocity()-vResponse);

```

# Answer
> 0 votes
Are you asking the how you would do the math? It's simple really.

To test "collisions" (intersections) between two AABBs all you need is the minimum and the maximum coordinates of the boxes you're testing.

Say you have two AABBs called `A` and `B` which each have minimum and maximum values on each axis. You test if on each axis if they overlap. If they overlap **all** 3 axis, then they are colliding. If not, they are not colliding.

There is only one problem; your room is an AABB, so the aforementioned method will not work. So you could just have the floor as a AABB instead, or possibly look at convex collision.

# Answer
> 0 votes
First, your room should not have an AABB like that. Give each wall an AABB (which will effectively be planes). Otherwise you have to deal with inverted logic, where some objects push out of each other and other objects must be contained. You don't want that duality.

Second, to fine proper plane normals with AABBs, you can use a simplified Separating Axis Theorem test to find the plane of least penetration, which will be your normal. The second you start dealing with any other shapes though (spheres, capsules, OBBs, arbitrary convex hulls, etc.) that will no longer give satisfactory results.

You can use a modified GJK (Gilbert–Johnson–Keerthi) algorithm or MPR (Minkowski Portal Refinement). The latter is a bit more direct for physics needs, but the former can be a bit simpler to understand. I would recommend getting a grasp on GJK first and then looking into MPR.

A nice link to explain the basics of GJK for collision detection (but not manifold generation) is here: http://www.codezealot.org/archives/88

A decent link I just found on MPR is here: http://motleycoder.com/?p=66

---
Tags: c++, collision-detection, mathematics
---


# Question
Title: What are the app file size limitations for different smartphone OSes & carriers?
I know the iPhone App Store limits how large an app can be in general and there are also limitations with AT&T over the size it can be to transmit over a data plan vs WiFi. I have no idea what, if any, these limits are for Android apps and what I'm finding online is a mix of different numbers.

Does anyone know these numbers definitively? The Android game I'm porting is in the 20-30MB range and we'd like to know if we need to further reduce its size.

# Answer
> 6 votes
## Android

The maximum size for the market is 50 MB, and can be downloaded over-the-air. Third party stores can have whatever size files they want. The 50 MB limit is only on the .apk file size, it is possible to load content or other data after the app loads, only limited by the storage on the users device.

## iOS

The maximum size for distribution over cell networks is 20 MB. The maximum size for an app over WiFi or iTunes is 2 GB. It is possible to load content or other data after the app loads, only limited by the storage on the users device.

## Windows Phone 7

The maximum size for over-the-air is 20 MB. The maximum file size is 225 MB

# Answer
> 1 votes
The limit on iPhone apps for transmitting over 3G is 20MB (although that'll take a long time to download, so you definitely want to be much smaller than that.)

I don't know what the overall app size limit is (ie. how big can an app be to download over a wired connection?) because I behave as if the wireless limit is the upper limit.

# Answer
> 0 votes
As of September 24, 2010, the largest apk file you are able to upload is 25MB. I don't believe it has changed.

# Answer
> 0 votes
As of 5 March 2012, the limit for Android has been upped to 4GB from 50mb. As of 7 March 2012, the limit for OTA (over-the-air) downloads for iOS was raised to 50mb from 20mb. iOS max limit for non-OTA downloads remains 2GB.

See also this SO question on iOS changes, specifically.

---
Tags: iphone, android, windows-phone-7
---


title: OpenGL ES 2 - glSwapBuffers?

text:
# Question
Title: OpenGL ES 2 - glSwapBuffers?
this is what i do to blit FBO onto screen in ViewController:

```
[m_Context presentRenderbuffer:GL_RENDERBUFFER];

```

but i need something like **glSwapBuffers**, so that i can call it somewhere from the engine code ( which is cpp ) - to refresh the screen in special cases - is this available for iOS / how can i implement it - if i can at all..

# Answer
Ok, i have solved it by a small util function:

```
void SwapBuffers()
{
    EAGLContext* context = [EAGLContext currentContext];

    [context presentRenderbuffer:GL_RENDERBUFFER];
}

```
> 3 votes

---
Tags: opengl-es, ios, opengl-es2, ipad
---


# Question
Title: How can I get the front buffer into a texture on the GPU?
I'm attempting to write a small screen capture utility that writes captured video to disk.

First, I get the front buffer surface. I've written a shader that takes this surface and through render to texture, converts it to a YUY2 format frame. The format change is required so that I can pass the frames off to an encoder.

I'm using DirectX 9 to acquire the frontbuffer. There are a couple of ways I know of to get at the front buffer:

GetRenderTargetData()

GetFrontBufferData()

The MSDN page on both of these API calls state that the data is copied from device memory to system memory. I'd like to copy the front buffer surface directly to another graphics memory surface, as I have other manipulations to perform on the acquired surface before returning it to system memory.

I'm creating a D3DUSAGE\_DYNAMIC texture (gfx mem texture) and calling GetFrontBufferData() to write the front buffer to my textures surface0. Is this valid? Will the operation remain in gfx memory, or will it need to move to system memory and then back to graphics memory? If this is the case, is what I'm trying to achieve possible?

**EDIT** I've been acquiring the front buffer as below, simply because its a convenient way to get a surface populated:

```
hr = Dx9Mgr::Ref().D3DDev()->GetFrontBufferData( 0, m_spCaptureSurface );

```

OTOH, GetBackBuffer() allocates a new surface (I want to reuse one over and over), so I just went with GetFrontBufferData().

GetRenderTargetData() requires that the destination surface be created in system memory rather than in gfx memory (e.g. uses D3DPOOL\_SYSTEMMEM ), so I ruled this out. Maybe I should reconsider?

# Answer
> 2 votes
GetFrontBufferData is documented as being incredibly slow and unsuitable for use in any performance-critical path. In general terms the front buffer is something that belongs to your display subsystem and your program normally does not have access to it.

It's highly likely that there is a much better way of achieving the result you want without needing to access the front buffer at all. From the sound of it, you're talking about something that can be solved by a completely standard render-to-texture setup, but you'd need to give much more info on what it is you're trying to do before anyone could comment further.

---
Tags: c++, directx9
---


title: Resources for game networking in Java

text:
# Question
Title: Resources for game networking in Java
I am currently working on a Java multiplayer game. The game itself (single player) already works perfectly fine and so does the chat. The only thing that is really missing is the multiplayer part. Sadly I am absolutely clueless on where to start with that. I roughly know that I will have to work with packages, and I also know many things about streaming etc (chat is already working). Oh and it should - according to this article - be a UDP server. My problem is that I can't find any resources on how to do this. A tutorial (book or website) would be perfect, alternatively a good example of an open source client/server (in Java of course) would be fine as well. If you feel like doing something helpful I'd also really appreciate someone "privately" teaching me via email or some chat program :)

Thank you!

# Answer
You may also consider looking at the RedDwarf project that has been a community fork of Project Darkstar. The latter was a Research Project at Sun Microsystems and discontinued after Oracle took it over.

It was developed to be a horizontably scalable middleware and seems to have been very popular. The source of the RedDwarf Server fork is available on Sourceforge. That gave me an idea of how the serverside of a game can be realized. The documentation sometimes lacks information about the intentions of some classes but it gave me a basic understanding.
> 1 votes

# Answer
Take a look at Netty \- it's a very good high performance networking library that is well suited for game development. It has some very good documentation and tutorials.

See also:
> 0 votes

---
Tags: java, networking, multiplayer
---


# Question
Title: Store and create game objects at positions along terrain
I have a circular character that rolls down terrain like that shown in the picture below.

The terrain is created from an array holding 1000 points. The ground is drawn one screen width infront and one screen width behind. So as the character moves, edges are created infront and edges are removed behind.

My problem is, I want to create box2d bodies at certain locations along the path and need a way to store these creator methods or objects.

I need some way to store a position at which they are created and some pointer to a function to create them, once the character is in range. I guess this would be an array of some sort that is checked each time the ground is updated and then if in range, the function is executed and removed from the array. But I'm not sure if its even possible to store pointers to functions with parameters included... any help is much appreciated!

# Answer
Since you are only moving from left to right, all you need to do is store a two dimensional array of x coordinates and object type/parameters.

If you have an objects x position, you just need to see if it's on screen using this, if it is, put it in and work out the y coordinate of the ground at that location. The X position can simply be an index to your terrain array.

You can use bit-masking to create unique ids for objects and parameters. Then create a Factory method which will accept this id, break it down to get the type, call the constructor for that type and pass the id to it. The constructor can then use the id to work out how the object should be constructed.

As a quick example;

```
#include <iostream>

enum Type
{
    Box = 0,
    Enemy = 1,
    House = 2,
    Plant = 3,
    Vehicle = 4,
    // We want to shift value to the right hand side
    // of the int. The biggest value is 4 which
    // requires 3 bits to specify, so we want to
    // shift the number up to 32 - 3 (29).
    TypeBitShift = 29
};

enum EnemyType
{
    Snake = 0,
    Rhino = 1,
    Shark = 2
};

void main()
{
    unsigned int * IDs = new int[3];
    IDs[0] = (Enemy << TypeBitShift) | Snake;
    IDs[1] = (Enemy << TypeBitShift) | Rhino;
    IDs[2] = (Enemy << TypeBitShift) | Shark;

    for(int i = 0; i < 3; ++i)
    {
        // push the parameter bits off the end and convert to a type
        Type T = (Type)(IDs[i] >> TypeBitShift);
        if ( (int)T == Enemy )
        {
            // trim the type section, you can use;
            // (IDs[i] - ((IDs[i] >> TypeBitShift) << TypeBitShift))
            // or IDs[i] - (int) T << TypeBitShift since we already have the type
            // You can also get rid of any type parameter with;
            // or (IDs[i] & 0xFFFFFFFF >> (sizeof(int) * 8 - TypeBitShift))
            // or (IDs[i] & 0xFFFFFFFF >> 3)
            EnemyType ET = (EnemyType)(IDs[i] & 0xFFFFFFFF >> (sizeof(int) * 8 - TypeBitShift);
            switch(ET)
            {
            case Snake:
                std::cout << "I'm a snake.\n";
                break;
            case Rhino:
                std::cout << "I'm a rhino.\n";
                break;
            case Shark:
                std::cout << "I'm a shark.\n";
                break;
            }
        }
    }
    std::cin.get();
}

```
> 1 votes

---
Tags: box2d, cocos2d-iphone, cocos2d, objective-c
---


# Question
Title: How to request a specific OpenGL version?
I'm working on an OpenGL project, coming from D3D. They're organised in very different ways, so it's tricky going :)

Is there any way for a Windows application to request a specific OpenGL context version, e.g. 2.1 or 3.x?

Also, I believe I need to use wglext.h from the OpenGL registry as the GL.h that ships with Windows is an earlier version, 1.1 or 1.4 - can anyone confirm?

# Answer
> 3 votes
At first, you must know that you can run a given version of OpenGL in two different profiles: Compatibility profile is supposed to be compatible with the previous versions, and Core profile which doesn't support previous versions but might be faster/smaller. There is also a forward compatibility mode, best for you is to check on OpenGL website for more details about them.

Assuming you're using wgl to create an OpenGL context and glew, here is a code snippet that gives you access to advanced options such as version and profile:

```
// Usual initialization
if(!wglMakeCurrent(Context->hDC, Context->hRC))
    return 0;

glewInit();

GLint attribs[] =
{
    // Here we ask for OpenGL 2.1
    WGL_CONTEXT_MAJOR_VERSION_ARB, 2,
    WGL_CONTEXT_MINOR_VERSION_ARB, 1,
    // Uncomment this for forward compatibility mode
    //WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
    // Uncomment this for Compatibility profile
    //WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
    // We are using Core profile here
    WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
    0
};

HGLRC CompHRC = wglCreateContextAttribsARB(Context->hDC, 0, attribs);
if (CompHRC && wglMakeCurrent(Context->hDC, CompHRC))
    Context->hRC = CompHRC;

```

Don't forget to include `wglew.h` to get access to `wglCreateContextAttribsARB`. If you're not using glew (or something equivalent), I think you should do, especially if you're working under Windows and want to avoid a lot of pain.

# Answer
> 1 votes
I use GL Load

then it is a simply a matter of including the version of the header you want.

---
Tags: c++, opengl, windows
---


# Question
Title: How can I simulate multiple depth channels?
Here's what I'd like to achieve:

1. Rendering a first pass of objects in my scene, using standard depth comparison
2. Rendering another pass of objects in the same scene, but with the following rules:
    * A Pixel of the 2nd pass always override the first pass (no depth compare between them)
    * Use Depth comparison between pixels written from the second pass.

In English I want depth comparison made inside each pass but I always want the second pass pixels to override the first pass ones.

Some things I've thought:

* I tried to think about using stencil to solve this, but I couldn't find a way.
* I know I could render into a separate target the second pass then composite the result into the first, but I'd like to avoid that.
* I could use two separate Depth Buffer, one dedicated to each pass. (I never tried, but I figure it's possible to switch the depth buffer in a Render Target "on the fly")

Any idea of the best solution?

# Answer
You could draw the first pass, then clear the depth buffer and draw the second pass. (Assuming you don't need depth values from the first pass at any point later in your pipeline.)
> 3 votes

# Answer
Another way of doing this is to partition your depth range using two viewports - the first viewport has depth range 0 to 0.5 and the second has depth range 0.5 to 1, but otherwise they are identical. Your "first pass" would therefore go into the second viewport, and your "second pass" into the first.

That would have the advantage of enabling you to draw your objects in a more-or-less order-independent manner, but at the tradeoff of reduced depth buffer precision. Depending on the rest of your program's requirements this may or may not be a big deal.
> 1 votes

---
Tags: 3d, directx, directx11, depth-buffer, stencil
---


# Question
Title: Vector-based fonts vs. bitmap fonts in (2d) games?
I know that many games are using bitmap fonts. Which are the advantages for vector-based font rendering / manipulation when compared to bitmap fonts and in which scenarios would they matter the most?

Prefer a focus on 2d games when answering this question.

If relevant, please include examples for games using either approach.

**EDIT:** Please also include your personal preference if you have experience with the matter.

Some factors you might consider:

* amount of text used in the game
* scaling of text
* overlaying glyphs and anti-aliasing
* general rendering quality
* font colors and styling
* user interface requirements
* localisation / unicode
* text wrapping and formatting
* cross-platform deployment
* 2d vs 3d

---

**Background:**

I am developing a simple falling blocks game in 2d, targeted for pc. I would like to add text labels for level, score, and menu buttons. I am using SFML which uses FreeType internally, so vector-based features are easily available for my project.

In my view, font sizes in simple games often don't vary, and bitmap fonts should be easier for cross-platform concerns (font-formats and font rendering quality). But I am unsure if I am missing some important points here, especially since I want to polish the looks of the final game.

# Answer
**Bitmap fonts**

Advantages:

* Can be integrated into any existing codebase, whether it's OpenGL, DirectX, DirectDraw or even GDI+.
* Fast. Using a texture atlas, you can render all your text in a single pass.
* Artist-controlled. Texture atlases can be procedurally generated (rendering a font style to a texture) or they can be loaded from a file. Artists can then tweak the look of any glyph without breaking the game.

Disadvantages:

* Only useful for static text. When you're working with animated text (popping up, rotating, scaling, etc.), it becomes a pain to manage all the different font styles.
* Memory hog. If you want Arial 12, 16 and 24 in bold, italic or both, that becomes 3 (sizes) * 3 (styles) = 9 texture maps. Add another font and you have 18 different texture maps. Add support for Unicode and you're looking at 1024x1024 textures for each size! Mostly a problem on mobile platforms.

**Vector-based fonts**

**EDIT:** I didn't make this very clear, but a common implementation for vector-based fonts is to render them to a texture atlas and use them like a bitmap, which gives you the same speed advantage as a bitmap font.

Advantages:

* Manipulated easily. Because you're rasterizing between control points on the glyph, you can distort those control points any way you please. Very flexible for artists.

Disadvantages:

* Slow. When accounting for transformations, that means you have to transform each control point and rasterize a set of triangles for them.
* Hard to implement. Rasterizing glyphs is difficult to get right.

**How do other people do this?**

Take a look at this page:

http://www.microsoft.com/typography/OTSPEC/TTCH01.htm

This is how Microsoft solved it for Windows 95 and upwards. Basically:

* A font designer supplies an outline (vector-based)
* For every point size (8, 10, 12, etc.) a set of grid-fitting instructions is added

Which gives you the advantage of vector-based fonts (manipulated easy) combined with the speed of bitmaps.

Finally, you might want to take a look at a third option:

https://steamcdn-a.akamaihd.net/apps/valve/2007/SIGGRAPH2007\_AlphaTestedMagnification.pdf
> 7 votes

# Answer
The advantage of using Vector/True Type Fonts over Bitmap fonts is the greater deal of flexibility inside the application: you can draw them at any size, italize them, bold them, add some fancy transformation effects, all with maximum quality.

There are many many professional Vector Fonts out there, many of them have thousands of glyphs and many metadata for each, making it very profitable for dealing with displaying non-ascii strings, useful for translations.

The difference in performance will only show during the font loading given you cache the glyphs correctly. (The SFML render code isn't optimized at all, the glyph loading and caching is done properly however.)

FreeType has its own rasterizer and font loader and doesn't use the system ones, so quality and font formats won't be a problem.
> 1 votes

---
Tags: 2d, fonts
---


# Question
Title: How often should multiplayer games communicate with the server?
I once heard that Runescape "ticks" every 0.3s, and that seemed like a very long period of time, although Runescape is kind of a slow game.

I'm building a more dynamic top-down shooter game, and I'm wandering, how often should I communicate with the server? ASAP, or every 0.1s? How do shooter games usually do it?

Both the server and the client are written in Javascript, node.js and socket.io are being used.

# Answer
> 7 votes
30 times per second is a common packet rate, but that's really a very very small part of te equation.

Check out Networking for Game Programmers for a great intro article to game networking for latency sensitive designs like shooters.

---
Tags: networking, multiplayer, server
---


# Question
Title: Platformer Starter Kit - Collision Issues
I'm having trouble with my game that is based off the XNA Platformer starter kit. My game uses smaller tiles (16x16) then the original (32x40) which I'm thinking may be having an effect on collision (Being it needs to be more precise).

Standing on the edge of a tile and jumping causes the player to move off the the tile when he lands. And 80% of the time, when the player lands, he goes flying though SOLID tiles in a diagonal fashion. This is very annoying as it is almost impossible to test other features, when spawning and jumping will result in the player landing in another part of the level or falling off the edge completely.

The code is as follows:

```
/// <summary>
        /// Updates the player's velocity and position based on input, gravity, etc.
        /// </summary>
        public void ApplyPhysics(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            Vector2 previousPosition = Position;

            // Base velocity is a combination of horizontal movement control and
            // acceleration downward due to gravity.
            velocity.X += movement * MoveAcceleration * elapsed;
            velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed);

            velocity.Y = DoJump(velocity.Y, gameTime);

            // Apply pseudo-drag horizontally.
            if (IsOnGround)
                velocity.X *= GroundDragFactor;
            else
                velocity.X *= AirDragFactor;

            // Prevent the player from running faster than his top speed.
            velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed);

            // Apply velocity.
            Position += velocity * elapsed;
            Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y));

            // If the player is now colliding with the level, separate them.
            HandleCollisions();

            // If the collision stopped us from moving, reset the velocity to zero.
            if (Position.X == previousPosition.X)
                velocity.X = 0;

            if (Position.Y == previousPosition.Y)
                velocity.Y = 0;
        }

        /// <summary>
        /// Detects and resolves all collisions between the player and his neighboring
        /// tiles. When a collision is detected, the player is pushed away along one
        /// axis to prevent overlapping. There is some special logic for the Y axis to
        /// handle platforms which behave differently depending on direction of movement.

        /// </summary>
        private void HandleCollisions()
        {
            // Get the player's bounding rectangle and find neighboring tiles.
            Rectangle bounds = BoundingRectangle;
            int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
            int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1;
            int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
            int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1;

            // Reset flag to search for ground collision.
            isOnGround = false;

            // For each potentially colliding tile,
            for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    // If this tile is collidable,
                    ItemCollision collision = Level.GetCollision(x, y);
                    if (collision != ItemCollision.Passable)
                    {
                        // Determine collision depth (with direction) and magnitude.
                        Rectangle tileBounds = Level.GetBounds(x, y);
                        Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                        if (depth != Vector2.Zero)
                        {
                            float absDepthX = Math.Abs(depth.X);
                            float absDepthY = Math.Abs(depth.Y);

                            // Resolve the collision along the shallow axis.
                            if (absDepthY < absDepthX || collision == ItemCollision.Platform)
                            {
                                // If we crossed the top of a tile, we are on the ground.
                                if (previousBottom <= tileBounds.Top)
                                    isOnGround = true;

                                // Ignore platforms, unless we are on the ground.
                                if (collision == ItemCollision.Impassable || IsOnGround)
                                {
                                    // Resolve the collision along the Y axis.
                                    Position = new Vector2(Position.X, Position.Y + depth.Y);

                                    // Perform further collisions with the new bounds.
                                    bounds = BoundingRectangle;
                                }
                            }
                            else if (collision == ItemCollision.Impassable) // Ignore platforms.
                            {
                                // Resolve the collision along the X axis.
                                Position = new Vector2(Position.X + depth.X, Position.Y);

                                // Perform further collisions with the new bounds.
                                bounds = BoundingRectangle;
                            }
                        }
                    }
                }
            }

            // Save the new bounds bottom.
            previousBottom = bounds.Bottom;
        }

```

It also tends to jitter a little bit sometimes, I'm solved some of this with some fixes I found here on stackexchange, But Ive only seen one other case of the flying though blocks problem. This question seems to have a similar problem in the video, but mine is more crazy.

Again this is a very annoying bug! Any help would be greatly appreciated!

EDIT: Speed stuff

```
    // Constants for controling horizontal movement
    private const float MoveAcceleration = 13000.0f;
    private const float MaxMoveSpeed = 1750.0f;
    private const float GroundDragFactor = 0.48f;
    private const float AirDragFactor = 0.58f;

    // Constants for controlling vertical movement
    private const float MaxJumpTime = 0.35f;
    private const float JumpLaunchVelocity = -3500.0f;
    private const float GravityAcceleration = 3400.0f;
    private const float MaxFallSpeed = 550.0f;
    private const float JumpControlPower = 0.14f;

```

# Answer
> 7 votes
I believe you're on the right track. Take a look at my amazing artistic skills here ;)

Let's say that the player is the red block with the solid being their current position and the open square being their previous position. Now say that the blue tile is the platform you expect to land on and the green one is some other "impassable" tile beneath it.

The collision resolution assumes the you can only intersect one solid tile at a time and checks against it. Specifically, these lines

```
if (previousBottom <= tileBounds.Top)
    isOnGround = true;

```

So if we look at the right side of the image we can see that technically your previous bottom position would be less than the green tiles top. Since we've determined that, we assume it's a piece of ground and try to move on top of it. Then on the next go around since we've "corrected" the vertical collision, any other collisions will be treated as horizontal collisions and attempt to "push you away" from the other block, thus giving you a diagonal descent in to the pits of no-clip zone.

You've got a couple different solutions you could try:

* Change the maximum falling speed to be no greater than the height of your tiles.
* Use a more advanced collision structure and try to predict collisions before they occur.
* Check not only tiles you're directly colliding with but also one (or more) in a given direction. For example, if you're colliding with an "Impassable" check the tile just above it to see if it's a platform. It'd be pretty safe bet to say you passed through it if that's the case.

---
Tags: xna, c#, collision-detection, physics, platformer
---


title: Slide down transparent CCScene

text:
# Question
Title: Slide down transparent CCScene
I want a transparent CCScene (or CCLayer) to slide down when the game is paused...and I want it to be clear enough to see the CCLayer behind it.

How could I do this? Thanks

# Answer
You can use the `opacity` property on CCLayer. Any child you have added to that layer will also be affected.
> 3 votes

---
Tags: game-design, cocos2d-iphone
---


# Question
Title: Game Programming Resources for Programmers
I am a self-taught high school programmer (have an internship at local university), and understand the fundamentals of C++ and other related languages. I am looking to expand into game development, and have found a good DirectX book from which I will study. However, what are some good resources (online tutorials/books/etc) for C++ game programming which are tailored towards someone who is already experienced with C++? Most of the resources I have found attempt to teach basic programming, then get into game development.

# Answer
> 1 votes
There is a clear distinction between design and development. A game designer may have no programming skills, even though it would definitely be helpful.

Concerning game development, which I presume you're interested in, unfortunately there is no silver bullet. It's an issue that has been bothering me for a lot of time. It definitely depends on what you need to do, what you like and how much time you're prepared to invest in gamedev.

What I know is that the best way to learn how to code games is to actually code! There are two wonderful ways to achieve this:

* Start small, and try to build even simple types of games. Brickout and Pacman may sound trivial but they are an awful lot of work!
* Participate in a Libre/FOSS game project. Start studying the code, use paper to write down the basic architecture, and then delve in whatever part interests you most!

In addition, try not to re-invent the wheel and use popular/easy tools and algorithms, don't build everything from scratch, don't over-engineer, don't focus on performance or optimal design.

I'm sure you can find a lot of useful books here in Gamedev.SE and you can easily find interesting resources online.

You must also decide if you want to start with 2D or 3D game development. Of course, you can focus on tools or other parts of the game so graphics won't be an issue.

If you want to try something practical really fast, take a peek here: http://www.lazyfoo.net/SDL\_tutorials/

Why don't you check some projects here?

* freegamer.blogspot.com
* planetrev.freegamedev.net

**Fit in a big community in order to learn by studying and improving GOOD, WORKING CODE.** Simply studying resources and algorithms won't get you too far, as you will soon lose interest.

# Answer
> 0 votes
For game design, i recommend one of my favourite books: The Art of Game Design: A book of lenses, a extremely enjoable reading.

For game programming i have spent some time with Game Coding Complete, Fourth Edition, and i think it is worth reading because t explores all the major subsystems of modern game engines.

# Answer
> 0 votes
I found Game Programming AI by Example to be a great reference for fundamental game development concepts. It covers game math, flocking, state machines, lua scripting, advanced data structures, and path finding.

---
Tags: c++, assets
---


# Question
Title: How can I Implement KeyListeners/ActionListeners into the JFrame?
I'll get to the point: I have a player in my game that you control with the keyboard yet the key methods in the player class and ActionListener w/ KeyAdapter in the Board class don't seem to fire.

So far I've tried adding these key methods into the JFrame, doesn't seem to let me move him even though other objects that I have (enemies) can move fine.

Here's part of the JFrame class with the event listeners:

```
    frm.addKeyListener(KeyBoardListener);

    public void mouseClicked(MouseEvent e)
{
        nSound.play();
        StartB.setContentAreaFilled(false);
        cards.remove(StartB);
        frm.remove(TitleL);
        frm.remove(cards);
        frm.setLayout(new GridLayout(1, 1));
        frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200
        nBoard.setPreferredSize(new Dimension(1200, 420));
        cards.revalidate();
        frm.validate();
}

    public KeyListener KeyBoardListener = new KeyListener()
{
    @Override
    public void keyPressed(KeyEvent args0)
    {
    int key = args0.getKeyCode();

    if(key == KeyEvent.VK_LEFT)
    {
        nBoard.S.vx = -4;

    }
    if(key == KeyEvent.VK_RIGHT)
    {
        nBoard.S.vx = 4;
    }
    if(key == KeyEvent.VK_UP)
    {
        nBoard.S.vy = -4;
    }
    if(key == KeyEvent.VK_DOWN)
    {
        nBoard.S.vy = 4;
    }
    if(key == KeyEvent.VK_SPACE)
    {
        nBoard.S.fire();
    }

    }

    @Override
    public void keyReleased(KeyEvent args0)
    {
    int key = args0.getKeyCode();

    if(key == KeyEvent.VK_LEFT)
    {
        nBoard.S.vx = 0;
    }
    if(key == KeyEvent.VK_RIGHT)
    {
        nBoard.S.vx = 0;
    }
    if(key == KeyEvent.VK_UP)
    {
        nBoard.S.vy = 0;
    }
    if(key == KeyEvent.VK_DOWN)
    {
        nBoard.S.vy = 0;
    }
    }

    @Override
    public void keyTyped(KeyEvent args0) {
        // TODO Auto-generated method stub

    }
    };

```

# Answer
It sounds like your JFrame doesn't have keyboard focus. Try this:

> frm.requestFocus()

This question on StackOverflow may be useful as well.
> 0 votes

---
Tags: java, game-mechanics
---


# Question
Title: Create plane matrix from three 3d points
I have three 3d points (x, y, z). I am trying to create a 3d plane and get a 3d Matrix from those points.

The XYZ values are not accurate in this case but should give an idea on what I am looking. I am working in JavaScript but any pseudo code will do.

# Answer
Sounds like you don't need the plane at all. If I understand correctly, you want to create a transformation matrix which transforms a specific oriented rectangle to the rectangle in your picture. This transformation matrix you could then also use to transform other rectangles respectively.

You can create a transformation matrix easily if you know how base vectors should be transformed. Let's use 3x3 3D matrices here instead of 4x4 for simplification. You have three base vectors i=(0,0,1); j=(0,1,0); and k=(1,0,0);. Let's assume P1 is always in the origin as it is in the picture. From the picture it looks like you want to transform j to P2 and i to P4 (the last corner, missing from the picture). You still need to figure out where to transform k, and the answer is probably the cross product of P2 and P4. Let's call it P5. Now you can just make a 3x3 transformation matrix from these transformed vectors: \[P2 P4 P5\]. Put them either as row or column vectors depending how you handle the matrices.

If this is what you are looking for, taking translation into account and extending these to 4x4 matrices should not be hard.
> 2 votes

---
Tags: 3d, matrix
---


title: HTML5 Canvas Tileset Animation

text:
# Question
Title: HTML5 Canvas Tileset Animation
How to do in HTML5 canvas Image animating?

I am have this code now: http://jsfiddle.net/WnjB6/1/

In here I am can add animations something like -\> `Animation.add('stand', [0, 1, 2, 3, 4, 5]);`

But how to play this animation? My image drawing function is -\> `drawTile(canvasX, canvasY, tile, tileWidth, tileHeight);`

`Animation['stand']; return 0, 1, 2, 3, 4, 5`

I am need something like when I am run Animation.play('stand') run animation from 'stand' array.

I am try to do this something like one day, but no have more idea how. :(

Thanks and sorry for my bad English language.

# Answer
```
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

// Constructor for an animation object
// image: graphics source
// x, y: position to draw the animation
// width, height: size of each tile
// htiles: number of tiles horizontally in the image source
var Animation = function(image, x, y, width, height, htiles) {
    this.image = image;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.htiles = htiles;
    this.animations = {};
    this.currentAnimation = [0];
    this.currentFrame = 0;
}

// Add animation to the object
Animation.prototype.add = function(name, frames) {
    this.animations[name] = frames;
};

// Select animation by name
Animation.prototype.play = function(name) {
    this.currentAnimation = this.animations[name];
    this.currentFrame = 0;
};

// Advance animation, and draw the tile
Animation.prototype.nextFrame = function() {
    // Move to next frame in current animation
    this.currentFrame = (this.currentFrame + 1) % this.currentAnimation.length;
    // Extract which image tile that is
    var tile = this.currentAnimation[this.currentFrame];
    this.drawTile(tile);
};

// Draw the given tile at the current position
Animation.prototype.drawTile = function(tile) {
    // Clear region we are going to draw on
    context.clearRect(this.x,this.y,this.width,this.height);
    context.drawImage(this.image,
        (tile % this.htiles) * this.width,
        Math.floor(tile / this.htiles) * this.height,
        this.width, this.height,
        this.x, this.y, this.width, this.height);
};

// Initialize the animation
var image = new Image();
image.src = 'http://flashpunk.net/img/tut/swordguy.png';

var player1 = new Animation(image, 0, 0, 48, 32, 6);
player1.add('stand', [0, 1, 2, 3, 4, 5]);
player1.add('walk', [6, 7, 8, 9, 10, 11]);

var player2 = new Animation(image, 60, 60, 48, 32, 6);
player2.add('stand', [0, 1, 2, 3, 4, 5]);
player2.add('walk', [6, 7, 8, 9, 10, 11]);

// Start with the walking animation, and start animating
player1.play('walk');
player2.play('stand');
var interval = setInterval(function() {
    player1.nextFrame();
    player2.nextFrame();
}, 200);

// Toggle animation between standing and walking every 3 seconds
var mode = 0;
setInterval(function() {
    if (mode == 0) {
        mode = 1;
        player1.play('stand');
    }
    else {
        mode = 0;
        player1.play('walk');
    }
}, 3000);

```

You can see the result here: http://jsfiddle.net/WnjB6/7/
> 0 votes

---
Tags: animation, javascript, html5, html-canvas
---


title: Shaders in Cocos2d 2.0

text:
# Question
Title: Shaders in Cocos2d 2.0
I'm thinking of using cocos2d 2.0 for my next project and am wanting to know if it's possible to have a shader that renders to a texture and that texture be input into another shader?

I have a few effects that need this capability, but haven't been able to find anything that says you can do this.

# Answer
Use CCRenderTexture for this purpose..

http://www.raywenderlich.com/3857/how-to-create-dynamic-textures-with-ccrendertexture

in the draw code, you can always use: texture.sprite.shaderProgram ...
> 0 votes

---
Tags: cocos2d
---


# Question
Title: Trying to use stencils in 2D while retaining layer depth
This is a screen of what's going on just so you can get a frame of reference.

The problem I'm running into is that my game is slowing down due to the amount of texture swapping I'm doing during my draw call. Since walls, characters, floors, and all objects are on their respective sprite sheet containing those types, per tile draw, the loaded texture is swapping no less than 3 to 5+ times as it cycles and draws the sprites in order to layer properly.

Now, I've tried throwing all common objects together into their respective lists, and then using layerDepth drawing them that way which makes things a lot better, but the new problem I'm running into has to do with the way my doors/windows are drawn on walls. Namely, I was using stencils to clear out a block on the walls that are drawn in the shape of the door/window so that when the wall would draw, it would have a door/window sized hole in it.

This is the way my draw was set up for walls when I was going tile by tile rather than grouped up common objects.

1. first it would check to see if a door/window was on this wall. If not, it'd skip all the steps and just draw normally. Otherwise
2. end the current spriteBatch
3. Clear the buffers with a transparent color to preserve what was already drawn
4. start a new spritebatch with stencil settings
5. draw the door area
6. end the spriteBatch
7. start a new spritebatch that takes into account the previously set stencil
8. draw the wall which will now be drawn with a hole in it
9. end that spritebatch
10. start a new spritebatch with the normal settings to continue drawing tiles

In the tile by tile draw, clearing the depth/stencil buffers didn't matter since I wasn't using any layerDepth to organize what draws on top of what.

Now that I'm drawing from lists of common objects rather than tile by tile, it has sped up my draw call considerably but I can't seem to figure out a way to keep the stencil system to mask out the area a door or window will be drawn into a wall. The root of the problem is that when I end a spriteBatch to change the DepthStencilState, it flattens the current RenderTarget and there is no longer any depth sorting for anything drawn further down the line. This means walls always get drawn on top of everything regardless of depth or positioning in the game world and even on top of each other as the stencil has to happen once for every wall that has a door or window.

Does anyone know of a way to get around this? To boil it down, I need a way to draw having things sorted by layer depth while also being able to stencil/mask out portions of specific sprites.

# Answer
I don't know enough XNA to give you a proper solution, but I can give you a general answer.

The problem you're having is the painter's algorithm. Specifically, you need to order all the things you want to draw before you can draw them. The most common way to avoid this problem is with a depth-buffer. Interestingly, this is also called a z-buffer, because it stores the z-values in camera space.

However, because you don't have Z (because you are writing a 2D game), you cannot use this technique. Or can you?

Consider this: an orthographic projection doesn't change the perspective of points in 3D points. This is useful for things like user interface elements, because you always want them to be the same ways.

What I suggest is that you write a custom shader that takes 3D matrices and a depth value per vertex. This depth value should be used for depth buffering, but not for projection.

In pseudo-shadercode:

```
[vertex shader]
pos_output = TransformOrthographic * TransformView * vec3(pos_vertex.x, pos_vertex.y, 0.0);
depth_output = depth_vertex;

[fragment shader]
depth_output = (depth_input - depth_min) / (depth_max - depth_min);

```

Once you have this set up, you can stop worrying about objects being rendered in the wrong order and can instead set their depth value.

Now you should be able to render everything in one draw call, without worrying about stenciling out sections of the screen.
> 2 votes

---
Tags: xna
---


# Question
Title: How do people get around the Carmack's Reverse patent?
Apparently, Creative has a patent on Carmack's Reverse, and they successfully forced Id to modify their techniques for the source drop, as well as to include EAX in Doom 3.

But Carmack's Reverse is discussed quite often and apparently it's a good choice for deferred shading, so it's presumably used in a lot of other high-budget productions too.

Even though it's unlikely that Creative would go after smaller companies, I'm wondering how the bigger studios get around this problem. Do they just cross their fingers and hope Creative doesn't troll them, or do they just not use Carmack's Reverse at all?

# Answer
> I'm wondering how the bigger studios get around this problem.

They get around it by not using stencil shadow volumes. It's really not a good technique, and it doesn't work very well with deferred rendering, which is the direction a lot of the industry is going in.

Yes, it's nice in that it's pixel accurate, unlike shadow maps. But the many downsides (performance among them) make it a less than attractive idea for game developers.
> 9 votes

---
Tags: shadows, patents
---


# Question
Title: How do I approach large companies if I have a killer mobile game idea?
I have an idea for a game that has potential, but I'm not a programmer.

How do I tell this to development companies without having my idea stolen? All I want from the company is for somebody to watch a three minute long video presentation about my idea and if they see potential in it then we can talk about the details.

I have already sent an e-mail to several big companies that have the expertise needed to code the game, they haven't answered me. Actually the idea is nothing fancy, no 3D, but fun and unique.

# Answer
> 38 votes
First things first: ideas are worthless. Nobody is going to steal your idea, because everybody comes up with them all the time. *Get that into your head*.

Here's a flow chart:

* Come up with an idea for a game. Discuss it with everyone you know, especially its flaws.
* Summarize your idea in a single sentence *without comparing it to other games*.

+ Bad: "Like Mario but with guns."
    + Good: "Side-scrolling platformer with level-bending physics gun."
* Write a pitch. This is a three-minute presentation that will convince someone to invest in your idea.
* Make a demo. As you now have a pitch, you can convince developers to invest in your idea.
* Get a bag of money. With your demo, show publishers that your game is *awesome* and if you only just had a bit more money, you could make them so much more in return.

Did you see that idea I had for a game? I literally came up with that three minutes ago. Do you feel like you should steal it? Probably not. That's why I told you that ideas are worthless in and of itself. Only when you can see the idea working do you feel tempted to steal it.

# Answer
> 11 votes
> **Summary:** No-one will buy an idea from you and do all the work. If you want to see your game realised, you must *provide additional value beyond the original idea*. This can take many forms. I suggest that the value you provide come from programming. But, as I mention in the alternatives, there are other ways in which you can provide value.

Knight666 hits it on the head. It doesn't matter how good your idea is, it's the execution that matters. So grab a big marker and write this somewhere you'll see it every day:

> **Ideas Are Worthless**

You MUST read the question mentioned by Cyclops in the comments. Another way to think of the above statement is that since there is no demand for ideas, there is no market, they therefore have no value.

However I'm going to give you a different answer to Knight666:

## Provide value with programming (Learn to code)

It is not as hard as you think. It is comparable in difficulty to getting your driver's license. Even if you know nothing right now, you'll be able to create a demoable prototype of your game within six month if you apply yourself dilligently.

If you're not willing to put six month of effort part time to see your idea realised, it isn't worth *anyone*'s time.

Besides the fact that it's a useful all round skill to have, it will also allow you to interact with the people who *make* games. And this will be invaluable *if* you ever manage to get your idea off the ground. It's a no-lose scenario. You'll gain a valuable skill and insight even if you fail.

A major bonus is that while learning you'll build contacts with people who will be able to help you.

Then, instead of coming up to a company with some presentation, you can go:

> Hey, I've built this in six month without knowing how to program. Do you think it's cool?

Even if they don't take on the idea, you're bargaining from a stronger position. Instead of needing the company for your idea to survive, you're looking for a partner to create something awesome with.

Have a look at This tutorial and see if you can understand what's going on. If you can, pick the one that looks clearest to you and start playing around. When you get stuck, ask here or on Stackoverflow for help.

## Alternative ways of providing value

Another way to turn your idea into a reality is to **get a programmer on board**. To do this you'll have to *build a personal relationship* with that person, so that you're able to communicate your vision to them adequately. You will also have to **Provide significant value**. Contractors simply don't cut it for this kind of creative development unless you have enough cash to get great people.

I get ideas all the time. I could probably list off the top of my head 20 game ideas that haven't been made. The only reason for a programmer to work on *your* idea is that your involvement will significantly improve the chances of success.

If you're not going to program, then ask yourself this question:

**What do I contribute to the success of the game besides the initial idea?**

If your answer to that question is one of 'more ideas' or 'nothing' then *give up*.

If, on the other hand, you're able to things like:

* Drum up a storm on twitter
* Make crazy cool art
* Pitch to investors so well they beg to throw money at you

Then sell those abilities to a partner who can code.

Change the question from

**What can I get someone to do for me?**

to

**What can I contribute to the success of this idea?**

and you'll be in a much better position moving forward.

**\[Edit\]**: I wrote a course to teach people how to make games so you can turn your idea into reality :-) Get in touch and say hi for a discount.

# Answer
> 5 votes
While @knight666 is absolutely correct in his answer, this technically being a mobile application you might be able to game the system a little bit.

One approach you may consider taking is to reach out to consulting companies that build mobile applications for other companies. And you should approach them as a potential customer looking for them to build an application for you.

The biggest thing about this approach is that the company will listen to you. You are coming in as a paying customer and they will likely meet with you at no cost to see what your needs are and to see if they will be able to provide you with the services you need. They will likely put together a quote and at this point you may haggle for royalties but I doubt you are going to to get them to do it for completely free + royalties, but maybe you'll get lucky! If you can't come to terms, you just take your business else where.

The biggest disadvantage with this that I see is you are no longer necessarily dealing with game companies and as such the mindset may not be there for the developers to properly build and test game.

You may have to go to 100s of companies before you find someone willing to work with you on terms you deem acceptable but there is a (very very small) chance that you'll find one.

# Answer
> 5 votes
You can't really go to a game development company and have them make your idea. Unless of course you have a ton of money to pay them to make the game for you, in which case you aren't so much getting another company to make your game as funding a game company.

Besides what people have said in other answers, refer to this page on Sloperama: http://www.sloperama.com/advice/idea.htm

Near the end of that page is this great explanatory metaphor:

> Newsgroups: comp.games.development.industry From: gerryq@indigo.ie (Gerry Quinn) Subject: Re: What if I had an idea... Date: Tue, 10 Jun 2003 08:33:10 GMT
>
> ```
> darin_mosch@hotmail.com (Darin Mosch) wrote:
> >I have had an idea for a game for about 1 year now, and we've got
> >whitepapers and diagrams on the entire thing... where do I go from
> >here?
> >Do I talk with developers?
> >Do I start coding with my familiar languages?
> >Do I do more on the design?
> >
> >If it makes any difference, it's an "RPG-oriented" game.
> >
> >Experts, let me know your thoughts.
> >Thanks in advance,
>
> ```
>
> Imagine you have an idea for a new building in your city. You have made some drawings and floor plans. If it makes any difference, it's a square building.
>
> The situation is analogous (except that you don't need planning permission, so you're ahead in that respect anyway).
>
> Do what you would do in order to get it built. IE. either build it yourself, or convince people to help you build it. If you haven't the money to pay them, you must convince somebody to give or lend you lots of money, or persuade the helpers to help you without payment.
>
> If you go for the latter, you had better be very persuasive, because if the people who help for free are not very talented, and the building is more than a one-storey shack, it will probably fall down. Even more likely, if they lose interest, it will be left half finished.
>
> So, how are you going to convince people to give you millions to build your dream building? If I knew that, I'd tell you, just as soon as I had collected my own cheque. (Actually, I'd cash mine first...)
>
> If the 'building' of something big is what really attracts you, you could join a construction company. Maybe you would pick up contacts along the way that will help a few years down the line when you have money and experience of your own to invest. If you just want to build *something* of your own, get a day job and build it at weekends, alone or with like-minded others. If the long term career prospects are your meat, you could consider taking a degree in architecture or civil engineering.
>
> Hope the metaphor clarifies matters a little by distancing it ;-)

---

As kylotan points out in his comment though the situation is slightly different in games than in books or movies so I want to address those differences. First off, there is massively more work to the development of a game than the writing of a book. This is actually a fairly minor factor here, and doesn't apply at all to movies, but I want to mention it.

The main thing is that pitching a book or movie is generally not just "pitch the idea, then you leave while other people do everything else". For example, after you pitch a book to a publisher it is up to you to actually write the book. Similarly, with a movie you are the producer; no you're not acting or directing or anything, but you are very involved with the production and are doing lots of work to get the movie made.

Meanwhile the primary situation in which people just have an idea for a book and someone else writes it (ie. ghost-writing) is when the person is already really famous and/or important.

# Answer
> 3 votes
Literally the only known methods of getting your raw idea made into a game are:

```
1) contract a developer, there are many service shops that do work behind the scenes
2) start your own company

```

and read this

---
Tags: android, game-design, iphone
---


# Question
Title: Cost to licence characters or ships for a game
I am producing a game pitch document for a university game design class, and I am looking for examples of licencing cost for using characters or ships from other IP holders in a game. For example:

* cost of using an X-Wing in a game, licencing from Lucas
* cost of using the Enterprise in a game, licencing from Paramount
* cost of using the Space Shuttle (if any), licencing from Nasa

**EDIT**

The closest information I can find is from an article about Nights of the Old Republic, but isn't nearly specific enough for my needs:

> What Kotick means by Lucas being the principal beneficiary of the success of The Old Republic is that there are most likely clauses in the license agreement that give percentages, points, or another denomination of revenue out to Lucas and his people just for the Star Wars name, and that amount is presumed to be a great deal of money. Kotick is saying that because the cost of the license is so prohibitive, as he has personally had experience with in his position as CEO of Activision Blizzard, that EA will not be able to be profitable because of the hemorrhaging of money to the licensor.

**EDIT 2**

Another vague source stating that FOX uses a "five-figure rule" (assuming between $10,000 -\> $99,000)

> It seems FOX, like most studios, will not license individuals to create new works based upon their products. They will only commission individuals of their choosing if they elect to branch out into expanded product lines related to those licenses. Alternately, they are open to making the licencing available to large corporations with access to global markets, but only if those corporations agree to what Ms Friedman called a "five-figure guarantee". Presumably this means that the corporation seeking the licensing must agree to pay a 5-figure sum for that license, and be confident that their product will sell enough volume to recoup that fee, and to produce sufficient profits to make the acquisition worth their while.

# Answer
My sense is that every party you deal with will have different rules and prices, and that there isn't necessarily an "industry standard" for this. Part of it is the wildly variable value of the IP. An X-wing is part of a huge IP that's worth a lot of money, and thus is going to be costly. The spaceship from Mork & Mindy probably not so much.

Then there's the question of whether any particular licensee would allow their content for any amount of money. They clearly don't want it used in a degrading or other manner that is contrary to their brand and image. Every one of them wants to maintain as much control of their IP as they can and have the use of it be to advance their agendas.

NASA for example probably doesn't want the Space Shuttle to have lasers shooting whales. Lucas might not want to be in the same story world as Paramount IP, simply because they don't want Star Wars and Star Trek to be confused or otherwise combined. ABC probably isn't going to put characters from a FOX TV show in a crossover for example, unless there's some kind of special agreement between the two organizations.

Now that said, there is the whole idea of using the IP as part of a blatant parody. There are some conditions where you can use IP in that way (see http://en.wikipedia.org/wiki/Parody#United\_States for example).

Though your question was about cost, I'd say in general the idea of combining a bunch of IP like this is not a good one - especially very high value IP. If part of your grade (assuming this is a class) is creating a realistic game design document that has some potential for success, I think you're creating some unrealistic dependencies here that make it less likely to succeed.

Can you make the game work without all this IP and have it still be good? If so, do it. Consider the ability to get this IP as "icing on the cake" that makes your great idea even greater.
> 6 votes

# Answer
I did some quick searching and like you I found it very difficult to find any actual numbers though I did come across this useful article that explains some considerations you will want to think about when it comes to licensing all sorts of IP.

Your best bet would be to reach out to several studios, be them Movie, TV, Video Game, etc. and explain to them that you are writing a paper for school and ask what they do when it comes to determining cost for licensing and if they would be able to provide you specific examples (though I have a feeling those numbers are private - you might get lucky).
> 3 votes

# Answer
There's always the option of doing something like what Grand Theft Auto did. That is I believe instead of licensing actual cars, it used made up cars that were similar enough to real cars that people recognised them, but with different names. It's not the only game that has done that.

To be safe you'd need to take legal advice as to how close to the real thing you could get away with.
> 1 votes

---
Tags: game-design, licensing, costs
---


# Question
Title: Is it a good idea to make a game for one aspect ratio and arbitrary screen resolution?
After several very small games I have decided to make something more standalone (2D) and playable. However, I have met the problem of every game that is going to be played in more screen resolutions.

Basically, after some research I see that there are several solutions.

This seems to be the simplest one: *Let's say I define a constant aspect ratio for the game* (16:9) and the whole game will be created for a resolution 1680 x 1050.

The game will be rendered in this resolution and then I will be able to scale the render to match the player's display resolution. Therefore the game might be playable on almost any resolution, while it would keep the aspect ratio. So, if the game was run on 4:3 display, the top and the bottom of the display would be filled with black color.

It seems easy, but my question is - *Is this a good approach* for a simple game? The game will be simple, but I want to maintain high quality.

# Answer
> 4 votes
It's a fair approach, I've seen not-so-simple games using it.

However, as your target is **high quality**, I advise you to **support all aspect ratios properly**. You don't want your players annoyed because you're using only a percentage of their pixels.

So you've got two options:

1. If you only have a few aspect ratios to support (e.g only 4:3 and 16:9), you can cheat and use **distinct sets of absolute positions and sizes** for your 2D elements. One for each ratio. This might sound cheesy, but it's actually a fine solution in this situation, as option 2. is way trickier.
2. Use a library that supports **adapting 2D elements to ratio changes**. You might think this is an easy task to re-create one yourself, but it's not. So if you feel like going this way, be ready to craft your library with rigor. I've seen several people falling in the trap of *just-creating-a-menu-system-in-2-days*. Nope. This takes *way* more time. Goodbye absolute placement: you need anchors, relative sizes, extra care for the safe areas, etc. That's a broad topic (and a boring one, IMHO), and that's one of the main selling points of UI middlewares such as Autodesk Scaleform.

Once you've picked up your option, always make sure you **test thoroughly** your layout changes with all the different aspect ratios.

*PS: You're not concerned by this as you're making a 2D game, but for the record: for 3D rendering, adapting to different aspect ratios is only a change to the perspective matrix.*

# Answer
> 2 votes
To answer the question: yes, it is a good idea to make a game for a given aspect ratio and screen resolution.

However, it is only a good idea in certain circumstances.

Those circumstances include, but are not limited to:

1. developing for a platform with a particular aspect ratio and screen resolution like a console where display hardware is fixed (which it does not sound like what you are doing)
2. the game relies upon the aspect ratio for some reason that should it need to be retooled for a different aspect ratio it would somehow ruin the game play (doesn't sound like you have this either)
3. Deliberate stylistic reasons (it doesn't sound like you are doing this either).

If your reason is "because it is hard and complex to support multiple aspect ratios", then if that is enough of a reason for you, it is your game.

---
Tags: resolution, aspect-ratio
---


# Question
Title: Which image format to use for sprites in an HTML5 game?
In a 2D HTML5 game, what is the best image format to use and why? Should I use different formats in different situations? For example, .png for the background image, .jpeg for the animation frames and so on...

The "why" part is important to me. It doesn't really have to be localized to HTML5, it can be general advice as well.

# Answer
The image format is only a way to save raw data of pixels, so as long as you use bitmaps, the format usually does not make a difference in execution after the loading step. What matters is the pixel data supplied to the graphics API. There are three formats commonly used in the web:

**.gif** The (now normally deprecated) GIF format is used for images with 256 colors or less, leading to a very small size. GIF is also often used for animations. When using only 256 or less colors, it is a lossless format, which means that no quality is lost in term of compression. Otherwise the color variety has to be shriked down to 256, leading to quality reduction.

**.png** The Portable Network Graphics format is, as I think, the most used image format at all, since it comes with a good compression rate while being able to save more colors than GIF. PNG is also capable of translucency (or commonly called transparency, which is the wrong name since a pixel has to be 100% translucent to be called transparent). It is also a lossless format and aimed to improve and replace GIF in 2006 (source, first paragraph). I personally use it as an image type on websites and in games.

**.jpeg** The JPEG format is commonly used for photos and that stuff. It is not capable of translucency, nor does it gurantee lossless compression. It is common to specify the quality when compressing, leading to a tradeoff between space and quality.

Let's go through some use cases:

* **Artworks** or generally complex art is good to be saved in the JPEG format, as it is designed for that type of images.
* **Sprites** are best to be saved in PNG, especially when the variety of color is low.
* It is hard to define what **Backgrounds** should be saved in. The general rule would be something like: If it's a picture or complex art involving a high variety of color, take JPEG, otherwise PNG.
* An **Icon** should probably be a PNG image, even if it uses less than 256 colors, since GIF is, as stated above, replaced by PNG.

Bear in mind that the memory consumption and performance of the graphics API is usually equal between those formats. What matters is size and loading speed (you can dive into the algorithms of these formats if you want to estimate the loading cost). The memory consumption of any image in the raw state is usually defined by the general rule `width*height*4` byte for an RGBA pixel format, which is the most common.
> 9 votes

# Answer
Just a couple of things to add to @Marco's answer:

.gif is sorely outdated. I would completely avoid using .gif files as much as possible. I think people only use them these days because of in-browser animations, and animated png's aren't well supported at this time.

So all you have is jpg and png.

* PNG: **Is lossless**. The only thing you are considering here is the *rate of compression* you get. Generally does a good job compressing *blocks of solid color*, but a bad job compressing scenes with a lot of variation.
* JPG: Does a horrendous job with *blocks of solid color* (both loses detail *and* takes more space than png) but a great job with pictures *with a lot of variation* (good compression, almost unnoticeable image quality loss).

For example

## **4Kb** Megaman, in PNG format:

## This same picture is **36Kb** in JPG

## And the detail loss (that comes FREE! with jpg compression)

So here, with the solid blocks of color image, **we lose detail and incur additional size by using JPG**. Conclusion: don't use jPG for images with large blocks of solid color.

Now, think about a high color scene:

## ***1.63 MB*** PNG:

## The ***277 k*** JPG:

## approximate losses (i used jpg to upload this! but it shows you the losses

So in sum

* **Use PNG for images with blocks of solid color, ie NES-style sprites**.
* **Use JPG for images with lots of variation in color. This is like, any other image, especially backgrounds**.
> 12 votes

# Answer
Let us further abstract the question, then:

In a game running on its designated platform, what are the considerations for the media that it makes use of?

Consideration #1: size, aka speed of loading

No matter the platform and no matter the game and no matter the type of media, the fact is that it needs to be brought into a context for rendering. On a web based platform, this means downloading. On a desktop environment or console, it means loading from a local storage media. Loading your media takes time. Web based platforms can be especially crippled if a lot of media needs to be downloaded over a slow connection.

Consideration #2: memory consumption

Related to, but not the same as size. A pieces of media may be compressed while on disk or in a package or whatever, but once it is loaded as a texture or sound buffer for something it may be quite a bit bigger. The device upon which your game is executing does not have an infinite amount of memory.

Consideration #3: quality and style

Is the media of sufficient quality? This can be crucial to your game, and is often at odds with the size consideration. Very often a balance is needed between the two. Some games have incredibly simple graphics (minecraft) and yet are very successful. Others have really awesome graphics that take up gobs and gobs of memory, but give an immersive quality with amazing looking backgrounds. Some games get away with blips and bloops for sound effects, while others need to have 41k stereo music.

So, based on which is most important, you make the right decision for your game. The decision is per game, not one size fits all.
> 1 votes

# Answer
Generally, you go for the smallest filesize that still provides an acceptable quality of image. Additionally, png supports alpha so you don't need to deal with additional images to handle an alpha layer.

What/when to use png for (*generally speaking*):

* when you need to use an alpha layer
* cartoonish images/vector-like images that you want to preserve the sharp lines of.
* images with a small amounts of colors

PNG is lossless, but the color depth can be changed.

Use jpg for the remaining cases - photographic images, paintings, pictures with a lot of small details, colors and gradients. If you try to use PNG to store these images you'll notice the filesize is a lot larger than the jpg.

Tools like adobe image ready will give you a preview of your image along with the filesize in a variety of formats and quality settings.
> 0 votes

---
Tags: 2d, animation, html5, art, image
---


# Question
Title: How to make players be creative in a game, if the game cannot evaluate it?
I am working on a prototype game with several funny/visual effects that the player can trigger. The player can be quite creative in the way to use or combine these effects but it seems **impossible to make detect/evaluate this creativity by the computer**.

So, from a game design perspective, I wonder what could be the **features to drive the players to be creative** (experiment various combinations).

For the moment i think about "Draw something" where the result is evaluated by other players. I think about levels designed by "Little Big Planet" players but this aspect is out of the core game. I think also about "Minecraft" but I do not understand really how this game encourages the people to be creative (except of the open world).

Please tell me if you have any ideas, articles or references that could help me coping with this problem.

# Answer
The simple answer is you don't evaluate it.

Look up this phrase: "Emergent gameplay". Basically the idea is you give people a toolbox, and the interesting side effects of the interactions between complicated pieces gives players an avenue for creativity.

The end result is what some people call "user stories". That is to say, they're experiences that people want to share as a result of their decisions and creativity in the game but aren't necessarily what the game designer is forcing the players to do. Open world games with physics are notorious for having great user stories. Everybody who has played minecraft has their story about what decisions they made and how they ended up dying.

A lot of games, like Draw Something, have started including the ability to share these user stories as part of the critical flow. Several AAA games have started including screen-recording tools as part of the game as well. A great example is the Skate series.

And of course there's the "add a level editor" aspect to it a la LBP, Trials Evolution, and Portal 2. The barrier to entry for those creative outlets is probably too high for the casual user, however.
> 4 votes

# Answer
People are creative. Just generally, whenever. This can be traced back to when we started wearing loincloths and drawing on the walls of caves (my theory is the loincloths making static in our brains, though these days we have nicer loincloths).

There is one requirement for creativity to really flourish among the masses: **freedom**.

If you give people the freedom to be creative they'll be creative. So your major feature should be freedom. It doesn't have to be evaluated by the program itself. That's one reason Minecraft is insanely successful. It allows people the freedom to be creative!

Now, don't be thinking that freedom is an easy thing to achieve. You have to carefully craft the freedom. It has to be accessible and easy with complexity buried within. People need it to respond the way they expect and it has to do so consistently.

If you really want to add fuel to the creativity fire, **allow people to share their creativity easily**. Sharing with other people spurs people on to amazing amounts of creativity. Depending on your game, this can either be via screen captures, videos or sharing the save game files for other people to open up and explore.
> 1 votes

# Answer
Gameplay is about rewarding (for example: allowing to play the next level) and punishing (for example: having to restart from the beginning of the level). So the question kinda is "How can one reward the player for beeing creative?".

Well, it's not so easy because the computer can't "judge" how "creative" you are. First of all, **loosen those rules**, give a objective but give freedom on how to archive it. The less precision the game requires the more room there is for creativity. Next **make "construction" a goal**, it doesn't necessarily "requires" creativity, but it's connected to it to quite a degree. (Example: Terraria, build rooms-\>get people, people drive the game forward.) Another idea is to **give the players problems that have no obvious solutions** and thus require the player to think, and to get creative, about it. (Example: Clonk, the settlement scenarios you often have to face such situations, be it a cave flooded with Lava or a big granite wall). Last but not least: **social interaction**, when more than one human is involved there is an additional social "reward" for being creative: you can show it off. "Hey dude, look what I build!"
> 1 votes

# Answer
Be mindful of what you cannot do, and accept it. Namely, one cannot write a program to judge something as complex and abstract as creativity. Don't try to force the issue and create a convoluted scoring system that people will learn how to exploit anyway. If your goal is to encourage creativity, there's much better ways of doing it.

The first is simply to provide users with the means to put their creativity to work. Provide them with an environment that minimizes the effort required for them to translate their creativity into in-game results. A friendly user interface for a game like LittleBigPlanet can go a long way. Additionally, the user needs a world to actually interact and play around with; the more interesting you make the world, the more likely the player will be enticed to be creative in it. Giving the player the ability to disguise oneself as the enemy, for example, instantly opens up all sorts of interesting opportunities.

Another way is to allow users to share their creations with the world. A large reason LittleBigPlanet became a hit was the fact that users knew that the levels they designed would be experienced by people worldwide. Be wary of rating systems, however: if the experience becomes too focused on these, then players may lose interest when their beloved creations are rated poorly. Numerical ratings should be used more for players to find others' creations, not for a player to judge their own work's worth. Qualitative ratings may be better for the latter.
> 0 votes

---
Tags: game-design
---


title: Bitwise operators in DX9 ps_2_0 shader

text:
# Question
Title: Bitwise operators in DX9 ps_2_0 shader
I've got the following code in a shader:

```
// v & y are both uints
nPixel = v;
nPixel << 8;
nPixel |= y;

```

and this gives me the following error in compilation:

```
shader.fx(80,10): error X3535: Bitwise operations not supported on legacy targets.
shader.fx(92,18): ID3DXEffectCompiler::CompileEffect: There was an error compiling expression
ID3DXEffectCompiler: Compilation failed

```

The error is on the following line:

```
nPixel |= y;

```

What am I doing wrong here?

# Answer
> 6 votes
Bitwise operations and integer operations were new for SM 4.0/DX10. As your error says:

> Bitwise operations not supported on legacy targets.

You'll have to target DX10.

Alternatively, this blog post suggests using a texture to map results of AND,OR,XOR to different color channels.

*bitwise operators texture: AND,OR,XOR*

Seems plausible, and might be faster than the alternative I suggested in the comments.

---
Tags: directx, shaders, hlsl
---


title: SDL 1.2 reports wrong screen size

text:
# Question
Title: SDL 1.2 reports wrong screen size
I have a multi-monitor setup with two displays, both 1920x1200. In games, I can only select resolutions \> 1920x1200 (like 2560x1200) which makes games unusable.

Full screen doesn't work either because it switches one display to 800x600 which means I can't reach the close button... I have to kill the game and then, I have to restore my desktop because all windows are moved/resized.

How can I force SDL to use any resolution that I want?

# Answer
If this is a game you're making with SDL, then use SDL\_SetVideoMode to set any resolution you want. Just pass in values for `width` and `height`.

If this is a game you're trying to play that uses SDL, then you'll have to provide more details, such as what the game is (also, Gaming.SE would be better suited for such a question)

**\[EDIT\]** If the game uses SDL to get a list of video modes, it calls SDL\_ListModes. There is currently no way to influence the result of this method with, say, environment variables.
> 1 votes

# Answer
In the mean time, I've written a patch for SDL 1.2 which allows to force a screen size down its throat: http://blog.pdark.de/2011/12/04/forcing-sdl-to-use-a-certain-window-size/
> 1 votes

---
Tags: sdl, screen
---