# Question
Title: How to make a cube mesh and texture for XNA use?
I have a very specific question which I feel should have a very short answer, but which I can't seem to find despite Googling on and off all day.

I'm trying to start with 3D graphics, and I read up a bit on the theory, etc. and I know the math. The issue is just with software. I'm trying to make a cube, which appears to be made of dirt (honestly solid brown would be fine), to appear on the screen. Technically I'm using XNA but I don't think this affects the answer or question very much.

I know how to make a functioning mesh/texture combo appear on the screen properly (I've read http://msdn.microsoft.com/en-us/library/bb975644(v=xnagamestudio.31).aspx among others); the issue is producing the texture itself.

For example, with Blender, I can easily make a cube and stick a procedurally generated texture on it that looks pretty good, but when I export as, say, .fbx, I get a mesh (and I think no texture data) and it doesn't work (as in doesn't appear on the screen but doesn't give an error message, which is consistent with the "no texture data" hypothesis).

So one great answer would just be to tell me how to export texture data from Blender along with, or in addition to, the mesh.

One other great answer would be to tell me how to produce textures in a different (free) program that is perhaps better suited (Blender may not be the right choice, I don't know anything about it).

Either answer or some completely other kind of answer is fine. But I feel like this should be a simple problem to solve, and I don't think I can stand another 30 minute youtube video that doesn't answer the question.

# Answer
In Blender, you need to UV map a texture to your cube model. Then when you export your model (using the standard FBX exporter) it will contain a reference to that texture in addition to your UV coordinates on each vertex. Then if you render your cube using a BasicEffect, as in the tutorial you referenced, this would be when you iterate through the mesh's effects...

`foreach (BasicEffect effect in mesh.Effects)`

you just need to set TextureEnabled = true and Texture to your loaded texture content. See http://msdn.microsoft.com/en-us/library/bb464051.aspx, particularly step 4.
> 1 votes

---
Tags: xna, 3d, textures, blender
---


# Question
Title: Isometric game engine in JavaScript/HTML5
Is anybody aware of any stable-ish (ie out of alpha) isometric drawing engines for JavaScript/HTML5? I have done some Google searches and found a few, but they were mostly in alpha/invite-only status.

Is there anything mature enough to be used in a production environment? Or should I simply roll my own implementation for now and wait for the rest of the world to catch up?

# Answer
> 16 votes
As you said, the only ones I have found are either betas or alphas with none seeming to be ready for release.

**At this point in time it is probably better to roll your own:**

* Better understanding of the internals.
* Able to tweak the engine to your needs.
* Develop the features you need to use
* Skip features of other engines you don't need, reducing code bloat, and overhead.
* Bugs and issues will be your own problem, and easier and faster to fix than an unfinished engine.

# Answer
> 3 votes
How about this one: http://code.google.com/p/jgen/

# Answer
> 2 votes
The Aves Engine was a really good engine (so it seemed), and then Zynga (Farmville people) bought it and made it closed source. There's a video of it being presented somewhere, before it was bought.

# Answer
> 2 votes
I agree, all of HTML5 is in beta, but lots of people are working on game engines. I'm doing one myself (which I'll release open-source and describe fully in a book on HTML5 game dev.)

So far, I've got a basic sprite object that works much like a MovieClip in ActionScript or a Sprite in PyGame. It's got all the basic features: speed, direction, vector-projection, multiple images, boundary-checking, transformations, and basic collision detection.

I'm working on a very simple game object as well. This will encapsulate the canvas element, manage the main animation loop, and provide high-level interface to the event system (such as it is)

I'm trying to keep it as simple as possible: something like gameEngine in Python:

http://aharrisbooks.net/pythonGame/

Even when I get this working, it certainly won't be stable, because the underlying technologies are far too unstable. The browser support of various HTML5 features literally changes every day, and there is still no meaningful support for most HTML5 features in IE. Also, performance varies dramatically between browsers, so a game that runs great in chrome may not run at all in Firefox.

If you're wanting a stable, practical environment, HTML5 isn't it yet. If you're interested in experimenting with HTML5, it's looking like a very promising alternative. I'm definitely eager to use it as a teaching environment. I believe it will be pretty useful in that regard.

# Answer
> 1 votes
Personally I believe HTML5 to be downwards stable, i.e. what's there won't go again. Obviously no ones knows how all the unresolved issues will turn out in the end and yes, there might be features in the future that one should wait for, but it's already "good enough". That's why I guess a lot of people are working on their own html5 game engine or towards that. At least I am :-)

It does not have an isometric builder yet, but well, it does not stop you either. Tutorials will be added soonish, but mainly I am posting this cause I also listed all the other engines I found so far - here at the bottom http://blog.weeblog.net/?p=29

# Answer
> 1 votes
The following engines don't support ISO out of the box but are - from the kind of abstraction they provide - maybe interesting for you to read, or might even provide underlying code:

# Answer
> 1 votes
There's isogame that came up from google.

# Answer
> 1 votes
I would suggest taking look at LimeJS, seems very promising - http://www.limejs.com

# Answer
> 1 votes
CraftyJS supports isometric pretty well, and has examples on their site. Check it out: http://craftyjs.com/

# Answer
> 0 votes
Isogenic Engine is in 1.1 and aims to provide "rock-solid 2d and isometric" features.

# Answer
> -1 votes
I wrote an html5 game engine and open sourced it here: https://github.com/j03m/trafficcone

It supports an isometric world + sprites and is free.

# Answer
> -1 votes
Yes,You may find it in http://myospace.jp/about.php. I developed that Html5 based avatar engine. and I give it the name "MYO". I used it to duplicate the most well know Japanese Avatar system of "ameba pigg". It works on Iphone, android and of course WEB. but best on Iphone. You may try it yourself. if you want more info about it Please Mail me.

---
Tags: javascript, html5, isometric
---


# Question
Title: Are there any alternative JS ports of Box2D?
I have been thinking about creating a top down 2D car game for HTML5. For my first game I wrote the physics and collisions my self but for this one I would like to use some ready made library.

I found out Box2D and its JS port.

http://box2d-js.sourceforge.net

It seems to be quite old port, made in 2008. Is it lacking many features of current Box2D or does it have major issues with it? And are there any alternatives for it?

# Answer
> 10 votes
Box2D has a kind of maintained version on github:

https://github.com/thinkpixellab/pl/tree/master/src/box2d

Microsoft is using it for at least on of their IE9 test drive demos.

# Answer
> 16 votes
There's box2dweb, which is a much newer port and has a lot fewer issues than box2djs. I highly recommend it.

http://code.google.com/p/box2dweb/

# Answer
> 3 votes
A popular alternative (though not a port) is cannon.js, a "lightweight 3D physics engine" for the web.

# Answer
> 2 votes
Also:

I also remember a port for the original C++ code to JavaScript using Emscripten ie. LLVM but I can't seem to find it back. Only found https://github.com/kripken/emscripten/issues/22
Too bad, I find interesting to adapt the original code rather than a port of a port...

# Answer
> 1 votes
While this isn't Box2D, there is a port of JigLib (3D Physics) to JS: https://github.com/supereggbert/JigLibJS. I haven't used it, but it was ported to be used in the GLGE WebGL library.

# Answer
> 0 votes
There is very good alternative for Box2D-JS, just see box2dweb. See this game which is built using box2dweb. You can make your project easily using this physics engine.

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


# Question
Title: Do opengl games tend to use multiple shaders?
For any given object that you want to render, there may be a whole bunch of things that need to be considered for rendering (Material, Texture, Lighting, Blending etc). But, you may also have some objects which are very simple, and do not have a Texture or material or require any blending and ignore lights.

So, how do people approach this. Do you write one GLSL shader that has various booleans and checks that need to be set as vertices are pumped through, or do you write separate shaders for each general category of object, and switch between these as your render?

# Answer
> 9 votes
To answer your specific question, and focussing on two recent OpenGL titles:

* A frame of Doom 3 BFG Edition can use ~12 different GLSL programs.
* A frame of Rage can use ~38 different GLSL programs.

(Captured using GL Intercept).

So the answer is a "yes" - OpenGL games (or at least these ones) will use multiple shaders.

As a general case answer it's more a case of "it depends". The choice to use multiple shaders or using branching can often be down to which is the more expensive option - making a shader change or having every vertex or fragment processed have to take a branch.

In the old days this was pretty clear cut - the first shading languages available didn't support branching *at all*, so you had no option - you used multiple shaders.

As branching support started coming in, things got interesting. First off, you might want to support older hardware, in which case you likewise didn't have a choice - no branching. Secondly, the original forms of shader branching were quite primitive; basically both branches would be executed and the internal hardware registers would be updated based on which one passed (i.e. branching was most likely just emulated using a mix/lerp/step/etc instruction - you can still see this today in HLSL code if you compile with branching disabled and view it's disassembly). So again the best option was to not branch.

Modern hardware is, of course, more flexible and you have 2 forms of branching available. Branching based on a shader uniform (GLSL) or constant (HLSL) should be very cheap indeed - not free, but the hardware can know that all executions of the shader for the current set of states will take the same branch, and optimize accordingly.

Branching based on some value determined at runtime (or input via a vertex attrib) is more interesting. Modern hardware will execute shaders in "groups" (I'm avoiding vendor-specific terminology here) of vertices or fragments, and if all executions of a shader for a given "group" take the same branch, it can also pull some optimizatios.

There's also the fact that GLSL complicates things a little by having current uniform values be part of program state. HLSL doesn't have this, and it's not the way hardware works, but that's the decision that was made for GLSL, so what it means is that a shader change could also involve saving out the existing contents of hardware registers, then loading in new values as part of the new program state. Using UBOs would also avoid that, of course, but if you're using standalone uniforms then you need to be aware that changing shaders can involve a good deal more than just swapping out some small executable images.

None of this is to say that having a single big shader with lots of branching is the preferred option, of course. Branching still has it's own cost, and it may well incur more overhead than a shader change, even on modern hardware. You also need to consider that your vertex shader input is quite tied to the shader itself, unless you use a common vertex format and layout for everything. On modern hardware with geometry and tesselation shader stages you may have to deal with cases where these (optional) shader stages may or may not be active in the current program. Beware especially of the geometry shader, because it can be *sloooooow* \- even if just a passthrough shader - so you'll not want it active unless you're doing something that explicitly requires it (such as writing to a non-zero viewport index).

So all this lengthy preamble was a fairly roundabout way of coming to the usual conclusion to questions such as this: everybody's use case is different, so profile, benchmark, find which is the fastest for you, decide which performance vs flexibility/code-cleanliness tradeoffs you will or won't accept, and base your code around these real-world metrics.

# Answer
> 3 votes
In general, I believe that what you want to do is minimize the number of times that you change OpenGL state. That means calls to glUniform, glUseProgram, etc should be avoided as much as possible. To do that, you'd want to group all of your objects such that those that require the same OpenGL state get rendered together (i.e. render objects without textures and materials all at once).

The way this usually works is that each object that will be rendered will use a specific "material"... not in the OpenGL sense, but rather in the "what state settings do I need to render this" sense. These include textures, shaders, and other attributes that are needed for rendering. What you want to do is group as many of these "materials" together in sequential draw calls to avoid changing parameters, or at least, change very little.

---
Tags: opengl, glsl
---


# Question
Title: Where can I find complete multilingual in-game dialogue transcripts?
I'd like to do some linguistic analysis.

It doesn't matter if it's a AAA title or not; the requirement is only that it should be the complete transcript from the official game and that it's available in multiple languages.

# Answer
> 2 votes
Try open-source visual novels. The writing is typically rough around the edges, but there is plenty of it. Such games are frequently translated by fans.
<sub>(Watch out, contents may be, uh, *steamy*.)</sub>

If they're made in Ren'Py, a Python-based VN engine (many are) then their dialogue will be findable in human-readable form in the distribution.

Juniper's Knot, for example has been translated into various languages.

# Answer
> 1 votes
It will vary from game to game. Some games will have this information easily accessible in human readable data files, other games will have it stored in binary data packages. This is something you'll just have to poke around and find yourself depending on which game you're interested in. Either by looking through the data files yourself, or searching online for someone that's found the information already.

There are likely easier ways to get transcripts in multiple languages. For example, movie subtitles are frequently available in multiple languages.

---
Tags: localization, dialogue-tree
---


title: Which way to go after C++?

text:
# Question
Title: Which way to go after C++?
I have 2 years learning C++ and created an RPG text-based game lately. Everything I have done so far was about pure C++ and the console, with the exception of a game in Allegro 5. Now I want to start learning 3D directly, since 2D programming is a cropped down version of it and I am better in 3D than 2D in maths. I was watching Irrlicht and it seems very good. So basically choices are: Learn more C++ || Jump into 2D again || Go with 3D

Which one is really worth it? I personally think going with Irrlicht is the best option which is a graphics engine and from the demos it could do everything I think of.

# Answer
I'd advise against "Learn more C++" in favour of creating something because you'll learn more with hands-on experience. I'd recommend to consider getting some experience with mobile app development by making a game. There are some C++ SDKs that allow you to build for iOS and Android(I can think of MarmaladeSDK(non-free)).

3D has a much higher payoff, but it is also more of a challenge. There is only so much you can learn from 2D. For engines/frameworks for 3D that you could choose from:

You could also check out Unity3D or Unreal Development Kit

If you go with Irrlicht you'll also need to pick a sound library you can find here. You could check out some open-source games and see how they perform with their engines or get some ideas on how they use it. Minetest uses Irrlicht.

You can't really go wrong with any of these libraries, although I would research their portability if you're interested in developing for mobile/other platforms.
> 1 votes

---
Tags: 3d
---


# Question
Title: Creating a BufferedImage with several smaller images?
I am making a 2D tile based game. The tiles render fine from a spritesheet and a text file. However, I am using a for loop to draw the map to the screen. When it refreshes, it slows down the loop, and the bottom is black for a fraction of a second.

I was wondering if I could create a separate method to create a `BufferedImage` to hold the map, so I could render it continuously, and change it when needed.

**Map Class:**

```
package uk.co.madmonkeystudios.distortioner;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

public class Map {

    static BufferedImage sheet;

    public static void SetSpriteSheet() throws IOException{
        sheet = ImageIO.read(new File("res/grid.png"));
    }

    public static BufferedImage GetTile(int id) throws IOException{
        if(sheet == null){SetSpriteSheet();}

        int across = 24;

        BufferedImage tile = null;
        int x = 0;
        int y = 1;
        int w = 31;
        int h = 31;
        for(int done = 0;done<id;done++){

            x= done * w;
            x += id;
            if(done >= across){
                y += h;
                y++;
            }

        }
        tile = sheet.getSubimage(x, y, w, h);

        return tile;
    }

    public static void DrawMap(int id) throws IOException{

        Graphics2D g = (Graphics2D)Core.myself.getGraphics();

        g.clearRect(0,0,640,480);

        int[][] map = ReadMap(0);

        int xsize = map.length;
        int ysize = map[0].length;
        System.out.println("Map Read, size (" +xsize + "," +ysize+")");

        int x = Player.x;
        int y = Player.y;

        for(int loopy = 0;loopy<ysize;loopy++){
            for(int loop = 0;loop<xsize;loop++){
                g.drawImage(GetTile(map[loop][loopy]),loop * 32 + x, loopy * 32 +y + 25,32,32,null);
            }
            }
    }

    public static int[][] ReadMap(int id){
        int [][] map = null;
        try{
        @SuppressWarnings("resource")
        Scanner s = new Scanner(new File("res/maps/area"+id+".map"));
        int [][] map1 = new int[Integer.parseInt(s.next())][Integer.parseInt(s.next())];
        String current;

        int xsize = map1.length;
        int ysize = map1[0].length;

        for(int loopy = 0;loopy<ysize;loopy++){
        for(int loop = 0;loop<xsize;loop++){
            current = s.next();
            map1[loop][loopy] = Integer.parseInt(current);
        }
        }
        map = map1;
        }catch(NullPointerException ex70){
            System.err.println("Cannot read map in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't read map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        catch(FileNotFoundException ex71){
            System.err.println("Cannot find map in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't read map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        catch(ArrayIndexOutOfBoundsException ex72){
            System.err.println("Cannot add map to array in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't send map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        return map;
    }

}

```

# Answer
> 0 votes
Why not add double buffering to everything drawn in your game?

This is the way I would do it...

you would declare 2 variables in your main game class like so:

```
private Graphics g;
private BufferStrategy bs;
//private YourTileMap map;

```

then in my main class I would have a render method which does exactly what it sounds like it does... It renders all of my components in the game.

Note: To use the "getBufferStrategy();" method; my main class extends Canvas

There are many ways to skin a cat and this is my take on it :)

```
public void render() {
    bs = getBufferStrategy(); // Gets BufferStrategy
    if (bs == null) { // If it = null
        createBufferStrategy(3); // Create 3 Buffer Strategies
        return;
    }

    try {
        g = bs.getDrawGraphics(); // Gets BufferStrategies draw graphics
        g.setColor(Color.BLACK); // Sets Color to black
        g.fillRect(0, 0, (int)SCREEN_SIZE.getWidth(), (int)SCREEN_SIZE.getHeight()); // Fills the background of window with black

        // Render Components Here
        //Example:
        // map.render(g);

    } finally {
        g.dispose(); // Disposes of the graphics once finished copying them
    }

    bs.show(); // Shows the image you just created behind the scenes

}

```

As I stated before, this is just one take on double buffering and I'm sure there are people who have different ways of doing it...

I find this the best way of doing :)

Dont forget to initialise your map either ;)

---
Tags: java, tiles, tilemap
---


# Question
Title: How do I allow a player to build a dedicated server, but prevent them from cheating?
Instead of maintaining a central server, many games allow players to build their own server, like Minecraft.

But if you give them the server-side program, how could you prevent them from cheating? I thought it's impossible, but Team Fortress 2 seems doing that. Usual TF2 servers are built by players. But Valve sells the items in TF2, so they must have a way to prevent server owner generating these items.

# Answer
I suppose you could have the server send a hash of it's executable to an authentication server, to ensure it hasn't been modified been modified, but that's about it.

I wouldn't worry too much about it, if you're going to let players have their own servers let them do whatever they want with the game, they purchased it. You can make it difficult to cheat, but you can't stop players from cheating. Your job is to make a fun game that people want to play. Focus on that first.
> 6 votes

# Answer
Can't be done.

Haven't you ever been in a 10mx10m TF2 server where you'd just wait for drops? Neither have I! ;)

You could implement some sanity-checks on your server, but then you'd have a central server.

Can you afford a central server for such checks?
> 6 votes

# Answer
Unfortunately, there is no fool-proof method of preventing cheating in a set-up like this. I imagine Valve is able to enforce its game-economy through strict policing.

As such, there are ways to make fixing the damage--for example, you could limit what a server could give its players. If you had a some paid virtual item, a random server shouldn't be able to give the player the item; only the master server should be able to.

Another thing you can do is keep a log of what the servers tell the master server. This way, if you discover that a server has been sending "shady" commands (i.e. "Player X gained 1000000 XP"), you can instantly roll-back all commands that the server has sent to the master-server, instantly undoing everything that the server told the master server to do.

Sending the hash wouldn't work; if I were determined enough, I could always change the server code to send the appropriate hash.

You're never going to be able to trust the client. Once information gets on their computer, it's out there for good. The best thing you can do is develop accurate heuristics and deal harsh punishments.
> 0 votes

---
Tags: multiplayer, server, client-server, anti-cheat
---


# Question
Title: XNA GameComponent.Initialize() not called
I have a game which creates an object in its Initialize() method:

```
    private GameComponent1 _thingy;
    protected override void Initialize() //Game1.Initialize()
    {
        base.Initialize();
        _thing = new GameComponent1(this);
    }

```

In the GameComponent1 class:

```
    public GameComponent1(Game1 game) : base(game)
    {
        _game = game;
        game.Components.Add(this);
    }

    public override void Initialize() //GameComponent1.Initialize()
    {
        //Do stuff here
        base.Initialize();
    }

```

However, in this case, `_thing`'s `Initialize` method is not called. Why is this?

It behaves fine when the object is created in, say, Game1's `Update` method...

# Answer
> 5 votes
swap the order of this:

```
base.Initialize();
_thing = new GameComponent1(this);

```

to this:

```
_thing = new GameComponent1(this);
base.Initialize();

```

You need to initialize your components before, I believe.

---
Tags: xna
---


title: Packet handling system architecture?

text:
# Question
Title: Packet handling system architecture?
I'm working on a multiplayer Flash game (ActionScript 3) with an accompanying server written in Python and I'd like some tips regarding networking, and specifically, **the handling of packets and implementation of such a system on both the client and server**.

At this moment, I am using bytes to identify packets (e.g, 0x00 is login request, 0x02 is login response), sending and reading data in the order specified by my protocol. This is fine, and I am okay with this, but I'd like to **clean up the code that handles this system because it seems redundant and unintuitive to use.** I'm asking for experienced network programmers, specifically game developers, to answer this question as I lack experience in this field.

Right now, the packet system is made of **two main components**: The `Networker` and the `PacketParser`. The `Networker`'s job is to determine when a packet begins and then passes the packet to the `PacketParser` which will read the packet contents determined by the identification byte, and return an associative array of the data, which is then handled by the `Networker`, for example, an Entity's position is updated.

When sending a packet, the user would send an associative array of data to the `Networker`, which is then sent to the socket through the `PacketParser`, and this code is rather ugly and ridiculous. Here is a sample in Python, packetparser.py:

```
def sendPacket(data, socket):
    byters = "" # Buffer - will be sent at once

    if data["Type"] == "LoginReply":
        byters = unpacker.sendUnsignedByte(byters, 1)
        byters = unpacker.sendString(byters, data["Message"])

    if data["Type"] == "Message":
        byters = unpacker.sendUnsignedByte(byters, 2)
        byters = unpacker.sendString(byters, data["Message"])

    if data["Type"] == "Tick":
        byters = unpacker.sendUnsignedByte(byters, 3)

    if data["Type"] == "TankInfo":
        byters = unpacker.sendUnsignedByte(byters, 4)
        name = data["Tank"].getName()
        velocity = data["Tank"].velocity
        baserot = data["Tank"].baserot
        x = data["Tank"].x
        y = data["Tank"].y

        byters = unpacker.sendString(byters, name)
        byters = unpacker.sendInt(byters, velocity)
        byters = unpacker.sendInt(byters, baserot)
        byters = unpacker.sendInt(byters, x)
        byters = unpacker.sendInt(byters, y)

```

As you can see, this is rather ridiculous, and repetitive.

So, I now would like to smoothen this system out. My initial idea is to create a `Packet` interface and for every packet I'd like to handle, I would implement the interface with the hardcoded data, so I can do something like this:

```
networker.sendPacket(new LoginRequestPacket("username", "password"));

```

This is rather nice to the eye and nice to use, *but is it the best?* Also, this works fine for sending packets, but what about receiving packets? Perhaps the `Networker` will have to do this?

```
ident = socket.readByte();

if (ident == 0x01)
{
    pack = new LoginRequestPacket();
    pack.read(socket);
}

```

Also, once packets have been received, **where in the codebase should game logic be handled** (relating to the packet received)? Right now, it's handled directly in `Networker` but this seems self-defeating - the `Networker` for network-related stuff, not game logic! That's handled in the main `Game` class! So, should I set up/use some sort of event system, for example, `onLoginResponse()` or `onPositionUpdate`? Or maybe, to make the `Packet` classes more useful, logic should be handled directly in there? Or maybe even queuing the packets somewhere, for both input and output? Would that work?

These are just things I've thought of on the top of my head, I have no idea on what the pros and cons of these suggestions are and I'd like someone to outline them.

I've had such little experience in this that I really want to hear how you have implemented such a system, to give me a baseline to develop off. Please tell me what I'm doing wrong, what I'm doing right, and what should be done better.

Thanks!

**UPDATE**

I didn't say so before, but right now, the client is using non-blocking sockets and the server is using blocking sockets, spawning a new thread per client. After some research it looks like the common consensus is to avoid blocking sockets for a game that expects \>10 clients (source), so I will be redesigning the serverside codebase to use non-blocking sockets, but this **still leaves the issue of where to handle the logic** and **how `Packet`s are architecturally designed**. Please advise me!

# Answer
I'm writing game in HTML5 using websockets and my design should apply well for you too.

I've separated few things.

TRANSPORT. This is a module that takes care of reading data from network. Transport is for example TCP or UDP, but it might be also serial or something else. You should have functions in this module to connect, read, write and disconnect.

PROTOCOL. This is a way in which you are parsing data (not your game logic data yet, just whole messages). In example you can have "sign delimeter" protocol, which reads data from transport and creates messages from it by splitting data where "delimeter sign" occurs.

```
123%456%789%

```

this data read from transport would be converted to 3 messages \[123,456, 789\] if your delimeter is %. Special case of this protocol is "line receiver" where delimeter sign is "\n".

For binary packets you should create protocol that creates messages based on size of packet.

(3 1 3 4)

Let's assume that this is 4 bytes long data. Your protocol should read first byte (3) so it knows that this packet has 3 bytes. Then you read next 3 bytes so this protocol gets message (1 3 4). You can also have sizes constant for types, but it's not a good idea if you want to send strings.

PARSER. Messages that you get from protocol should be parsed. Parsing is based on some type of identifier sent in message. I have separated ID into type and subtype. My ID is 2 bytes long, and I store type id in 4 first bits, and subtype id in rest 12 bits. How to do this you have to read elsewhere. This way your switch (ifs) is more optimized. Store these identifiers at the top of parser module. In example:

```
    TYPE_SYSTEM = 1
    SUBTYPE_LOGIN_REQUEST = 1

    if type == TYPE_SYSTEM:
        if subtype == SUBTYPE_LOGIN_REQUEST:
            do_something()

```

In the end you should remember about design patterns MODEL, CONTROLLER, VIEW. On server you just need MODELS and CONTROLLERS. Parsers are controllers, while transport and protocol are models, you just use them in controllers. They should have no dependancy. Every model should be encapsulated.

Once again I'll explain flow of work in shorter form.

You separated modules that should have no dependancies on each other: \- transport, \- protocol, \- game logics,

Controllers: \- main controller, \- main\_parser, \- specific\_parsers.

In main controller in a loop you read data using transport model, that data is saved to buffer. Buffer is then passed to protocol model. If buffer has enough data then protocol returns list of messages that it created from data. This list of messages is passed to main parser controller. Main parser based on type and subtype calls specific parser and passes it data from message. Specific parser use functions from game logic model. And that's all about it.

I've separated main parser and specific parsers because in one module it would take too much space and it would be troublesome to find function you want later when you'll write like 100 parser functions.

Good luck.
> 0 votes

# Answer
Here is some thoughts about game server architecture, which I've used for packet handling in several projects:

1) If you use python at server side, **don't use sockets directly**, use twisted library. This library provide set of tools for creating great high-load applications using asynchronous approach. At first sight twisted seems to be very difficult to understand, but after comprehension several core concepts you will be happy. Here is great twisted introduction: http://krondo.com/?page\_id=1327

2) Python have some **problems with using threads because of GIL**(Global Interpreter Lock), searching through this site could explain why.

3) It's very good idea to move the code which serialize your data to separate module, but the best idea, I think, to use some already existed serialization format like **XML, JSON, BSON or msgpack ( or even AMF)**. They all have pros and cons and should be chosen carefully. However, if you use standard Python types like dictionaries and lists for processing data and returning result to client, serialization/deserialization procedures are trivial(not for XML :) ) .

4) Another good pattern will be to use **simple RPC**. When the client want to ask server perform some useful work, it creates a packet which include the name of function which should be called at server + provide some arguments for this function. Our server will process request according to game logic and return response to the client. Using this pattern it's easy to move separate pieces of game logic into separate modules.

Here is code-skeleton which is used in several twisted-based projects for processing packets from client at server side. I haven't provide the actual code, because it has many many details which are deeply unnecessary for understanding the main idea, but I think this is enough for understanding.

```
class Protocol(LineReceiver):
    def __init__(self, config):
        #here we create an adapter object according to
        #configuration format. It could be XML, JSON, BSON, msgpack or
        #some other custom format
        self.adapter = getSerializationAdapter(type=config["serialization_format"])
        #here we define the packet delimiter "\0" is great for
        #non-binary protocol and also for some binaries like msgpack which
        #can't produce "\0" symbol after serialization
        self.delimiter = "\0"
    ...
    def lineReceived(self, line):
        #here we unpack seriali
        packet = self.adapter.deserialize(line)

        #process requested line asynchronously, processRequest returns
        #special Deferred object which represent the result of packet
        #handling and could be used for attaching
        #some callbacks to it
        d = processRequest(packet)

        #add callback which will write to the client generated response
        d.addCallback(self.writeResponse, packet)

        #add callback which will process server exception
        d.addErrCallback(self.writeErrResponse, packet)

    def writeResponse(self, result, packet):
        #... take some information from packet if nessesary

        #here we serialize the object which we obtain from
        #game logic layer
        self.sendLine(self.adapter.serialize(result))

    def writeErrResponse(self, err, packet):
        #... take some information from packet if nessesary

        log.err(err)
        #here we create internal game error object from
        #Failure object, which contains all info about error
        #(code, error message, traceback, local context of error, etc.)
        game_error = _create_game_error(err)

        #here we serialize game error object to stream of bytes
        self.sendLine(self.adapter.serialize(game_error))

    #a special twisted magic decorator which is used for simplifying
    #asynchronous code with callback chains, see twisted documentation
    #for additional information
    @defer.inlineCallbacks
    def processRequest(self, packet):
        ...
        method_name = packet["method_name"]
        method_map = {
            "login": some_module1.do_login,
            "takeMoney": some_module2.take_money,
        }
        if method_name not in method_map:
                #return an error from generator function using special magic
                #returnValue function
                defer.returnValue(_create_game_error("Invalid method"))

        #here we call method which implements some game logic, process request
        #and return some object as result
        res = yield method_map[method_name](method_args)

        #return result from generator function using
        #special magic returnValue function
        defer.returnValue(res)

```

And you should implement several serialization adapters for supporting needed formats, here is example of JSON-based serialization adapter:

```
class SerializationAdapterJson(object):
    def pack(self, arg_dict):
        import json
        return json.dumps(arg_dict)

    def unpack(self, packet):
        import json
        return json.loads(packet)

```
> 0 votes

---
Tags: architecture, networking, actionscript-3, python, packet
---


# Question
Title: How to create a fog effect in XNA with PixelShaderFunction?
I developped a small XNA games in 3D. I would like to add a "**fog of war**" on my models instantiated **with an effect** in my **(.fx)** file. The problem is, I do not know how to change the function "PixelShaderFunction".

File \[.fx\]

Here is the **declaration of my variables** in my effect file (.fx):

```
// InstancedModel.fx
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------

// Camera settings.
float4x4 World;
float4x4 View;
float4x4 Projection;

//Fog settings
float FogNear;
float FogFar;
float4 FogColor;

```

And my **function "PixelShaderFunction"** in my effect file (.fx):

```
// Both techniques share this same pixel shader.
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return tex2D(Sampler, input.TextureCoordinate) * input.Color;
}

```

# Answer
You could take a look in XNA's BasicEffect shader source and see how they have implemented Fog support there.

The source code is available here.
> 1 votes

---
Tags: xna, game-design, graphic-effects, fragment-shader, effects
---


title: What are the basic game activities?

text:
# Question
Title: What are the basic game activities?
So there are genres like FPS, RTS and RPG, but every game is created around some sort of activity, like exploration, resource collection, storytelling or combat. What other basic activities exist?

# Answer
Here is a list of genres, description of possible gameplay/activities, and an example game demonstrating that genre/gameplay:

> * Action Arena
>     + Fast-paced game where combat/conflict occurs in a closed arena. Often top-down view
>     + Smash TV

* Action FPS
    + First-persion shooter: fast-paced game viewed from first person perspective, where gameplay centers around shooting
    + Doom

> * Action Other
>     + Any fast-moving, timing/twitch-dependant game not fitting into other
>     + Action subgenres:

* Action Platformer
    + Fast-moving or coordination-dependent game centered around a
    character navigating a maze or level to pursue goals
    + Cloning Clyde

> * Action Puzzler
>     + Action games with a significant puzzle-solving component
>     + Roboblitz

* Action RPG
    + Action game with RPG features (i.e. experience levels, item
    acquisition, etc)
    + Diablo

> * Action Schmup
>     + Aka ‘shoot ‘em up’, any vertical or horizontal scrolling game involving blasting through an onslaught of enemies.
>     + Heavy Weapon, Scramble

* Casual Action
    + Casual games with a faster pace, time-pressure, or twitch mechanic
    + Feeding Frenzy

> * Casual
>     + Card/Board Electronic adaptations of traditional card and board games
>     + UNO, Backgammon

* Casual I-Spy
    + Object-finding games
    + Mystery Case Files

> * Casual Match3/Chain-pop
>     + Match 3-or-more of same color or shape to clear
>     + Bejewelled, Zuma, Luxor

* Casual Other
    + Any casual game not fitting into other casual categories

> * Casual Puzzle/Word
>     + Logic or word games
>     + Sudoku, Hangman

* Experimental
    + Games with an utterly new/novel mechanic. This is an extremely rare classification; be honest with yourself before selecting it. The very first version of Warioware would have qualified; subsequent versions no longer would.

> * Fighting
>     + Person vs. Person combat
>     + Street Fighter 2

* Kids
    + Forgiving, simple-to-comprehend game with child-friendly content.

> * Music
>     + Beatmatch, or any game where music is core to the gameplay
>     + Boom Boom Rocket, DDR

* Party
    + Games primarily designed around 4+ player, same-console play
    + Trivia games, Smash Brothers, etc

> * Racing Arena Combat
>     + Vehicle combat in an arena
>     + Novadrome, Mario Kart

* Racing Toon/Fantasy
    + Fanciful racing environments and/or physics
    + Gripshift

> * Racing Traditional
>     + Straight-up realistic racing
>     + Need for Speed

* Retro/Greatest Hits – Arcade
    + Arcade classics

> * Retro/Greatest Hits – Computer
>     + Computer classics

* Retro/Greatest Hits – Console
    + Console classics

> * Sims
>     + System simulator, life simulator, work simulator, etc
>     + SimCity, Nintendogs

* Sports: Extreme
    + Themed around ‘extreme’ sports
    + SSX

> * Sports: Fantasy
>     + Themed around make-believe sports (fantasy, future, etc)
>     + Cyberball

* Sports: Pub
    + Themed around real pub games
    + Darts, Billiards

> * Sports: Traditional
>     + Themed around popular sports
>     + Football, basketball

* Strategy
    + Turn-based or realtime games of strategy; little to no twitch element
    + Advance Wars
> 4 votes

# Answer
Extra Credits has devoted an episode to so-called 'core aesthetics', the main reasons a game appeals to us, and provides a non-exhaustive list as a more accurate basis for defining genres than what we normally base our distinctions on. Nearly all games I've played fall into a few of these categories:

* Sensation
* Fantasy
* Narrative
* Challenge
* Competition
* Fellowship
* Discovery
* Expression
* Abnegation
> 4 votes

# Answer
There are numerous "basic activities" that are found in games, usually dependent on the genre. For example, "empire management" games like Sim City, Civilization, and Dwarf fortress require the player to macro or micro manage cities and/or people. In these games, the player's goals generally involve keeping his "empire" stable and growing.

However, games can be based off just about any kind of activity. There are video games about dancing, exercising, sports, board games, card games, etc. Multiplayer can expand these into cooperative or competitive games. Even the activities you mentioned can be combined into unique activities, or broken down into simpler activities.

LostGarden.com has several articles that go very in depth into this subject. Here's one I particularly like.
> 0 votes

---
Tags: game-design
---


# Question
Title: Required Throwable found SlickException when initializing states
When I write this statment throws a SlickException. I got an error and this is the message: `required Throwable found SlickException`. This my code :

```
public void initStatesList(GameContainer gc) throws SlickException{
    this.getState(menu).init(gc, this);
     this.getState(menu).init(gc, this);
     this.enterState(menu);
}

```

# Answer
The initStateList method is there for you to add states, not initialize them. Slick will initialize them for you and enter the first state you added automatically.

It should look like this:

```
public void initStatesList(GameContainer gc) throws SlickException {
    addState(new YourFirstState();
    addState(new YourSecondState();
    ...
    }

```

Then slick will automatically initialize them and enter "YourFirstState"
> 1 votes

---
Tags: java
---


title: Android Virtual Pet Gameloop

text:
# Question
Title: Android Virtual Pet Gameloop
Hello I'm looking for a bit of advice in which way is the best to proceed creating my applications 'gameloop' - It doesn't want to be a game loop in the truest sense since I'm not really rendering any graphics just displaying some animated gifs.

My goal is to have a task that runs every 30 minutes that decrements pet variables

```
Example Method
passTime { <pets health> = <pets health> - 1; <pets hunger> = <pets hunger> -1; <pets exp> = <pets exp> + 5; } et

```

c. I was wondering the best way to go about this? AsyncTask will be of no use since this ideally wants to be running even when the app isn't.

I would rather use an IntentService subclass rather than a Service subclass but I can't seem to get the IntentService to run through a pendingIntent via the AlarmManager.

So I'm asking advice on the best way to proceed from the ground up with this. Thank you!

# Answer
> 1 votes
If you are looking for your 'tick' method to be called every X minutes, you could look at using a timerTask. This will allow for your method to be called at a specific time.

You can find some more information and an example here: http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html

---
Tags: java, android
---


# Question
Title: Best place for learning how to write games in Unity3d
What's the best place for tutorials & other learning resources for unity3d?

# Answer
> 16 votes

# Answer
> 13 votes
In addition to the documentation and the unity forums, I recommend the Unity question & answer site:

http://answers.unity3d.com/

# Answer
> 8 votes
There's a giant community wiki of tutorials and resources on Unity's answer's site:

http://answers.unity3d.com/questions/12321/how-can-i-start-learning-unity-fast-list-of-tutori.html

# Answer
> 6 votes
I've just started following these in my own learning, and found them to be top notch, tons of videos already added:

http://unity3dstudent.com

# Answer
> 6 votes
I've been following a free video tutorial series by the "Tornado Twins" on YouTube. It's turned out to be a really excellent series that covers quite a lot over the course of writing a simple 3d adventure game. I would **highly** recommend this to others.

http://www.youtube.com/user/TornadoTwins

Also at Keyframe's recommendation I've also started following the 2.5D video series at 3dBuzz but while I'm finding it informative I'm not a fan of their presentation style as there's a lot of fluff and something that could be presented in 10 minutes takes 20 minutes with all the idle chit chat. But still very helpful.

# Answer
> 5 votes
Unity has it's own excellent documentation: http://unity3d.com/support/documentation/

# Answer
> 5 votes
When I was learning Unity, the most helpful thing was going through the Lerpz tutorial (http://unity3d.com/support/resources/tutorials/3d-platform-game), but then (and probably even more helpful) going through the FPS Shooter tutorial (http://unity3d.com/support/resources/tutorials/fpstutorial).

Going through those two tutorials helped immensely, more than any other tutorials, and even the Unity Development book.

# Answer
> 2 votes
I have a brand new Unity 4 course I put together for beginners on Udemy called Anyone Can Learn to Make a Game. https://www.udemy.com/unity-tutorial/

# Answer
> 1 votes
The unity forums also contain a wealth of information. You'll be hard pressed, starting out, to come up with questions that others before you didn't have as well, and it's a pretty helpful bunch overthere.

---
Tags: unity
---


title: Tiled map seen from an angle

text:
# Question
Title: Tiled map seen from an angle
I have working code to display a tiled map. It's composed of a `OrthogonalTiledMapRenderer` and an `OrthoGraphicCamera` :

```
camera.setToOrtho(false, WORLD_WINDOW_SIZE.x,
            WORLD_WINDOW_SIZE.y);

renderer = new OrthogonalTiledMapRenderer(tiledmap, 1 / TILE_WIDTH);

renderer.setView(camera);

```

So far so good. The map is rendered as seen from above:

My question is, how do I render it with the camera not facing right down to the floor?

Like this: \[Thanks to all GIMP developers :) \]

Is it possible? I tried `Camera.rotate(45)` but it rotates in the wrong axis. I can't set `Camera.direction` because of this - taken from `OrthogonalTiledMapRenderer.setView(camera)` documentation :

> Sets the projection matrix and viewbounds from the given camera. If
> the camera changes, you have to call this method again. The viewbounds are taken from the camera's position and viewport size as well as the scale. **This method will only work if the camera's direction vector is (0,0,-1) and its up vector is (0, 1, 0), which are the defaults.**

If I change the camera direction, the renders are weird or non-existant.

Is it possible to do so with the standard LibGDX api? If not, how can I do this? If not are there any workarounds to get the same effect?

# Answer
> 1 votes
I think you are looking for isometric view. You should use `OtrhographicCamera` as you are using now, but construct it using this constructor, passing `diamondAngle`

> `public OrthographicCamera(float viewportWidth,
>  float viewportHeight,
>  float diamondAngle)`
>
> Constructs a new OrthographicCamera, using the given viewport width and height. This will create a camera useable for iso-metric views. The diamond angle is specifies the angle of a tile viewed isometrically.

---
Tags: tiles, camera, libgdx, tilemap, viewport
---


title: Model too small in Orthographic view

text:
# Question
Title: Model too small in Orthographic view
This must be super-basic, but I don't know where the problem is, since I just started with 3D-Programming.

Why is my model "ballTest" so small on the screen?

```
private Model _model;
private Matrix view, proj;

//Initialize()
_model = Content.Load<Model>("ball test");
view = Matrix.CreateLookAt(new Vector3(0, 0, 10), new Vector3(0, 0, 0), Vector3.Up);
proj = Matrix.CreateOrthographic(800, 480, 0.1f, 30.0f);

//Draw
_model.Draw(Matrix.Identity, view, proj);

```

# Answer
You have to specify the scale of the model, depending on the size of your model you might have to increase or decrease it in size.

```
float scale = 1f; // No scaling, 0.5f = half size, 2f = double the size
Vector3 Rotation = Vector3.Zero; // No rotation
Vector3 Position = Vector3.Zero; // Default position = 0,0,0

Matrix world = Matrix.CreateScale(scale) *
               Matrix.CreateRotationX(MathHelper.ToRadians(Rotation.X)) *
               Matrix.CreateRotationY(MathHelper.ToRadians(Rotation.Y)) *
               Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation.Z)) *
               Matrix.CreateTranslation(Position);

```

then

```
_model.Draw(world, view, projection);

```
> 0 votes

---
Tags: xna, c#, windows-phone-8
---


# Question
Title: Game Design Issue: Special items implementation
I have a Match Two game similar to the bejeweled board. I am rewarding the player on speed of score. If he scores X in Y time , he gets a bomb. The time window is not rolling but discreat.

I check what the users score was in last X seconds after every Y seconds and reward him. The issue is the reward is a bomb which explodes 9 tiles. (I've dumbed down the score of the tiles exploded by bombs) Now that score will be counted in the next user score check and if the user made of more pair he will be given another bomb and this continues.

So once the user gets a bomb it's very easy to get it again and keep getting it. Which ruins the uniquness of the bomb. If I say hey let's not count the score because of the bomb that way the user will have to start all over again to get a bomb and if we have Z types of bombs one better than the other it would be impossible for the user to get all the bombs. If the score keeps on restarting.

I'm having a hard time finding the middle ground in it. Any ideas?

Also for special items, what seems to be better roll over time windows or static time windows?

# Answer
> 6 votes
One solution to this problem might be to gradually decrease the amount of time allowed for the player to get the required score and/or gradually increase the score required to get a bomb for a short period of time.

For instance, if a player earns a bomb, and the score of that bomb contributes to the combo score of the next time window, that time window will be shorter and the combo score required to earn the next bomb will be larger. After that time window elapses, the required time and combo score could be reset.

# Answer
> 2 votes
> So once the user gets a bomb **it's very easy to get it again and keep getting it. Which ruins the uniquness of the bomb**. If I say hey let's not count the score because of the bomb that way the user will have to start all over again to get a bomb and if we have Z types of bombs one better than the other it would be impossible for the user to get all the bombs. If the score keeps on restarting.

You could make it so that after a player gets a specific kind of bomb, he can't unlock the same bomb again until Z seconds have passed. Thus, the player could still utilize the bomb to gain enough score to gain other types of bombs, but wouldn't continuously just keep getting the same one he used.

---
Tags: game-design, game-mechanics
---


# Question
Title: Augment an existing game with touch gestures
I want to enhance Homeworld 2 gameplay with touch gestures. The game is running on Windows.

So, two questions:

1. Is it possible to wrap the game with a program that would capture touch gestures, convert it to keyboard and mouse input and send it to the game?
2. How would I approach this task? Using 3rd party libraries, making my own, or something built in to Windows?

# Answer
> 2 votes
**Yes** it is likely possible. What you need to do is hook the mouse, (basically the same thing key loggers and event monitors do), interpret the mouse motions in *your process*, and then simulate event input to the Homeworld 2 window using SendMessage.

What should happen is you should be able to attach your app as a kind of "virtual keyboard" into the Homeworld 2 game window, and the commands you send via `SendMessage` need to be picked up by the game, as if the player were pressing those keys on the keyboard.

This may take some experimentation and implementation is unlikely to be as straightforward as it sounds here.

---
Tags: software-engineering, windows, modding, touch
---


title: Shadow artifacts caused by filtering

text:
# Question
Title: Shadow artifacts caused by filtering
I'm working on a shadow-mapping implementation for an OpenGLES 2.0 environment (Stage3D in Flash to be exact). This is how my current implementation works:

1. Render the scene to backbuffer.
2. Render depth map from the light's point of view.
3. Render shadows on a texture from the camera's point of view.
4. (Do blur and other effects to improve the shadow texture, not implemented yet)
5. Render the shadow texture to the backbuffer with multiply.

Some pictures to help explaining. Note that the bunny is floating in the air on purpose.

Shadows rendered on a texture from the camera's view.

The final scene with shadow texture rendered on top with multiply.

The problem is the unshadowed pixels at the bottom of the bunny. Because the shadow texture is rendered with linear filter, the edge of the shadow loses its sharpness. This is mostly a good thing but not everywhere. I would like to do more filtering effects on the shadows but they would cause even bigger issues.

I haven't encountered this kind of problem in any tutorials or forums so either there is an obvious solution for this or there is something wrong with my approach. The question is, can I solve this somehow using my current approach? Or is there a bigger gap in my method?

# Answer
> 3 votes
In general, the way that shadow maps are supposed to work is not by combining a screen-space shadow texture with a rendered texture. In that case you will always get awkward artifacts at boundaries between fully-lit areas and fully-shadow areas that have similar z-values. These are the areas where you're sampling at a boundary in the shadow map.

The preferred method is to use a shadow-map as an additional texture to the scene that you're rendering. In this way, before you render a final pixel, you map that pixel's position to the coordinate space from the light's point of view, and test it against the z-value in the shadow map. From here you can multi-sample the shadow map and get a better idea whether or not the pixel is in shadow. The general algorithm is:

1. Render depth map from the light's point of view.
2. Render the scene from the camera's point of view and test whether or not pixels are in shadow

There is a great tutorial available about this (in regular OpenGL but the techniques still apply to ES 2.0) here:

http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/

---
Tags: 3d, opengl-es2, shadows, shadow-mapping, stage3d
---


# Question
Title: Scaling along an arbitrary axis (Dealing with non-uniform scale)
I'm trying to build my own little engine to get more familiar with the concepts of 3D programming.

I have a transform class that on each frame it creates a Scaling Matrix (S), a Rotation Matrix from a Quaternion (R) and concatenates them together (S\*R). Once i have SR, I insert the translation values into the bottom of the three columns. So i end up with a transformation matrix that looks like:

```
[SR SR SR 0]
[SR SR SR 0]
[SR SR SR 0]
[tx ty tz 1]

```

This works perfectly in all cases except when rotating an object that has a non-uniform scale.

For example a unit cube with ScaleX = 4, ScaleY = 2, ScaleZ = 1 will give me a rectangular box that is 4 times as wide as the depth and twice as high as the depth.

If i then translate this around, the box stays the same and looks normal.

The problem happens whenever I try to rotate this scaled box. The shape itself becomes distorted and it appears as though the Scale factors are affecting the object on the World X,Y,Z axis rather than the local X,Y,Z axis of the object.

I've done some pretty extensive research through a variety of textbooks (Eberly, Moller/Hoffman, Phar etc) and there isn't a ton there to go off of. Online, most of the answers say to avoid non-uniform scaling which I understand the desire to avoid it, but I'd still like to figure out how to support it.

The only thing I can think off is that when constructing a Scale Matrix:

```
[sx 0  0  0]
[0  sy 0  0]
[0  0  sz 0]
[0  0  0  1]

```

This is scaling along the World Axis instead of the object's local Direction, Up and Right vectors or it's local Z, Y, X axis.

Does anyone have any tips or ideas on how to handle construction a transformation matrix that allows for non-uniform scaling and rotation?

Thanks!

# Answer
If you are in a directx api which uses row major matrices (which is what your matrix shown above is ... i.e. the tx, ty, tz is the translation vector and it is laid out on a row) then you would need to do `scale * rotation`. This applies scale before rotation when dealing with row major matrices.

However, if you are in a opengl or other column major api, then you need to do `rotation * scale` which also applies scale before rotation with column major matrices.

I just tested an example out in opengl. I had a skew scaling matrix followed by a rotation. Doing `rotation * scale` gave me the correct results, but doing `scale * rotation` gives the skewed results you are talking about. So my guess is whatever context you are in is using column major matrices, and you need to reverse you matrix multiplications.
> 1 votes

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


# Question
Title: Reward volatility of League of Legends matchmaking system
According to this article in league of legends matchmaking there's an average of 50/50 chances of winning or loosing a game based on how system ranks a specific account (player skill). However this implies that a player is expected to loose at least half of his games (provided that he's not a student of the game) or at most he'll win 75% of the games (that's ranked top rated guys and the highest win rate I've seen in my region, so should be a feasible boundary).

However, the latter is rather rare since not so many people actually achieve that skill level (that can also be observed by going through ranked statistics) and the former is also not a constant since a) it's also in the algorithm and a queue of 1 min is most likely not a 50/50 and b) there are situations where it is extremely obvious that a player was placed against a way stronger team or vice verse.

An example from my practice is that I had a win rate of 88% which severely dropped after about one ore two weeks (to around 71%) and it rose again in a week or so with me learning nothing (I literally didn't). So, during such drops a player reward expectation is not met which results in negative attitude (taken to extreme in some cases, as was also observed). Some people were literally saying: "I hate the game" and they kept playing.

**So the question is:** why? why is it that with such reward volatility people still keep playing? (please, give a rigorous proof, if any, supplied with references presumably from behavioral psychology)

**P.S.:** I do not have any empirical data, so I realize this might be only a feeling as well as the fact that mostly I observed it through my account (not even lvl 30) and in my region. I also understand that most likely they are using statistical learning algorithms which obviously require data and will put a player to his actual rating as number of games grows (theory of big numbers).

# Answer
If you want a behavioral psychology answer, then here's one - if the player isn't sure if he'll win the next game, he's more likely to try one more game. If he lost, he thinks "Maybe this I'll be lucky". If he won, he thinks "Ooooh that was awesome, one more".

You actually **need** a 50/50 win/loss ratio to keep the players engaged. The effect is basically the same as with slot machines, and is known as a variable-ratio reinforcement schedule. Of course, slot machines don't have a 50/50 ratio; there are other effects with slots (like the chance of a huge win, and very fast play time).

The crucial element in a variable ratio schedule is uncertainty - the brain never knows what the result of the current match will be. This is what keeps the game exciting, whearas a fixed-ratio schedule would just mean "every second game is a win", which is just... plain boring.

While not really used in LoL, the other common schedule in games is variable-interval. For example, in MMORPGs you can farm monster for an hour or a day before you get the uber-loot you are looking for. The activity is more or less constant, you just don't know how long it will take.
> 5 votes

# Answer
There are other, more powerful factors than just "reward". In the case of competive multiplayer games such as LoL the most important one is the social component, you will likely have friends who play LoL too, and that alone will make the player much more likely to continue playing even if they are fed up with it. Another is the overcoming of challenge, and competition. You want to become better so you play more. And you want to show others how good you are.
> 1 votes

# Answer
A win rate of 50% is the only number a matchmaking system can possibly aim for. As an example, if the system were set up to create matches in which players have an estimated 60% chance of winning, then from the pigeonhole principle, it follows that there must be a probability of at least 20% of the match ending with both teams victorious. *League of Legends*, as most competitive games are, is zero-sum. For every match you win, someone else must lose.

Regardless of how your matchmaking system works, if the total number of wins equals the total number of losses, the average win ratio will always be fixed to exactly 50%. That doesn't mean everyone is winning only half the time, but if your win rate is above average, someone else's must be below.

Better players will naturally gravitate towards high numbers, worse players to low. That's fun for neither. It means better players are insufficiently challenged and are conditioned to expect a win, decreasing the rewarding experience when they do and increasing the frustration when they don't. On the other end of the spectrum, frequent losses disappoint, people feel they are not given a fair chance to compete and new players are alienated from the game.

Generally, the less certain the outcome of a match is in advance, the more exciting the game will be. That is what a matchmaking system hopes to achieve. By putting players against opponents of their own skill level, it does not ensure the win rate averages close to 50%, but it lowers the variance in win rate across skill levels.

Not necessarily to a minimum, by the way. A matchmaking system could actively have new players face veterans instead of other rookies, so their win rate starts off low and increases as they get better at the game. This pushes the ratio of seasoned players to an optimum between 50% and 100%, whereas new players experience a sense of progression.

In conclusion, why aim to keep everyone winning only half the time? The alternative is to have some win too often, others not enough.
> 1 votes

---
Tags: game-mechanics, behavior, matchmaking, psychology
---


# Question
Title: Are models on 3D warehouse free of copyright?
Are models on sketchup's 3D warehouse free to use for personal or commercial work? I haven't been able to find copyright information on the site.

# Answer
> 5 votes
I'm not a lawyer, but this is my interpretation:

Found in the Terms of Service linked in the footer of the page you linked, this is the notice given to people uploading their content:

> The Services allow you to submit content, including 3D models in the SketchUp and Keyhole Markup Language (KML) formats. You retain ownership of any intellectual property rights that you hold in that content. In short, what belongs to you stays yours.

...

> Rights granted to other end users of the Services. You give other end users of the Services a perpetual, sublicensable, irrevocable, worldwide, royalty-free, and non-exclusive license to reproduce, adapt, modify, translate, publish, publicly perform, publicly display and distribute Existing Geolocated Models, Existing Non-Geolocated Models, New Models and related content and derivative works thereof which you submit, post or display on or through, the Services.

You fall into the "other end users of the Services" group. So you have the right to pretty much do whatever you want. But you will not own the intellectual property rights.

---
Tags: 3d-meshes
---


# Question
Title: What knowledge do I need to learn Unity?
What do I need to get into using Unity? Do I need some knowledge in any language in particular? Can I just get to know the program with tutorials? What would you recommend?

# Answer
> 2 votes
The only knowledge you need is how to operate your web browser, read English and a link to the Unity Manual. (Judging by your question here, I think you have the first two).

From there, you can learn everything you need to know about what you don't know yet. Pick it up and learn as you go with tutorials and further searches on the internet for the things you're not sure about.

# Answer
> 0 votes
You can learn quite a bit from online tutorials and by visiting the Unity site and having a peak at the documentation. You can code in Unity using UnityScript(JavaScript), Boo and C#. Many beginning developers will opt to code in UnityScript and as they get more comfortable many switch over to C#.

I created a course for beginners using Unity 4 you may be interested in on Udemy. You can find more info about it here https://www.udemy.com/unity-tutorial/.

Welcome to the Unity :-)

---
Tags: unity
---


# Question
Title: 2D animation: Animated 3D models or sprites with animation frames?
Starting out with new project, I am stuck choosing between:

* 3D textured model animated directly through the renderer
* 2D sprites and drawing each animation frame

The game will be 2D platform, I would like the pros and cons of each method to help make a decision between the two.

# Answer
> 4 votes
The pros of using animated sprites are:

1. **Ease of use**: simply switch each frame to animate a sprite. There are already many tools developed for generating sprite sheets and animating them, many of them available from the Unity Asset Store. Doing so opens up a huge amount of productivity for a simple game.
2. **Easy collision detection**: Since each sprite is defined by a frame, it is trivial to use that frame as a bounding box in your world. If your sprites have alpha, it's not too difficult to preprocess the non-transparent pixels to use as bounds. Comparing collision against bounding boxes is very fast as well.

The cons of using animated sprites are:

1. **Memory Usage**: If you have a lot of sprites with a lot of animation, you're going to need a lot of memory to store each of those images. This can quickly get out of hand if you're targeting a mobile device or you plan on having many different animated sprites on your screen at once. This can be remedied by techniques such as texture compression. For small projects (or projects with low quality sprites) this is usually not an issue.
2. **Smoothness**: There is no ability to ease animation with sprites. In general, you will have choppy animations if you do not animate everything to an extremely fine level. This is usually not an issue for games with 8-bit graphics, but if you're debating between using sprites and animated skeletal models, you should be aware that you're going to have to have a lot of animation frames to get smooth looking animations.
3. **No animation blending**: This folds into the previous point, but you're likely not going to be able to do things like look in a certain direction while jumping if you use sprites for animation. If you want to split up the abilities your character can do, or have your animations interact with things in your world (like grabbing a door handle), then you will need a separate sprite for each height of door handle. Again, this isn't too much of a problem if you have a simple game, but it can easily become one if you're thinking about something more complicated.

The pros and cons for animation blending are more or less the inverse of the pros and cons for sprite usage. In general, you want to use animated models for

1. **Animation blending**: For example, if you want to be able to move and shoot a gun in a particular direction at the same time and want it to look good, you can use animation blending. This is a little tricky to implement, but Unity has these features built in for you so you don't need to worry too much about it.
2. **Smooth animations**: Everything is interpolated, meaning that everything looks smooth and nice. Transitioning from one animation to another is fluid and looks good.

The cons are:

1. **Development**: You need a separate skill set to properly implement animated skeletal models. This is something that is sometimes hard for people that are used to sprite animation to handle, but with enough practice everything works out.
2. **Implementation**: Although Unity will handle most of the heavy lifting for you, if you want to implement skeletal animation, you have to figure out how to specify which animations will blend with which other animations and integrate that into your game and event system. This isn't a trivial programming task, but again, Unity should take care of that.

My advice is to use sprite animation for anything that isn't an overly complicated object. Things like power-ups, and simple monsters are great for sprite animation. If you have a very complex main character that can do a lot of different things, these are triggers that should say, "Oh, I should probably use skeletal animation for this guy".

---
Tags: animation, sprites, models
---


title: What is Ramp Shading or Lighting?

text:
# Question
Title: What is Ramp Shading or Lighting?
What is ramp shading or lighting and how does it work? Is it different than toon shading or is it the same concept? How is specularity calculated differently for ramp shading versus blinn-phong or lambert?

# Answer
In traditional Blinn/Phong shading, you calculate the diffuse term for a pixel by measuring the cosine of the angle between the normal at the surface and the direction of the light. So, in this case, a simple shader would look something like this:

```
float DiffuseCoeff(in float3 pos, in float3 normal, in float3 lightPos) {
    float3 lightDir = lightPos - pos;
    lightDir.normalize();

    return max(0.0, Dot(lightDir, normal));
}

```

In ramp shading, the idea is to modulate the diffuse coefficient by a 1D lookup texture. Depending on what you put in this texture you can generate different effects. Hence, our shader function to compute the diffuse coefficient becomes:

```
texture1D rampTex;
float DiffuseCoeff(in float3 pos, in float3 normal, in float3 lightPos) {
    float3 lightDir = lightPos - pos;
    lightDir.normalize();

    // Map value from [-1, 1] to [0, 1]
    float rampCoord = Dot(lightDir, normal) * 0.5 + 0.5;
    return tex1D(rampTex, rampCoord);
}

```

For example, if we wanted to implement a cell shader, what we could do is generate a ramp texture that emulates a step function:

You can use the same idea to generate different effects for the specular lighting as well. "Ramp" shading really only refers to the idea of modulating a shading value by a texture.

**EDIT**: Team Fortress 2 uses a ramp shader in their rendering. You can check out the details in this paper:

http://www.valvesoftware.com/publications/2007/NPAR07\_IllustrativeRenderingInTeamFortress2.pdf

Look under Section 5, at the subsection entitled "Diffuse Warping Function"
> 22 votes

---
Tags: shaders, lighting
---


title: Changing colour while keeping gradient

text:
# Question
Title: Changing colour while keeping gradient
I'm making a Flash game with ActionScript 3 and I have a square with a gradient applied to it. I am trying to programmatically changing the colour of the square depending on time, for example, some times it is orange, some times it is red, but it must always fade to black at the bottom.

The problem is, I'm using ColorTransform (as per here) but it seems to overwrite the gradient and simply fill the square with the solid colour. This isn't what I want. I want the colour that is chosen to fade to black at the bottom, like the original gradient.

How can I do this? Is there a way to only change the "hue" of the symbol (IE: not filling the entire thing with a solid colour), or will I have to reapply a gradient programmatically, with the desired colours?

# Answer
That should be pretty simple with the `ColorTransform` class. You can't simply set the `color` property though, you need to make use of the multipliers of the `ColorTransform`. Example:

```
function colorize(object:DisplayObject, color:uint):void {
    // get individual color components 0-1 range
    var r:Number = ((color >> 16) & 0xff) / 255;
    var g:Number = ((color >> 8) & 0xff) / 255;
    var b:Number = ((color) & 0xff) / 255;

    // get the color transform and update its color multipliers
    var ct:ColorTransform = object.transform.colorTransform;
    ct.redMultiplier = r;
    ct.greenMultiplier = g;
    ct.blueMultiplier = b;

    // assign transform back to sprite/movieclip
    object.transform.colorTransform = ct;
}

```

Then you can simply color your sprite like this:

```
colorize(mySprite, 0xffaa00); // colors sprite orange

```

Instead of tinting the whole sprite in the given colors, it uses multiplication. So if you have a white pixel (`1`) it will have the given color, while a black pixe (`0`) will remain black (`0 * color = 0`)
> 1 votes

# Answer
You can use two layers: the top layer contains a gradient that goes from fully transparent to black, and the bottom layer contains the colour that you are changing.
> 2 votes

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


title: C++ formatted serialization

text:
# Question
Title: C++ formatted serialization
I've decided it's time to implement serialization in my simple engine but this has caused me many headaches for the past couple of days/weeks. My engine uses an entity/component based approach similar to what is described in the T=Machine blog.

To keep it simple, my first goal was to implement serialization of entities. Since I'm going to use Lua for scripting, I thought it would be nice to serialize entities into Lua tables. Unfortunately, I find the information that is available on serialization in C++ is rather scarce. After many days of thinking I found one approach which is working for my implementation and is described here.

In essence, I have an EntityManager class from which I request new entities. This class holds entity as well as pointers of type BaseComponent from which all components derive. Because I store components as base pointers, I couldn't use a friend class for serialization, but had to make the BaseComponent inherit from a Serializable class, which has pure virtual serialization methods.

So, this is not that bad, I just have to inherit from the Serializable class and implement the serialization method. To support deserialization though, I have to do a few tricks according to the last link. That is, I have to include a static object inside each component whose sole purpose is to populate a map from component names to *constructors*. Here is a generic example (and please ignore any possible errors),

```

/* Base.h */
struct Base: public Serializeable{
    static std::map<std::string, std::function<Base*(void)> > deriveds;
    virtual ~Base(void){}
};

/* Derived.h */
template<class T>
struct add_map_entry{
    explicit add_map_entry(std::string name){
        Base::deriveds[name] = [](void) -> Base* {
            return new T;
        };
    }
}

class Derived: public Base{
public:
    int x;
    int y;
    Derived(void){
        std::cout << "Derived created" << std::endl;
    }
    void serialize(std::ostream&);
    static add_map_entry<Derived> adder_;
};

```

Then in the implementation file I also have to initialize the static map of the base class as well as the static object of each derived class.

I find this quite a mess and although it could probably be improved with the use of macros, I can't help to wonder if there are better ways. How do you handle this kind of formatted serialization?

PS: Please don't recommend changing to a more flexible programming language :) !

# Answer
> 1 votes
I'm not saying either your approach is good or not! Just simply note that it's very complex and might later give you a headache if you even need to change simplest things. But there is an issue with your current implementation. C++ compilers doesn't care about the order they initialize static variables. this won't cause that much problem with primitive types (integers/float/pointers/etc.) but it definitely might cause a problem in your case. simply because when `Derived::adder_` is being initialized, `base::deriveds` might not be initialized yet. The solution is to use late initializers, something like providing a function to add a new entry in your Object list, and in that forcing derived function to be initialized. here is your code with my suggestion applied:

```
/* Base.h */
struct Base: public Serializeable{
    static std::map<std::string, std::function<Base*(void)> >* deriveds;
    template <class T> static addEntry(add_map_entry<T>&)
    {
        if (deriveds == nullptr)
            deriveds = new std::map<std::string, std::function<Base*(void)> >();
        (*deriveds)[name] = [](void) -> Base* {
            return new T;
        };
    }
    virtual ~Base(void){}
};

/* Derived.h */
template<class T>
struct add_map_entry{
    explicit add_map_entry(std::string name){
        Base::addEntry(*this);
    }
}

class Derived: public Base{
public:
    int x;
    int y;
    Derived(void){
        std::cout << "Derived created" << std::endl;
    }
    void serialize(std::ostream&);
    static add_map_entry<Derived> adder_;
};

```

if I remember correctly all global variables are guarantied to be initialized to zero before the application starts (correct me if I'm wrong) so you won't have such mentioned problem with this code.

---
Tags: c++, component-based, lua, serialization, code-reflection
---


# Question
Title: I want to start making 2D Games with C++ or #C
I know C++ pretty well, I think - polymorphism, vectors, templates, and more. I also know C#.

I want to program a 2D game, but not like those programs where you click a button or two, and you suddenly have a game running.

Though I feel pretty lost by googling.

I've found SFML for C++, though I had trouble finding a good tutorial on 2.0...

Then I searched for a C# one, and found Unity and XNA, though I'm not sure which one should fit my needs better.

So generally, I'm really confused and not sure how to start.

Btw, I'm open to other suggestions (like Java), and also I want to create at first very simple 2D games, like Tic Tac Toe and such, and move to more complicated one later.

Thanks for your help!

# Answer
> 1 votes
For c++ there is SFML or SDL. SDL is my choice as i started with that one my self. To get started here is a good site for development : http://lazyfoo.net/SDL\_tutorials/index.php

In C# there is XNA, and there is tons of great tutorials for that aswell. http://www.riemers.net/

It´s mostly up to you what you pick, but i'd go with XNA first and after a while when you got good beef on your legs, jump into C++.

* Unity is more of a engine rather than a framework. This will let you focus mainly on building your game, but i doubt you will have as much fun with unity than you will with C++/C#.

---
Tags: xna, c++, c#, unity, sfml
---


# Question
Title: Creating a simple 2d engine (C++), best way to create an Sprite class?
Since MS announced that they are not give more support to XNA , for me was an opportunity to start to learn DirectX , so i wanted to learn DX11, i was following this tutorials

http://www.rastertek.com/tutdx11.html

i want to build a simple 2D engine while im learning with basic thing,like render an sprite based on a spritesheet, ,animate it, scale, rotation, flip image

I started creating some simple basic structure,

* Engine Class, this hold the initialization of the Window basically
* RenderManager class, this hold all the DX stuff, initialize it, create the swapchain, store the device , etc

So now my next step is create the Sprite class , i wanted to create an method called "Quad2D" inside my RenderManager, so i can use it on my render method in my sprite class

```
//This is not actual code, is just oh i want to approach this
class Sprite{

public void Render(RenderManager *rm){

    rm->Quad2D(Texture,Position,Width,Height);

}
}

```

i have some experience with OpenGL and Directx9 and with those, it was easy to approach this, i just needed to create an Array with the vertices, send to the VertexBuffer, bind the Texture, and done

but because now DX10 and DX11 not used fixed pipeline, and you need create this with more advanced stuff (Shaders)

i stopped in here http://www.rastertek.com/dx11tut11.html , i can see how to render the image and everything, but i was thinking, do i need to create an separate Class just to render a Quad? if so, is this going to compile the shader everytime is used?, well one solution maybe is just declare an static atribute for the ps and vs and it will shared the same compiled shader within the instances

so i would like to hear how do you manage your Sprite class?

if is it necessary, i can attach my source code, but it doesnt has too much, just open a window

Note: i want to know how to do it in DX11, please dont reply, (used DX9,OpenGL,DX10, etc..)

# Answer
> 3 votes
I based a good deal of my Engine from the Rastertek tutorials too. For the shaders, I don't see why you'd need to compile them for each Quad... My solution was to store the shader in a Graphics class, and pass the information into the render function of the shader.

This is my layout (Sorry for the length of this, I'll try to trim out lots.)

```
bool TextureShader::render(ID3D11DeviceContext* deviceContext, int indexCount, const     XMMATRIX& worldMatrix, const XMMATRIX& viewMatrix,
                                               const XMMATRIX& projectionMatrix, VEngine::Graphics::DirectX11::Material* material)
{
    bool result;

    // Set the shader parameters that it will use for rendering.
    result = setShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, material);
    if(!result)
            return false;

    // Now render the prepared buffers with the shader.
    renderShader(deviceContext, indexCount);

    return true;
}

bool TextureShader::setShaderParameters(ID3D11DeviceContext* deviceContext, const      XMMATRIX& worldMatrix,
                                       const XMMATRIX& viewMatrix, const XMMATRIX& projectionMatrix, ID3D11ShaderResourceView* texture)
{
    HRESULT result;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    MatrixBuffer* dataPtr;
    unsigned int bufferNumber;

    // Transpose the matrices to prepare them for the shader.
    XMMATRIX tWorldMatrix(XMMatrixTranspose(worldMatrix));
    XMMATRIX tViewMatrix(XMMatrixTranspose(viewMatrix));
    XMMATRIX tProjectionMatrix(XMMatrixTranspose(projectionMatrix));

    // Lock the constant buffer so it can be written to.
    result = deviceContext->Map(_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if(FAILED(result))
    {
            return false;
    }

    // Get a pointer to the data in the constant buffer.
    dataPtr = (MatrixBuffer*)mappedResource.pData;

    // Copy the matrices into the constant buffer.
    dataPtr->world = tWorldMatrix;
    dataPtr->view = tViewMatrix;
    dataPtr->projection = tProjectionMatrix;

    // Unlock the constant buffer.
    deviceContext->Unmap(_matrixBuffer, 0);

    // Set the position of the constant buffer in the vertex shader.
    bufferNumber = 0;

    // Finanly set the constant buffer in the vertex shader with the updated values.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1, &_matrixBuffer);

    deviceContext->PSSetShaderResources(0, 1, &texture);

    return true;
}

```

And, for the Graphics class which calls it.

```
bool DX11::render()
{
    XMMATRIX viewMatrix;

    cleanRenderQueues();

    // Generate the view matrix based on the camera's position.
    _camera->render();

    // Get the world, view, and projection matrices from the camera and d3d objects.
    viewMatrix = _camera->getViewMatrix();

    XMMATRIX projectionMatrix = getProjectionMatrix();

    XMMATRIX orthoMatrix = getOrthoMatrix();
    bool result;

    disableZBuffer();
    enableAlphaBlending();
    for(unsigned int i(0); i < _renderQueue2d.size(); i++)
    {
            XMMATRIX worldMatrix = getWorldMatrix();

            _renderQueue2d[i]->render(_deviceContext);
            result = _textureShader->render(_deviceContext, _renderQueue2d[i]->getIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
                    _renderQueue2d[i]->getTexture());
            if(!result)
                    return false;
    }

//...More here for 3d

    return true;
}

```

As you mentioned, I've created a Sprite class, which contains a simple Quad, and a texture that I pass through to the shader.

Sprite class is essentially this (Update buffers is pretty much identical to the one in the Rastertek tutorials. Ignore the namespaces and the interface.

Header

```
/*--------------------
----INCLUDES
----------------------*/
#include <d3d11.h>
#include <xnamath.h>

/*--------------------
----MY INCLUDES
----------------------*/
#include "Texture.h"
#include "../IBitmap.h"

namespace VEngine
{
    namespace Graphics
    {
            namespace DirectX11
            {
                    class Bitmap : public IBitmap
                    {
                    private:
                            struct VertexType
                            {
                                    XMFLOAT3 position;
                                    XMFLOAT2 texture;
                            };

                    public:
                            Bitmap();
                            Bitmap(const Bitmap&);
                            ~Bitmap();

                            bool initialise(ID3D11Device*, int, int, const char*, int, int);
                            void shutdown();
                            bool render(ID3D11DeviceContext*);

                            int getIndexCount();
                            ID3D11ShaderResourceView* getTexture();

                            std::array<int, 2> getPosition();
                            std::array<float, 2> getRotation();
                            void setPosition(const int&, const int&);
                            void setRotation(const float&, const float&);
                            void setImageWidth(const int&);
                            int getImageWidth();
                            void setImageHeight(const int&);
                            int getImageHeight();

                            void setTextureFile(const char*);

                    private: //functions
                            bool initialiseBuffers(ID3D11Device*);
                            void shutdownBuffers();
                            bool updateBuffers(ID3D11DeviceContext*);
                            void renderBuffers(ID3D11DeviceContext*);

                            bool loadTexture(ID3D11Device*, const char*);
                            void releaseTexture();

                            bool createVertexBuffer(ID3D11Device* device, VertexType* vertices);
                            bool createIndexBuffer(ID3D11Device* device, unsigned long* indices);

                    private: // variables
                            ID3D11Device* _device;
                            ID3D11Buffer* _vertexBuffer;
                            ID3D11Buffer* _indexBuffer;
                            Texture* _texture;
                            int _vertexCount;
                            int _indexCount;

                            int _screenWidth;
                            int _screenHeight;
                            int _bitmapWidth;
                            int _bitmapHeight;

                            int _x;
                            int _y;
                            XMFLOAT2 _rotation;
                            int _previousPosX;
                            int _previousPosY;
                    };
            }
    }
}

```

Implementation

```
bool Bitmap::render(ID3D11DeviceContext* deviceContext)
{
    bool result;
    result = updateBuffers(deviceContext);
    if(!result)
            return false;

    renderBuffers(deviceContext);

    return true;
}

void Bitmap::renderBuffers(ID3D11DeviceContext* deviceContext)
{
    unsigned int stride;
    unsigned int offset;

    stride = sizeof(VertexType);
    offset = 0;
    deviceContext->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);

    deviceContext->IASetIndexBuffer(_indexBuffer, DXGI_FORMAT_R32_UINT, 0);

    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    return;
 }

```

I'd recommend going through the Rastertek in order. There are a few issues I have with the tutorial, and I've drifted away from quite a bit of it's architecture in my newer builds, but they're incredibly useful.

---
Tags: c++, directx11
---


# Question
Title: Extension method must be defined in a non-generic static class when adding static bool function
I try to use first answer of Checking for alternate keys with XNA IsKeyDown but the compiler shows me Extension method must be defined in a non-generic static class. How can I fix this issue?

# Answer
The solution proposed by the given answer (https://gamedev.stackexchange.com/a/37637/18568) uses the C# language concept of Extension Methods. These are described in more detail here. What you are doing is effectively 'tacking on' another method to a pre-made class definition that you are unable to modify directly, due to it being supplied as part of a library, or in another form or situation such that the original class should not be edited directly.

To answer your question simply, the snippet of the `Any` method supplied in the post you linked above is incomplete. By requirement of the C# language, an Extension Method (identified by the use of `this` as a prefix of the first parameter) must be within a static class. The class type of the method parameter prefixed by `this` is the class to which the extension method applies; it essentially forces the method to be a member of that class, with the only difference being that the `this` keyword does not work within the method as it would for a traditional non-static method, and you must instead use the name of the `this`-prefixed parameter.

```
#if WINDOWS
namespace MyKeyboardExtensions
{
    public static class MyKeyboardStateExtensionClass
    {
        public static bool Any(this KeyboardState state, params Keys[] keys)
        {
            return keys.Any(state.IsKeyDown);
        }
    }
}
#endif

```

Following this, you need to make sure that you specify `using MyKeyboardExtensions;` wherever you want the extension method(s) to take effect. Keep in mind, also, that extension methods cannot access private variables of the extended class, since otherwise they'd just rip a hole in some pretty basic OOP principles.
> 1 votes

---
Tags: xna, xna-4.0
---


# Question
Title: Unity3D 3.5 pro - Moving the camera vs setting draw distance
I move the camera mostly via right-click + WASD, sometimes with \[shift\] if I want it to move faster. Occasionally, instead of moving my camera, it alters the draw distance / FOV / some visual aspect of the editing scene that causes trees and other object to disappear when I scroll enough, and eventually even the terrain starts disappearing. It is not m "zooming out". My camera does not move, the width and height of the FOV stays the same (one might say the depth is being altered though). What key am I hitting to cause this to happen, and is it possible to disable it?

side note: "keybinds" is probably the most *spot-on* tag for this question but it doesn't exist (surprisingly) and I lack the rep to create it.

# Answer
The camera type is preserved when you save your scene and will set itself the next time you open it. You have had your Scene window camera set to Isometric at some point in your scene and saved it. Restart your view layout by using the selection box top right of Unity3D or Shift+Left Click on the Axis widget box to switch between Isometric and Perspective.
> 1 votes

# Answer
Maybe your objects scale is to large, so when you're going backwards objects doesn't fit in your FOV. Try to rescale everything so that 1 game unit would be equal to about 1 meter.Let's say tree height should be about 4 units.
> 0 votes

---
Tags: unity, camera
---