# Question
Title: Where is the LocalizedFontProcessor in XNA?
I tried this tutorial to localize my XNA Windows Phone game, but I can't find the `LocalizedFontProcessor` in the drop-down list. Why is the `LocalizedFontProcessor` missing in the drop-down list? What is wrong?

In this picture you can see that the `LocalizedFontProcessor` is missing in the drop-down list:

Is there another way to localize a Windows Phone game?

**Edit: Here is my LocalizedFontProcessor class**

```
namespace LocalizationPipeline
{
[ContentProcessor]
class LocalizedFontProcessor : ContentProcessor<LocalizedFontDescription,
                                                SpriteFontContent>
{
    /// <summary>
    /// Converts a font description into SpriteFont format.
    /// </summary>
    public override SpriteFontContent Process(LocalizedFontDescription input,
                                              ContentProcessorContext context)
    {
        // Scan each .resx file in turn.
        foreach (string resourceFile in input.ResourceFiles)
        {
            string absolutePath = Path.GetFullPath(resourceFile);

            // Make sure the .resx file really does exist.
            if (!File.Exists(absolutePath))
            {
                throw new InvalidContentException("Can't find " + absolutePath);
            }

            // Load the .resx data.
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.Load(absolutePath);

            // Scan each string from the .resx file.
            foreach (XmlNode xmlNode in xmlDocument.SelectNodes("root/data/value"))
            {
                string resourceString = xmlNode.InnerText;

                // Scan each character of the string.
                foreach (char usedCharacter in resourceString)
                {
                    input.Characters.Add(usedCharacter);
                }
            }

            // Mark that this font should be rebuilt if the resource file changes.
            context.AddDependency(absolutePath);
        }

        // After adding the necessary characters, we can use the built in
        // FontDescriptionProcessor to do the hard work of building the font for us.
        return context.Convert<FontDescription,
                               SpriteFontContent>(input, "FontDescriptionProcessor");
    }
}
}

```

# Answer
Right click on your content project (`LocalizationContent`) in Solution Explorer. Select "**Add Reference**".

**Add a reference to your pipeline project (`LocalizationPipeline`) to your content project.**

Make sure the pipeline project is built. Right click it and select build.

Your `LocalizedFontProcessor` should now show up in the Content Processor list.

(You might also have to make your `LocalizedFontProcessor` class `public`, I'm not sure. Also, you can give it a nice name by setting it in the attribute: `[ContentProcessor(DisplayName = "My Localized Font Processor")]`.)
> 1 votes

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


title: Tutorial text without annoying user?

text:
# Question
Title: Tutorial text without annoying user?
I have tutorial text (which I plan to augment with voice-over later, but it must be text for now, because I have not contracted a VO actor yet).

The text presents itself in dialogs, which are like tweets (fewer than 140 characters each). The text is big and readable.

The text contains *vital instructions that step the user through what to do next*. In playtesting, a user would just press OK OK OK without reading the text. The final dialog would disappear, and the user would be without a clue what to do, because he didn't read the instructions. The game is expecting him to perform the task it just asked, and he doesn't know what it is.

I tried:

* putting in a counter (3), (2), (1), then when the counter disappears you can press ok. I think the counter is annoying/distracting
* graying out/disabling the button until 2-3 seconds have passed for each dialog of text
* completely hiding the ok button until 2-3 seconds have passed for each dialog of text

How can I better handle this problem of the user not reading the tutorial text before dismissing the dialog?

# Answer
> 33 votes
Don't have umpteen walls of text of tutorial. If you need more than a single small arrow on screen, you should really consider *why*.

"Why is the user clicking through dialog after dialog?" Wrong question. "Why are we showing multiple dialogs?" Right question.

You say the dialogs inform the user how to perform the task. The task is too big. The task should be "move here", "click this", "touch that", etc. *Not* "move here, touch your nose, rub your belly, look due North, hop on one foot, press Up, Up, Down, Down, Left, Right, Left, Right, B, A"

The instructions given need to be broken down into small, discrete parts. Done right, you can keep the instructions on-screen at all times or otherwise highlight the necessary bit. For example, in a game with a controller you could show a picture of the desired button to press on-screen until it's pressed. If you want the player to interact with an item, make it glow, bounce, or otherwise stand-out until interacted with. If you want to tell the player how to interact, pop up the right button/key when they're close enough (many games do this all the time anyway even outside of tutorials, especially ones with context-sensitive controls).

Another theme that you might have noticed to avoid text. Gamers are lazy creatures and they don't want to *read* instructions. Show, don't tell.

# Answer
> 21 votes
If your testers are just skipping your text, **you should do the same** \- take that as a clue to **eliminate it**.

Instead, craft your game such that it gives users a progressive learning experience that teaches them what they need to know.

On of my favorite games for this is the Half-Life series. You start out learning just how to walk. Then you need to learn to jump. And then you get a crowbar. They don't throw it in your hands and immediately make you fight with it, but instead you start out just breaking stuff just for fun - or perhaps to eliminate a simple barrier to your progress. Later, you have to use it to survive and fight. But first, you get to play with it.

So structure your game to create the teaching, and don't structure your teaching to create the game. If that makes sense.

Also consider the use of NPCs to convey messages. If you need the player to go pick up an item, have an NPC tell them, "You need to go pick up that item". If they don't do it, no big deal. But after a while, that NPC should say, "Hey you need to pick up that item - did you not hear me the first time?" Think, "They're waiting for you Gordon... In the Test... Chamber..." if you know your HL ;)

Players like to play - and explore. Let them do that. Don't force them down a rigid path with no chance to experiment. Let them learn what works by doing, not by you just telling them.

And if what you are asking them to do is so complicated you need to give them a manual, seriously reconsider the approach you're taking with the game.

# Answer
> 19 votes
If the tutorial text is vital, why would you allow the player to dismiss them forever and get themselves lost? Here's a few ideas:

A common approach I've seen is to **dismiss the tutorial text only when the player has completed the required action**.

For example, if the current text is:

> Welcome to bobobobo's game! Press **A** to jump.

Only dismiss that text if the player has pressed **A** and jumped.

Another approach is to **let the player revisit the text at will**. For example, in Binding of Isaac the starting room tells you the controls. You can freely come back to this room in case you need a reminder:

There's another tip here and that's to **make the tutorial text as unobtrusive as possible**. A text bubble that floats over everything is distracting. If it's in the background, or is something that could be brought up at will (e.g. signs that can be read, or NPCs that can be talked to):

One more approach (and this is the hardest but probably has the best effect) is to **make the hints very very subtle**. In the developer commentary for Escape from Butcher Bay, the lead developer mentioned small level changes that prevented their testers from getting lost: making certain doorways larger, adding lights etc. These had a psychological effect on the players that made them feel as if that was the right way to proceed, without being told explicitly so.

In the same vein (but in a less subtle way), the opening stage of Half-Life contained color-coded corridors. The player could choose to follow them, or maybe be subconsciously reminded by them:

One more thing; I read this somewhere (but I don't remember now) that the first level in Super Mario Bros has an excellent example of preparing the player in advance for obstacles. Consider this section:

See how it's almost the same jumping puzzle repeated twice. First there's almost no consequence for failing to jump over the gap, but the player in failing (or not) will know what to expect and what to do (or not to do) when they get to the real deal: the second obstacle where failure results in death. Sometimes it's better to teach the player by letting them practice in low-stakes settings in this way.

# Answer
> 5 votes
It just occurred to me that type-out text is not just a gimmick used in Final Fantasy, Legend of Zelda, etc.

If the text rolls on over a couple of seconds, THEN the user is given the option to press OK, user is more likely to read it!

# Answer
> 4 votes
This is a very good question for the UX (User Experience) StackExchange site, by the way!

Provide a way for the user to hide the dialogs, but with a way to resurrect them when the user discovers he or she is stuck.

```
 Do not bother me with this stuff, I know what I'm doing [ ] <- checkbox (or whatever)

```

When the user selects this checkbox and dismisses the dialog, you can somehow notify the user.

For instance, let's say your game has some status bar at the bottom. A "balloon" could pop up there saying, "Okay, I'll be out of your way, but click here if you're stuck!" and then fade away by itself.

Or the dismissed dialog could shrink-animate toward that location, and then a balloon briefly appears, "Okay, but I haven't gone away; I'm down here if you need me".

Anything of that sort.

# Answer
> 2 votes
I would say, give the user an option to access a tutorials screen which contains the entries presented so far, or if the user is in the same area for long, display the tutorial again...

# Answer
> 2 votes
Assuming all the other answers don't apply, (and you really, REALY need to have text instruction) present that text at precisely the moment when the user needs it. That makes it relevant, whereas presenting it ahead of time makes it annoying.

Wait for the player to be exactly in the right location; they are at the point where they need to take the action to proceed. Wait for them to literally bump into the locked door before telling them how to open it. If possible, detect that they're fumbling around stupidly, so as to give them a chance to divine the correct procedure with no message. If the player seems to be waiting for something, the instruction may be a welcome sight.

And ALWAYS make the text skipable. Allow the player to skip it almost by accident, such as with any click or the button closest to their thumb. If the tutorial milestone, trigger, event, etc. (the proof that the player has gotten the message) does not occur, then you can replay the message. Don't interrupt.

# Answer
> 1 votes
You might be able to make it an optional thing that they can activate if they need it, or ignore if they don't.

Perhaps better put would be, instead of a dialog with instructions, give an option to open up that dialog. I wouldn't suggest adding sound effects to it, those get annoying. And it might be a tricky thing to balance visually. But, personally, I REALLY don't like those "help" dialogs, especially when replaying the game, they easily become annoying.

---
Tags: tutorials
---


# Question
Title: UnrealScript access variable in one class from another?
So there are some similar questions out there but the responses often say that you should use 'new' or 'spawn', but I'm working with the playercontroller don't want to make a new playercontroller. Maybe this isn't the right way to be doing this but I want to view the state of a variable in the playercontroller that will change fairly often from my HUD. Is there a way to do this?

playercontroller class

```
var bool bYeaNo;

exec function change() {
  bYeaNo= !bYeaNo;
}

defaultproperties
{
  bYeaNo = false
}

```

HUD class

```
event PostRender() {
  Super.PostRender();
}

function DrawHUD() {
  Super.DrawHUD();
  Canvas.SetDrawColor(0, 0, 0);
  Canvas.SetPos(25, 25);

  if (bYeaNo) { //this is wrong so what would make this work?
    Canvas.DrawText("Yea");
  } else {
    Canvas.DrawText("No");
  }
}

```

# Answer
> 0 votes
Wasn't quite what I was thinking but this works well and gets the job done. Basically what I do is register the playercontroller with gameinfo which makes it really easy to retrieve values in the hud class.

MyPlayerController class

```
simulated function PostBeginPlay() {
  MyGameInfo(WorldInfo.Game).RegisterController(self);
}

var bool bYeaNo;

exec function change() {
  bYeaNo= !bYeaNo;
}

defaultproperties
{
  bYeaNo = false
}

```

MyGameInfo class

```
function RegisterController(MyPlayerController PC) {
    MyController = PC;
}

defaultproperties
{
  HUDType=class'MyGame.MyHUD'
  PlayerControllerClass=class'MyGame.MyPlayerController'
}

```

MyHUD class

```
event PostRender() {
  Super.PostRender();
}

function DrawHUD() {
  Super.DrawHUD();
  Canvas.SetDrawColor(0, 0, 0);
  Canvas.SetPos(25, 25);

  if (MacroGameInfo(WorldInfo.Game).MyController.bYeaNo) {
    Canvas.DrawText("Yea");
  } else {
    Canvas.DrawText("No");
  }
}

```

Found from willyg302.wordpress.com

---
Tags: udk
---


# Question
Title: How do you get player to interact with level?
I suffer from this problem where I have say a class called Player and a class called Level. Now the only way I can figure out how to say make the player interact with the level is if I do something like

```
player.input();

level.update(player);

```

I would have to do something like that, but then it gets even more complicated if I have monsters and I need to add them to the level e.t.c., so how do I get the monsters to interact with the player.

So I'm struggling with this basic concept. If I use C it gets rid of this problem as I use extern and I can get the data I want so all I think about is the flow. So in C I can do something like this

```
switch (terrain[u.y + dy][u.x + dx])
{
case WALL:
print_msg("You cannot go there.\n");
return 0;
case FLOOR:
case DOOR:
case STAIRS:
reloc_player(u.y + dy, u.x + dx);
return 1;
}

```

So in here we have Player u and your moving that player around only if it doesn't hit a wall. But, I can do this because I use extern on terrain\[\]\[\].

I'm really struggling. I don't really want to use C as C++ is easier with SFML and I like classes. I suppose the answer is how do I manage interaction between level, mobs and players?

If I was going to do it now I would do this

```
Game::Game()
{
   level.init();
   player.init();
}

void Game::input()
{
  player.input(level.getLevel()); // so yucky
}

void Game::update()
{
  player.update();
  level.update(player); /// yuck
}

void Game::render()
{
 player.render();
 level.render();
}

```

I could do something like this, but it gets really complicated and everything becomes a mess of passing stuff around. In particularly I need to pass the player method to the level.update() so the level knows the player has moved. Everything gets messy and I feel I can't add into the game. Plus I would need to make the level static or something.

# Answer
> 5 votes
In object-oriented programming, you expose private data with getter-methods.

When your player-class wants to know the terrain-type of a tile, it would call `level.getTerrain(int x, int y)`. That public function of `class Level` would access the private `terrain` array and returns the value of the terrain tile.

When you don't want the player-class to depend on the level-class (which is not a bad idea at all), you would not make the player-class responsible for performing its own actions. Instead of that you would have a `PlayerController` class which knows both the player and the level. It would first ask the player-class what it wants to do. Then it would check the level to see if it can do that. And then it would decide what the player-class really does and make it perform that action. Some incomplete pseudocode:

```
 public void PlayerController::update() {
     // ask the player what it wants to do
     Action action = player.getCurrentAction();
     if (action == Action.MOVE_RIGHT) {
         // decide what the outcome is
         switch (level.getTerrain((player.getX() + 1, player.getY())) {
             case Terrain.FLOOR:
             case Terrain.DOOR_OPEN:
                 player.moveTo(player.getX() + 1, player.getY());
                 break;
             case Terrain.WALL:
             case Terrain.TREE:
                 player.speak("ouch!");
                 player.changeHitPoints(-1);
                 break;
             case Terrain.DOOR_CLOSED:
                 level.setTerrain((player.getX() + 1, player.getY(), Terrain.DOOR_OPEN);
                 break;
         }
     }
 }

```

---
Tags: architecture, oop, game-state
---


# Question
Title: Anyone know the frames per second that IOS apps run?
Anyone know the frame rate that iphones, ipads, and even android mobiles run?

# Answer
As far as I know all those devices are able to show up to 60 fps, however, for mobile development you should think differently:

* You've tagged your question with 'directx', but this won't work. iOS as well as Android both support OpenGL ES only, which is a more lightweight version of the desktop OpenGL.
* The more frames you display, the more work the GPU has to do, the more battery your game drains.
* If you're playing on a tablet or phone, you typically don't have a charging adapter attached and you don't want your battery running low early just by playing a game (even if it's lots of fun).
* Don't tie your game logic or gameplay to any kind of fixed fps. If you have to, create fixed timesteps with n updates per minute, but don't directly link it to your display fps.
* With that in mind, I wouldn't try to go above 30 fps with any game. The less animations happening, the more you can save on this. For example, a card game or round-based strategy game could slow down to almost no updates (like 1 or 2 fps) unless there are animations happening.
* If you really think that having high fps is an important feature of your game (e.g. for faster effects and the like), allow the user to pick whether they'd like to experience the game with 60 fps or save battery life while still being able to play the game.
> 3 votes

---
Tags: game-design, directx, ios, iphone, first-person-shooter
---


# Question
Title: Why does my game exit immediately if I restart it after calling Exit()?
When launching a game multiple times in a console, the first time `this.Exit()` on the game class is called, all following games do not properly run. Instead they exit immediately.

For example, if I have a function that does:

```
foreach(var i in options) {
  using(var game = new MyGame()) {
    game.Run();
  }
}

```

and the game class has

```
protected override void Update(GameTime gameTime)
{
  if(gameTime.TotalGameTime.TotalSeconds > 3)
    this.Exit();
  base.Update(gameTime);
}

```

then the first instance will execute just fine (for 3 seconds), but the second will exit immediately.

How can I prevent XNA from making the second games die immediately?

# Answer
There should only be one instance of Game created in an XNA process I believe, so that code won't work. Although you're using a 'using' directive (which will call Game.Dispose when the scope runs out), that will only clean up **unmanaged** resources; the game object itself, and any managed resources it holds on to won't have been disposed of by the garbage collector by the time the subsequent MyGame is constructed. I suspect it is internally checking that it is the only instance of a Game-derived class and refusing to do any work.

See this question for some more illumination on the problem.

Game is intended to be a high level object, constructed once, that activates a bunch of services for your game. There may be a way to make it clean up after itself, but I suspect you'll find your life much easier if you move your `foreach (var i in options)` inside the MyGame class, and spawn a secondary game-like class to do the actual per-option work.

Alternatively you could have the options loop spawn a new process for each game, but then you'd have to co-ordinate cross process to pass the option information in, and to establish when the sub-process has finished running.
> 2 votes

---
Tags: xna
---


title: Python game loop approach?

text:
# Question
Title: Python game loop approach?
I intend to write a game in Python and, later, if needed, offload any performance-critical sections of code to C++. I want to use Python basically because I am really familiar with the language and I find writing game logic in it to be easier. However, unlike game logic which runs at a constant rate(50-60 ticks/s), you usually want to do rendering as fast as the hardware allows. Given this, the renderer will probably be the first thing to optimize out.

**Arpoaches**

1. The game is overall written in Python, the game loop as well, the renderer is written in C/C++ and called from Python
2. The game is written in Python, the loop is written in C/C++ and call the game logic which is Python, and renderer which is C++(I intend to do this with Cython)
3. The game, loop and renderer are written in C++, only the logic is written in Python

I personally dislike the third option because I've tried it before and designing the abstraction layer between C++ and Python is a bit of a hassle compared to the other way round.

**Question**

Considering each approach what would be the incurred overhead of 1 and 2 compared to 3, and 1 compared to 2?

# Answer
> 2 votes
Option 1: If you are familiar with python this would be the best approach since in average the rendering takes 70-80 % and to make that part in python would slow the game to much. However you would want to avoid doing any low level 3d from python (like computing stuff on vertices) so the c++ part has support lots of features out of the box , without the need to go under the hood. I would recommend choosing Cinder for the c++ part. It has lots of nice features and support for new c++ standard.

Option 2: This would give no real world advantage over option 1 , it's just not worth the effort to split the code in all the random places.

Option 3: This would be the professional approach where performance is critical. If you don't have strong c++ skills you will probably loose this battle. One advantage of this is that you can keep a hard limit on the stuff that the python code can do so you keep the project safe within it's requirements.

As a side note, you mentioned that you `want to do rendering as fast as the hardware allows`, and i think that even if you go for option 1 you can still achieve that. If the game logic is done properly then there is no need to move any of that to c++ it can be written entirely in python.

---
Tags: python, game-loop
---


# Question
Title: How can I unpack a sprite sheet into multiple images?
I need to take a sprite sheet and convert it into multiple images, one for each frame of the sprite sheet.

How should I go about this? I would prefer an offline method or a tool to do so -- I found Alferd SpriteSheet Unpacker, but it is really slow on Windows 7 and does not seem to respond well at all.

# Answer
> 2 votes
Shoebox is a great tool for this purpose and rather flexible.

http://renderhjs.net/shoebox/extractSprites.htm

It's AIR based, so you can use it on OSX or Windows.

It's drag/drop automagic at it's best.

# Answer
> 4 votes
I just can't replicate the issue with `FolderBrowserDialog.ShowDialog` hanging, so I've created a new version of the app (version 9) which has a new 'Prompt for Export Folder' option. Unchecking this option removes the need for the dialog box.

You can download version 9 from my site Alferd Spritesheet Unpacker version 9.

On the 'Options' form untick the 'Prompt for Export Folder' check box and now ASU will just export the files to whatever directory path is in the long textbox at the bottom of the main form.

(If you don't want to change this option every-time you can set `PromptForDestinationFolder` to `false` in the `.exe.config` file)

---
Tags: tools, spritesheet
---


title: Maya: Mystery Grey Wireframe?

text:
# Question
Title: Maya: Mystery Grey Wireframe?
I am starting out with Maya and just moved my object up to reveal a mystery grey wireframe which I can't work out what it is at all. It appears I can't select or interact with it at all.

I have been playing predominantly with UV Maps, potential cause?

What is it? And how can I hide/remove it?

Thanks.

Image: https://i.stack.imgur.com/vgm3Z.png

# Answer
> 0 votes
It is most probably a driver issue... I often have the same artifacts. If you switch to 4 viewports mode then back to 1 viewport mode, it should disappear. Sometimes rotating the camera is also enough if the viewport is a persp. camera.

You could also have created a layer containing a duplicate of your initial mesh.

**Original mesh:**

**Mesh put in a layer and set as a template (not selectable):**

Check your layers here:

---
Tags: graphics, maya
---


# Question
Title: Problem with revolving EP Curve in Maya 2012?
I am trying to create a animated butterfly i made this using the EP curve

but when i try to revolve this it turns out to be this

can anyone tell me what is the \[roblem

Thanks

Akash

# Answer
You do not HAVE to use the right side of the left side.

You actually choose around which axis you want your EP curve to revolve:

If you have a curve like this one:

You can revolve around X-axis:

You can revolve around Y-axis:

You can revolve around Z-axis

Or you can revolve around a freely defined axis (1,1,-1 here):
> 1 votes

---
Tags: maya, curves
---


# Question
Title: Break a learning barrier with Java + LWJGL
I have been coding with Java and LWJGL for some time. I mainly use thebennybox's tutorials, but I can't always remember the 3D rendering. But even when I have a 3D rendering models, planes, cubes, etc. I can't get past that. I *need* a good LWJGL tutorial! I look up to Notch and I know a good bit about Minecraft's history, and wish I could code as fluently as him. I also understand a good bit of Java.

# Answer
> 5 votes
LWJGL was my starting point for OpenGL (I since moved on to writing native C++ code), so I get where you're coming from. But what you should be looking for is good *OpenGL* tutorials, not LWJGL tutorials in specific. The LWJGL wiki should have everything you need as far as the library is concerned.

The tutorials I'm going to recommend? Learning Modern 3D Graphics Programming.

The examples use C++, but if you're familiar with Java, then the syntax is very similar. Then with the help of LWJGL's documentation, get at them!

I promise, they are the best tutorials on the web right now as far as OpenGL is concerned. They only go so far though, the more advanced stuff hasn't been written yet, but that's okay. Once you finish these tutorials, you should really *understand* OpenGL at a much more fundamental level, and be able to play around with it. Of course it's always nice to read up on some specific techniques used for 3D graphics, for which I recommend the OpenGL 4.0 Shading Cookbook. But, again, that's for when you understand the core elements, and are ready to implement over-the-top bloom, lens flare, and the like.

Any tutorials that teach you immediate mode rendering, forget them. It's outdated, and will just hurt you in the long-run. And with that said, I'd also like to note that since GLSL (the shading language) is C-like, it'd likely help to know C/C++. But, again, Java is close enough, so you should get by with just that.

As for getting Notch-like programming powers, you just need more experience. If you look at everything he's done before Minecraft, there's a lot of it. As they say, Rome wasn't built in a day...

---
Tags: java, lwjgl
---


# Question
Title: Application of classes with critical non-static fields in LWJGL
I'm going to be as specific about this question as I can. Ultimately, how is it that I apply a class that uses non-static fields in LWJGL?

More specifically, I know that OpenGL is quite nearly more a direct interface with the hardware than a traditional API. Multithreading it doesn't make any sense. I understand that it's in my best interest (perhaps as my only option) to keep all rendering commands in the same thread.

I also understand that given LWJGL's nature as a nearly one-on-one proxy to OpenGL, it cannot follow non-static class fields. Thus, every global variable in the main thread needs to be static, or it consistently just shows up as null.

I can deal with this, but I'm now creating a class that allows for generation of a texture around traditional BufferedImage graphics operations. It contains a BufferedImage in a field (image), provides access to that image, and produces a texture from image every time it changes. I thought this might be handy if I want to do anything flashy with text rendering through OpenGL (in spite of the buffering issues). The problem is, when called from the thread that renders OpenGL, the image field is consistently null.

I'm feeling a little boxed in by that, particularly as an old-school multithreading and OO programmer. LWJGL seems to be woefully short on documentation and even example code; so without digging through its source, could someone explain to me how it is that I maintain and access image in this class?

Here is my code. Hopefully it's something stupid, I've been cramming LWJGL for over a week. It's a three-layer code sample, including none of the imports, the interface, the abstract, and the (more-or-less) concrete. Pardon the lack of clean-up, I'm sort of in the middle of that with this.

```
package framework.texture;

import java.awt.Image;
import java.awt.image.BufferedImage;

public interface ImageTexture {
public void setImage(Image image);
public Image getImage();

/**
 * Activates the image as a texture.
 *
 * @return the integer by which OpenGL identifies the data.
 */
public int activate();

}

public abstract class AbstractImageTexture implements ImageTexture {

protected BufferedImage image;

@Override
public void setImage(Image image) {
    System.out.println(image);
    this.image = (BufferedImage)image;
    deriveTexture();
}

@Override
public Image getImage() {
    return this.image;
}

protected abstract void deriveTexture();

public AbstractImageTexture(BufferedImage image) {
    this.image = image;
}

}

public class BufferedImageTexture extends AbstractImageTexture {

public BufferedImageTexture(BufferedImage image) {
    super(image);
}

private enum ImageType {
    RGB(3),
    RGBA(4);

    int bpp;

    private ImageType(int bpp) {
        this.bpp = bpp;
    }

    public int getBytesPerPixel() {
        return this.bpp;
    }
}

private ByteBuffer buffer = null;

@Override
protected void deriveTexture() {
    BufferedImage image = (BufferedImage)this.image;

    int[] pixels;
    try {
        pixels = new int[image.getWidth() * image.getHeight()];
    } catch(NegativeArraySizeException e) {
        throw new RuntimeException("Image cannot be converted into a texture due to unknown sizing.", e);
    }

    this.image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());

    this.buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * getImageType().getBytesPerPixel());

    for(int y = 0; y < image.getHeight(); y++)
        for(int x = 0; x < image.getWidth(); x++) {
            int pixel = pixels[y * image.getWidth() + x];
            this.buffer.put((byte) ((pixel >> 16) & 0xFF));     //R
            this.buffer.put((byte) ((pixel >> 8) & 0xFF));      //G
            this.buffer.put((byte) (pixel  & 0xFF));                //B
            if(getImageType() == ImageType.RGBA)
                this.buffer.put((byte) ((pixel >> 24) & 0xFF)); //A
        }

    this.buffer.flip(); //Yes, you did it. Chill.
}

private ImageType getImageType() {
    if(this.image.getColorModel().hasAlpha())
        return ImageType.RGBA;
    else
        return ImageType.RGB;
}

@Override
public int activate() {
    glEnable(GL_TEXTURE_2D);

    int textureID = glGenTextures();

    {
        glBindTexture(GL_TEXTURE_2D, textureID);    //Bind texture ID

        //Setup wrap mode
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);

        //Setup texture scaling filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        //send texel data to OpenGL
        //TODO: Check these parameters. Seems like there are a few unhealthy and undefensive assumptions in them.
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, super.image.getWidth(), super.image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
    }

    return textureID;
}

}

```

image, whether its set or not, consistently shows up to the main thread as null. If I were to make it static, that might change, but I want to have quite a few of these objects floating around so they can't share a field. Do I need to call it from a separate thread or something?

# Answer
It is completely possible to use all OO paradigms when using LWJGL.

All that matters is that the data that you're sending to OpenGL with the gl... methods is correct. How you structure your program or code is not important and an Object-oriented approach is probably the best way to create a complex LWJGL game.

I'm developing my small LWJGL game using `Spring` and plenty of `@Autowired` annotations so practically all my classes (camera, engine, renderers) are being instantiated by Spring, so it's definitely possible, so there's no need to use `static` all over the place (unless for the things that static IS used for - `constants`, `enums`, ...)

For example, I can have a `Square` class looking like this.

```
public class Square {
    private float size;
    private Vector3f position;
    private Color color;

    public Cube(float size, Vector3f position, Color color) {
        this.size = size;
        this.position = position;
        this.color = color;
    }

    public Vector3f getPosition() {
        return this.position;
    }

    public float getSize() {
        return this.size;
    }

    public Color getColor() {
        return this.color;
    }

    public void render() {
        float halfsize = size / 2;
        // bottom left
        glVertex3f(position.x - halfsize, position.y - halfsize, 0); // z-axis = 0
        // top left
        glVertex3f(position.x - halfsize, position.y + halfsize, 0);
        // top right
        glVertex3f(position.x + halfsize, position.y + halfsize, 0);
        // bottom right
        glVertex3f(position.x + halfsize, position.y - halfsize, 0);
    }
}

```

You would probably make some kind of `Interface` for this type of objects with a `render()` method which then should be implemented for each type of object you want to draw (squares, triangles, cubes, octagons, whatever) or offload it to a `Renderer` class of some kind. The only thing that is important is that the OpenGL calls happen in the correct order **each frame**. For each frame that your game is rendering, you need to repeat the same steps, for example:

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

// Do a single loop (logic/render)
loopCycle();

// Let the CPU synchronize with the GPU if GPU is tagging behind
Display.update();

```

So you're quite free to structure your program the way you want :-)
> 0 votes

# Answer
So, in conclusion to my original issues, it seems that a lot of this has to do with the application of a state machine in my more typical style of programming.

As to whether most GPUs are particularly multicore, I don't know. It's ultimately irrelevant given the necessity to buffer data to them to begin with. However, it seems that it is critical that all calls to GL\**, or even many of the calls to Display, come from the same thread. This makes sense, as calls from multiple threads or programs is often undefined and I want exclusive-mode graphics anyway.

At the same time, things like OpenAL and JInput have nothing to do with graphics, and more than likely are state machines in themselves. So, ideally, they would have a thread of their own. So, it behoves me to create a HardwareLibrary interface, which extends Runnable, which each of these libraries can be encapsulated in. They will run on independent threads, managed by an additional thread called ThreadManager. ThreadManager will keep a Stack of HardwareLibraries that are implemented, and shut each one down after a cueShutdown() call, before ending the program. This can be implemented via a low-risk static method.

By keeping everything non-OpenGL in ordinary classes that interact with, but do not depend on, the encapsulating GL class, I can program as I typically do. The run-down is as follows.

```
public interface HardwareLibrary extends Runnable {
public void setExclusive(boolean mode);

    /** Rasterize/display any buffered data. **/
public void render();

    /** End loop, close thread **/
public void cease();
}

```

And the only section that really needs to worry about static fields:

```
public abstract class GL extends AbstractHardwareLibrary {

private int FPS = 60;
private boolean exclusive = false;

private volatile boolean isRunning = false;

@Override
public void run() {
    isRunning = true;

    if (!Display.isCreated())
        try {
            createDisplay();
        } catch (LWJGLException ex) {
            ex.printStackTrace();
            System.exit(0);
        }

    while (isRunning) {
        render();

        //check status of Display. Add any other shutdown cues here.
        if(Display.isCloseRequested())
            DebugMain.cueShutdown();

        Display.sync(FPS);
        Display.update();
    }
}

public void createDisplay() throws LWJGLException {
    Display.create();
    this.setDisplayMode(Display.getDesktopDisplayMode().getWidth(), Display
            .getDesktopDisplayMode().getHeight(), true);
}

/**
 * Renders all graphics relevant to the thread.
 */
public abstract void render();

/**
 * Set the display mode to be used; defaults to non-exclusive mode.
 *
 * @param width
 *            The width of the display required
 * @param height

 *            The height of the display required
 */
public void setDisplayMode(int width, int height) {
    this.setDisplayMode(width, height, false);
}

/**
 * Set the display mode to be used
 *
 * @param width
 *            The width of the display required
 * @param height
 *            The height of the display required
 * @param fullscreen
 *            True if we want fullscreen mode
 */
public void setDisplayMode(int width, int height, boolean fullscreen) {

            // ...
            // Fairly well-understood material omitted, check Ninja Cave's tutorials
            // for details
            // ...
}

@Override
public void setExclusive(boolean mode) {
    this.exclusive = mode;

    this.setDisplayMode(Display.getDisplayMode().getWidth(), Display
            .getDisplayMode().getHeight(), true);
}

@Override
public void cease() {
    isRunning = false;
}

}

```

AL is more-or-less the same idea. Rename pending, as it may be confused for the actual LWJGL class called AL; I'm not working with audio yet, so I'm putting it off. Now, ThreadManager:

```
class ThreadManager implements Runnable {

Stack<HardwareLibrary> threadsManaged = new Stack<>();

private volatile boolean shutdownTime = false;

@Override
public void run() {
    try {
        while (!shutdownTime) {
            // Do nothing
            Thread.yield();  //Avoid busy-waiting.
        }
    } catch(IllegalStateException ex) {
        //Window too torn down to count as created; good enough for me.
    } finally {

        while (!threadsManaged.isEmpty()) {
            threadsManaged.pop().cease();
        }
    }
}

public void addLibrary(HardwareLibrary lib) {
    this.threadsManaged.add(lib);
}

    /** Cue the stopping and dismantling of all HardwareLibrary threads. */
public void shutdown() {
    this.shutdownTime = true;
}

}

```

While this is technically a debugging (and thus disposable) class, the main class would go something like so:

```
public class DebugMain {
GL gl = new GL() {

    @Override
    public void render() {
        // TODO Auto-generated method stub
        System.out.println("Rendering " + Math.random());
    }

};
Thread glThread = new Thread(gl);

AL al = new AL() {

    @Override
    public void render() {
        System.out.println("Playing " + Math.random());
    }
};
Thread alThread = new Thread(al);

static ThreadManager manager = new ThreadManager();
Thread managerThread = new Thread(manager);

public static void main(String args[]) throws LWJGLException {
    new DebugMain();
}

public DebugMain() throws LWJGLException {
    manager.addLibrary(al);
    manager.addLibrary(gl);

    managerThread.start();

    glThread.start();
    alThread.start();

}

    /* Static so it can be called by anyone, even without a reference; two programs
     * are not, by plan, going to be running at once so it shouldn't be a concern.
     * Asks ThreadManager to shut down all HardwareLibraries through their cease
     * methods. */
public static void cueShutdown() {
    manager.shutdown();
}
}

```

By doing this, I can keep my program pliable, take advantage of multicore systems while using libraries like OpenAL and OpenGL, and program with some realistic business-sense. It works fine; any remaining problems with my BufferedImage-to-Texture program are just sloppy coding by me and will be worked out in the debugging process.

Peace.
> 0 votes

---
Tags: opengl, textures, lwjgl, multithreading, assets
---


# Question
Title: How to store tiles with different sizes?
in a tilegame, how can we use several tiles for 1 object?

I thought I could add each tile in a json file, with the type and its coordinates, like :

`"line1: type1_xTile1_yTile1, etc."`

`"line2: type1_xTile1_yTile1, etc."`

but in case when an object is bigger than the others, i don't see how to store this information. Is there another common way to store the tiles with different sizes?

Here is an example : the pond is bigger than the other tiles :

Thanks!

# Answer
> 2 votes
you can say on pond tiles that they are part of a multi-tile object with a reference to where the actual data is stored

if there is no data then you can create a type for each sub tile of the large object and just store those, so you can find the orientation and bounds by just looking at the type

in game you can have it act as one object.

edit: let say your pond is a 2\*2 and needs no other data, then you create 4 tile types `pond0`, `pond1`, `pond2`, `pond3`, with pond0 the top left file. when you place a pond then you check if all tiles are free and then change all the tiles into the appropriate pond tile

when you interact with it then you forward the interaction to all tiles of the pond and have them act on it properly, (start glowing; have one trigger a sound, etc.)

# Answer
> 1 votes
That looks like different size tiles, and not multiple small tiles in a premade configuration.

If all the tiles are the same size, storing tile sheet information is simple. All you need to know is the number of pixels from the top and left edge of the sheet image.

```
left_x, top_y

```

If each tile is a different size, you also need to store the width/height of each tile

```
width, height

```

and the drawing offset for each tile. When drawing a larger tile to the screen, you need to know how many pixels +/- x and y over you need to draw this tile (compared to "regular" sized tiles). Example, if you want a very tall object you'll need to draw that tile further up on the screen (-y) than the other tiles.

```
offset_x, offset_y

```

So the full data you need for each tile in your tileset becomes:

```
tile_id, left_x, top_y, width, height, offset_x, offset_y

```

---
Tags: tilemap, data-structure
---


# Question
Title: Is it possible now to make something for android in Unity3d without buying any licenses?
I was just talking to a game dev who said its possible, that it involves downloading the android sdk and few other things. If this is possible can someone tell me how?

Also is it possible to build a .apk file and install on your device? Is it possible to release something developed this way on the play store?

# Answer
> 1 votes
Yes. Nowadays it is possible to develop for mobile platforms even with Unity Free. There is a good guide available: http://docs.unity3d.com/Documentation/Manual/android-GettingStarted.html

It is also possbile to build an .apk file and install it on your device. Once you have set up Unity & Android SDK just a simple build will generate the .apk file.

And final yes, you can develop for Play-store.

---
Tags: android, unity
---


title: Spot and area lights inconsistent

text:
# Question
Title: Spot and area lights inconsistent
Im having problems with area light and spotlight. When adjusting parameters the change is not consistent and sometimes the light grows tstronger and then dissapears and then reappears very strong, when increasong the strength.

Also i have a spotlight that only affects the 3d meshes that is the environemnt but not the ground, which is textured plane.

Wehn playing the game some area lights switch on or off depending on what angle and distance from it i am at the moment. Are the lights supposed to be able to be used dynamically ?

Im using the free version of Unity. Could this be affecting?

# Answer
I think it depends on how many per pixel lights are illuminating your objects. Unity, at least in forward rendering path, uses several additional shading passes while rendering your objects.

It renders before the lights marked as `RenderMode: important` (or `RenderMode:auto` and promoted as important by the engine itself). This kind of lights are rendered per pixel. The maximum number of those lights is set in Quality Settings-\> Pixel Light Count (the engine allows up to 4 per pixel light).

The other lights are rendered per vertex.

Spotlights need to be rendered per pixel to actually see the spot (well..it depends on the geometry of the lighted object, but for example a spotlight can't light correctly with a per vertex shading on a quad).

So if your lights are popping on/off this might due to:

* In certain angle/position of the camera relative to the object, the number of lights overcomes the per pixel light quality settings and unity decides that some of them will be renderered per vertex.
* Certain spot lights are not marked as important in the inspector, and unity decide autonomously which should be important which not, depedening on the situation.
> 1 votes

---
Tags: unity, lighting
---


# Question
Title: Is it possible to display no white images/sprites when using the latest Android OS?
Was it okay to use `Texture.setEnforcePotImages(false)` in order to disable conditional width and height pixel size that requires power of 2? I'm planning to sell the game app at Google Play. I want to know and make sure that most of the latest models and Android OS's that won't display faulty white images by estimation, depending how many smartphone owners have latest Android OS's. (Gingerbread, ICS, or Jellybean) I had updated my LibGDX library.

# Answer
> 1 votes
GL (and most other graphics acceleration libraries) specifies power of 2 size so that sampling operations just need shifts and additions

using any other size will replace that with a floating point multiplication which is much slower,

what you can do is resample the images when they load so they become a power of 2 size, this may introduce artifacts in the image so it is better to start from a power of 2 size

---
Tags: opengl, java, textures, libgdx, graphics-programming
---


title: What to pass to scripting

text:
# Question
Title: What to pass to scripting
I am using Java and libgdx to create a game and have decided to go a data driven approaching with Jython for this refactoring (just picked up Jython, have used Java for a while). The game is a turn/tile based game where each ability will store prototype values and references to other scripts to actually execute the mechanics. I am hardcoding basic mechanics such as changing health, moving units between tiles, placing (de)buffs on units/tiles, and turn order. Everything else will be handled in softcode like deciding where to actually deal damage for aoe, how much damage to deal, what the buff behavior is, etc. I understand ideally I would script the entire game, except for things like rendering and I/O. But this is a solo project, and I don't really care.

Previously in development I hardcoded all the abilities. When an ability was casted it would call a function with the targeted tile and the entire gameboard. The function would then find the proper locations/objects on the gameboard and manipulate their state directly. However, I recognize this is terrible design. I figure some sort of API system would be better. But I am unsure how to design it.

1. API gives references to the objects on gameboard and gamestate variables directly. Scripts can manipulate the objects. Seems straightforward, but unsafe with possible illegal operations like moving a piece to a location that does not exist. Scripts could also be written to error check, but that seems counter productive to the idea of scripting.
2. APIs only give values of objects and gamestates. This may cause the script to need many variables that are normally grouped into one object, or to reconstruct the object. Also API could pass a purely data object. API calls are then also used back to the hardcode to manipulate the object. Safer as hardcode could easier contain illegal operation checking and debugging. But I guess I should learn debugging in Jython also. Also seems like a high memory overhead and extra API calls.
3. A mix of 1 and 2. The APIs give scripts references to the objects directly, but the scripts can only get data out of the objects. Any manipulation must be done through an API call. So scripts could use getHealth(), but not setHealth(var). I have no idea of this is even possible. I like this solution the best, but it seems a little convoluted.

# Answer
> 2 votes
Part of this answer is going to depend on the specific scripting language and implementation. Passing objects vs values can have different performance characteristics for different languages and which you choose may well depend on your scripting language. I don't know Jython personally but if in doubt you can perform tests to see if there is any significant issue either way.

Assuming performance is similar between both, focus on what makes things easier to develop with. If you strongly prefer a procedural-style interface, use that. Java and Jython are ideally setup for an object-oriented interface, however, and you may find it more natural to use that.

Usually with most scripting systems you explicitly choose which methods are exported so you can ensure that "unsafe" methods are not available to scripts. If this isn't possible with Jython, one option may be to use wrapper/proxy objects that are exported to the script which offer only the methods you want the script to have (and may offer additional convenience methods the "real" object does not). There may be significant overhead to this approach; again, something you need to test with your specific implementation and needs. Using a procedural API as in your option 3 may be the easiest way to efficiently allow restricted access to objects.

I would note that in many cases you might want to just ignore the "unsafe" aspects. The scripting language may have full access to Java's state anyway. Modders can typically modify Java bytecode relatively easily, too. Focus on ease of use, not safety. If you're worried that some method exposed might be dangerous then at the very least name it appropriately. It's not uncommon to have something like `set` vs `set_unsafe` with the former doing checks and raising errors while the later does not.

Yet another (far more complicated) option is to use a more tailored scripting system. General-purpose scripting languages are powerful and easy to integrate but often are a poor match for what game logic really needs. An event-driven game language or a declarative language may make what you're trying to do much easier.

If you're aiming for a very data-driven system then one might note that simply moving code from one procedural/OOP language to another does not make it any more or less data-driven. Whether or not you even need a scripting language when you're already working in a high-level language like Java is not a foregone conclusion. Your statement that ideally you would script the entire game is not necessarily all that ideal; scripts (especially ones in dynamic languages) can be a huge source of hard-to-debug issues. There are some native-code games that have actually used Java as their scripting language.

My recommendation would be to just expose your objects to Jython as-is and not worry so much about distrusting your script code. Keep the script code limited to high-level game logic and event handling.

---
Tags: java, python, scripting
---


# Question
Title: Max Row and Col for Animating Sprite in Andengine
I want to animate a Sprite in Andengine , I have used the following

```
this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this,"arrow.png", 10, 10);

```

As show above in code its array is 10x10 that means I have 100 images to be animated, here is the image (I had individual image and joined it online so I created image below):

My issue is if I place this code and image it show black patch instead of animated image, i hv tried with 2x3, 4x2 animated sprite that is \> working fine . Is my issue because of 10x10 ? what is the max row and col I can place to animate a Sprite in Above Code

Here is my output :

# Answer
Hi MT8 and thanks for your question.

I am not familiar with the AndEngine but I recognized some issues that are typically for this problem.

Normally you get no limit cap by the number of division. These are just passed parameters to the graphics pipeline where to get the specific tile from in the image(texture).

One thing that can cause the problem is the size of your image. Graphic cards have a hardware specific maximum and minimum value. In order to get more tiles with the same size in pixels you have to increase the size of your texture. The texture you posted is huge in size and most mobile graphic chip can not handle it.

So what to do? First check your limitations. Since you are using an Android Engine I assume you are using OpenGLES. You can get the max dimension by:

```
GLint maxDimension;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxDimension, 0);

```

If this is the problem you have multiple choices. First reduce the size of every tile.

Second use a tile format to squeeze out your white spaces. You can find a nice video here.

Split your tiles in multiple textures. Anyway you are limited to your number of texture channels.

Additionally your image has no squared size to a number of 2^n. This leaks memory and slows down your rendering pipeline. Even if you do not use the space you should resize your image.

I hope I could help you. Have further questions? please tell us. :)

Michael
> 1 votes

---
Tags: android, andengine
---


title: Moai: Clipping an image to a polygon

text:
# Question
Title: Moai: Clipping an image to a polygon
I'm using *Moai SDK*. I have an image and some random convex 2D polygons. I want to show only the parts of the image inside these polygons.

Here's an example image:

The same, shown only where the polygons are:

How can I achieve this?

# Answer
In the general case, this is achieved using a clipping mask and an multiply composite operation.

The specifics varies by framework, but with Moai the job is done by way of the MOAIMultiTexture.
> 1 votes

# Answer
Create an image with the same resolution, make it completely opaque. Create some random set of polygons within the boundaries of the this image, set the opaqueness to 0 (so it's completely see through).

Here is an idea for creating the polygon with:

```
int noPolygons = whatever;

for (i = 0; i < noPolygons ; i ++) {
    int polygonPoints = whatever2;
    Vector points[polygonPoints ];
    float radius = whatever3;
    int centerX = random(0+radius, imageWidth-radius);
    int centerY = random(0+radius, imageHeight-radius);

    for (j = 0; j < polygonPoints ; j++) {
        float x     = cosinus(j/polygonPoints)*random(0.5, 1) * radius;
        float y     = sinus(j/polygonPoints)*random(0.5, 1) * radius;

        points[j] = new Vector(centerX+x, centerY + y);
    }

    Edge edges[polygonPoints ];
    for (j = 0; j < polygonPoints ; j++) {
        int lastIndex = j + 1 >= polygonPoints ? 0 : j +1;
        edges[j] = new Edge(points[j], points[lastIndex ]);
    }
}

```

This would produce fairly convex polygons, I think.

I hope Moai SDK supports these things, never used it.
> 0 votes

---
Tags: 2d, clipping
---


title: Workaround for Texture2D.GetData

text:
# Question
Title: Workaround for Texture2D.GetData
I’m converting a game from XNA to iOS with Monogame.
In the code snippet below, `smallDeform` is a `Texture2D` on which I call the `GetData` method.

```
smallDeform = Game.Content.Load<Texture2D>("Terrain/...");
smallDeform.GetData(smallDeformData, 0, smallDeform.Width * smallDeform.Height);

```

I’m having some problem with Monogame because the feature in iOS has not been implemented yet because it returns this exception.

```
#if IOS
   throw new NotImplementedException();
#elif ANDROID

```

I tried to serialize the data in a XML file from Windows to load the whole file from iOS. The serialized files weight more than 100MB each, that is quite unacceptable to parse.

Basically, I’m looking for a workaround to get the data (for instance a `uint[]` or `Color[]`) from a texture without using the `GetData` method.

PS: I'm on Mac, so I can't use the Monogame SharpDX library.

Thanks in advance.

# Answer
I answer my own question, if someone will have the same problem.

Following *craftworkgame*'s suggestion, I saved my data using byte streams, but due to the absence of `File` class, I had to use WinRT functions:

```
private async void SaveColorArray(string filename, Color[] array)
{
    StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(filename + ".dat", CreationCollisionOption.ReplaceExisting);
    IRandomAccessStream writeStream = await sampleFile.OpenAsync(FileAccessMode.ReadWrite);
    IOutputStream outputSteam = writeStream.GetOutputStreamAt(0);
    DataWriter dataWriter = new DataWriter(outputSteam);
    for (int i = 0; i < array.Length; i++)
    {
        dataWriter.WriteByte(array[i].R);
        dataWriter.WriteByte(array[i].G);
        dataWriter.WriteByte(array[i].B);
        dataWriter.WriteByte(array[i].A);
    }

    await dataWriter.StoreAsync();
    await outputSteam.FlushAsync();
}

protected async Task<Color[]> LoadColorArray(string filename)
{
    StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(filename + ".dat", CreationCollisionOption.OpenIfExists);
    IRandomAccessStream readStream = await sampleFile.OpenAsync(FileAccessMode.Read);
    IInputStream inputSteam = readStream.GetInputStreamAt(0);
    DataReader dataReader = new DataReader(inputSteam);
    await dataReader.LoadAsync((uint)readStream.Size);

    Color[] levelArray = new Color[dataReader.UnconsumedBufferLength / 4];
    int i = 0;
    while (dataReader.UnconsumedBufferLength > 0)
    {
        byte[] colorArray = new byte[4];
        dataReader.ReadBytes(colorArray);
        levelArray[i++] = new Color(colorArray[0], colorArray[1], colorArray[2], colorArray[3]);
    }

    return levelArray;
}

```
> 0 votes

# Answer
Serializing the data is actually a pretty clever workaround but XML is far to heavy for the job. What I would do is use a custom made, but simple, binary format so that you can control the size of the output.

Here are a couple of methods I whipped up that should work, but please note that I made them specifically to answer this question and they have not been tested.

EDIT: pinckerman pointed out that using File.Open doesn't work on all platforms so I've changed my answer slightly to use TitleContainer.OpenStream instead. As you can see from the MonoGame source code the TitleContainer is intended to handle reading files in a platform agnostic way with MonoGame. Again, this should work but I haven't tested it. If the answer needs to be corrected after implementation please do so.

NOTE: On most mobile devices only a small about of data can be written to isolated storage. This is obviously not sufficient or required for this task so I've left the File.Open in the SaveTextureData method. This should work on Windows 7 but if you are using WinRT you should do it pinckerman's way.

To save the data..

```
private void SaveTextureData(Texture2D texture, string filename)
{
    int width = texture.Width;
    int height = texture.Height;
    Color[] data = new Color[width * height];
    texture.GetData<Color>(data, 0, data.Length);

    using (var stream = File.Open(filename, FileMode.Create))
    using (var writer = new BinaryWriter(stream))
    {
        writer.Write(width);
        writer.Write(height);
        writer.Write(data.Length);

        for (int i = 0; i < data.Length; i++)
        {
            writer.Write(data[i].R);
            writer.Write(data[i].G);
            writer.Write(data[i].B);
            writer.Write(data[i].A);
        }
    }
}

```

And to load the data..

```
private Texture2D LoadTextureData(string filename)
{
    using (var stream = new TitleContainer.OpenStream(filename))
    using (var reader = new BinaryReader(stream))
    {
        var width = reader.ReadInt32();
        var height = reader.ReadInt32();
        var length = reader.ReadInt32();
        var data = new Color[length];

        for (int i = 0; i < data.Length; i++)
        {
            var r = reader.ReadByte();
            var g = reader.ReadByte();
            var b = reader.ReadByte();
            var a = reader.ReadByte();
            data[i] = new Color(r, g, b, a);
        }

        var texture = new Texture2D(GraphicsDevice, width, height);
        texture.SetData<Color>(data, 0, data.Length);
        return texture;
    }
}

```

Binary data is far smaller than XML data. It's about as small as you're going to get without compression. Just be aware that binary formats are pretty rigid when it comes to change. If you need to change the format it'll be easier in most cases to write out new files.

If you need to make changes to the methods, be careful to keep them in sync. Every Write should be matched with an identical Read in the exact same order and data type.

I'm interested to know how much smaller the files become. Let me know how it goes?
> 1 votes

---
Tags: xna, c#, textures, ios, monogame
---


# Question
Title: Vertex buffers - interleaved or separate?
Interleaved - all vertex data (position, normal, texcoord...) kept in 1 vertex buffer, separate - each vertex attribute is kept in a separate vertex buffer (1 for positions, 1 for normals...).

I know this question came up many times and I also know there's no 1 right answer (sadly). But I'd like to try to list the main advantages/disadvantages of both. Or maybe you have some general rules of thumb for when to use each.

1. Advantages of interleaved:

* faster? (all data for 1 vertex is fetched at once? sth about cache working better)?
    * less API calls (for creating and setting buffers but that's probably a very small difference)
2. Advantages of separate:

* when different shaders need different vertex attributes (e.g. one shader needs only position and another needs position, normal and texcoord) it's possible to provide each shader only the data it needs and there's no data duplication
    * when updating only e.g. position of vertices it's not necessary to resend the other attribute data (e.g. normals and texcoords)

If you see any other differences please write. From the above it generally looks like a struggle between memory and performance optimisation. But maybe I'm wrong? Maybe one is better/worse in most cases?

**Edit:** One more concern, actually - with interleaved buffers I could end up sending unnecessary data to GPU and the data bandwidth is a big bottleneck in today's cards. Should I worry about that?

# Answer
I've recently implemented both versions in OpenGL (4.3) and using the (Crytek) Sponza scene as a test render scene, I had shaders that used either only a subset or the complete set of all vertex attributes defined.

There was one difference to your setup: In the non-interleaved case, the attributes were inside the same vertex buffer, too. It easy to do this with OpenGL, you can just bind byte offsets to a certain attribute with glVertexAttribPointer(...) with the last parameter. An equivalent option probably exists for DirectX.

Specifically, while rendering a shadow map, which only needs vertex positions (in my case) went from ~210 to ~220 FPS when using non-interleaved buffers, which is a difference of about 0.2ms. In other words, you couldn't even go from 60 FPS to 61 FPS with that speedup.

When rendering the scene from the shadowing light's perspective, but using all attributes (in my case, a deferred shading geometry pass), the performance didn't change at all between the two versions.

I can only guess, but I think the reason the shadow map rendering improved is because GPUs probably (like CPUs) dont just pull single bytes, words or dwords out of memory with one memory access, but instead pull more bytes (on most modern CPUs this would be 64 bytes per access) and cache it somewhere. When data is interleaved, the GPU might pull one set of position/normal/texcoord/whatever per memory access at once, of which all but the position will be wasted memory bandwidth if you only use position.

One caveat: I was not memory bandwidth bound in my test case, so if memory throughput is your bottleneck, the measurements might come out differently.

Overall I'd suggest you leave it the way you have it now and change it later once you notice that some optimization is necessary. Changing it doesn't take long, you only need to change how the data is handed over to GPU memory and change how attributes are bound using your graphics API.
> 11 votes

# Answer
**interleaved**: if is easier to understand and to manage memory wise and code wise. Instead of having 4 buffer you have just one and that's it.

**separate**: there is no practical advantage in sharing resources, managing 3d stuff is difficult as it is and by having the separate streams shared would only create a nightmare. You might gain some memory by doing that but it's not worth it.

on performance there might be a difference , at least on some Android GPU i know that you will have different results.
> 0 votes

---
Tags: rendering, performance, memory, vertex-buffer, vertex-attribute
---


title: What is a Game Engine?

text:
# Question
Title: What is a Game Engine?
I am new to Game Development, All I have developed is some `2d` Games, using `Game Maker` by *YoYo Games*. There game development is much more easy, just as simple as Drag and Drop.

But, Now I wish to evolve in Game Development, and wanna try some hands with the common programming languages like, `Java`, `C++` or `C`. In order to achieve this, I came around the first topic, **`Game Engine`**.

## So, **What is Game Engine.?**

That is a broad question, with various answers. I came out with some conclusion after reading various links,

> **Wikipedia:**
>
> A game engine is a system designed for the creation and development of video games. The core functionality typically provided by a game engine includes a rendering engine for 2D or 3D graphics, a physics engine or collision detection (and collision response), sound, scripting, animation, artificial intelligence, networking, streaming, memory management, threading, localization support, and a scene graph.
>
> **GameCareerGuide.com**
>
> It exists to abstract the (sometime platform-dependent) details of doing common game-related tasks, like rendering, physics, and input, so that developers (artists, designers, scripters and, yes, even other programmers) can focus on the details that make their games unique.
>
> Engines offer reusable components that can be manipulated to bring a game to life. Loading, displaying, and animating models, collision detection between objects, physics, input, graphical user interfaces, and even portions of a game's artificial intelligence can all be components that make up the engine.

Now what I understand is, Game Engine takes care of all the common work, like *physics*, *loading* etc...

As far my question is concerned, **what is a Game Engine (Programmatically)?**

Is it a Library? With pre-defined functions and classes, which can be inherited? Or what so ever, what is it?

# Answer
A library simply refers to a collection of classes/functions. There is really not much to it. A Game engine can be released as a library, it's not going to change anything. Afterall software is build from a collection of classes and/or functions.

Where a game engine refers to the basic software of your game. When you speak of a game engine there is at least an architecture involved that handles the bare minimum of the game structure( Entities/Gameobject, rendering, etc ). A lot of the technical stuff is automated for you.

Game engines dictate how certain things are done ( adding scenes, entities/gameobject, loading assets, etc ). All you have to do is add gamelogic and give it an artistic flair ( assets-sound/models/shaders/whatever ).

Game engines exists so that they can boost production. Why or how they do certain things in certain ways is arbitrary ( programming styles as well as work environments can play a big role. To each their own).
> 2 votes

# Answer
Despite many accompanying stuff like editors/tools for the engine it can be 1 of 2 things, I guess:

1. What you said - a kind of library which gives you functions and (code) tools to setup the rendering/window, load assets, manage, update and render them. But it also helps you with audio, physics, AI and so on... The main goal of such a game engine is not to let you do all that - you can do that by youself with raw API - but to let you do it fast and easily.
2. A kind of environment that is closed and let's you only fiddle with some of it's functionality - setup the rendering machine and load/manage the assets. But the core functionality would be the same, I guess.

The difference betweend the two is that in the former case you have either the engine's source code or compiled binaries and use it like a library and in the latter it's a closed unit that you have no access to (like Unity3D) and it only let you do stuff in its editor and with scripts.

But I might be horribly wrong as I've only really worked with 1 commercial engine (Unity3D) and other than that I've tried creating my own ones, to no great effect. Still, I hope it helps.
> 2 votes

---
Tags: terminology
---


title: CPU - GPU memory data flow

text:
# Question
Title: CPU - GPU memory data flow
I'm a newbie graphics programmer and I've been wondering recently - how does model data (meshes and materials) flow from application (CPU memory) to graphics card (GPU memory?)? Say I have a static model (e.g. a building) that I load and setup once and don't change throughout the app lifespan.

* Does its data get sent to GPU memory only once and sit there forever?
* When the model gets actually rendered each frame do GPU processors have to fetch its data each time from GPU memory? What I mean is - if I had 2 models rendered multiple times each - would it matter if I first rendered the first one multiple times and then the second one multiple times or if I rendered the first one just once, the second one just once and kept interleaving it like that? I could call this question "internal GPU data flow" in this sense.
* Obviously graphics cards have limited RAM - when it can't hold all the model data necessary for rendering 1 frame I guess it keeps fetching (some of) it from CPU RAM each frame, is that correct?

I know there's a lot of books and stuff about this on the internet but maybe you have some quick general guidelines as to how to manage this data flow (when to send what and how much, when and how to render)?

**Edit:** I forgot to make one distinction: there's **sending the data to the GPU** and there's **setting/binding the buffers as current**. Does the latter cause any data flow?

**Edit2:** After reading Raxvan's post I'd like to distinct a few actions:

* buffer creation with initialisation (as he said I can store the data in either CPU ram or GPU one)
* buffer data update (which I believe is straightforward when the data is kept in CPU ram and requires fetching from GPU to CPU ram (and then back) when it's kept in GPU ram)
* binding the buffer as active (is it just a way to tell the API that I want **this** buffer to be rendered in the next draw call and **it doesn't do anything by itself**?)
* API draw call (here I'd like to hear from you what actually happens there)

# Answer
> 12 votes
> Does its data get sent to GPU memory only once and sit there forever?

Usually yes, but the driver is free to do what is "optimal", the data might be stored at VRAM or RAM or could just be cached here is an atricle that explains what actually happens with the VBO flow.

For example if it was flagged as a dynamic openGL buffer (e.g. VBO), it's more likely to be stored in RAM. GPU use direct memory access (DMA) to access the ram directly without the CPU intervention, this is controlled by the DMA controller in the graphics card and graphics driver and is executed in kernel mode.

> When the model gets actually rendered each frame do GPU processors have to fetch its data each time from GPU memory, even if a model is rendering multiple sequential times ?

Just like CPUs, GPUs are permitted to **re-order GPU instructions and memory access operations**, (read: out of order execution) so most likely the GPU will handle the scenario you mentioned by accessing the memory that is in it's cache (usually accessed recently), but sometimes it can't do this.

> Obviously graphics cards have limited RAM - when it can't hold all the model data necessary for rendering 1 frame I guess it keeps fetching (some of) it from CPU RAM each frame, is that correct?

You don't want this to happen. But regardless if that happens the GPU will start moving memory between RAM and VRAM (the command processor on the GPU is responsible for this) which will make rendering much slower which will case the GPU to stall, because it will need to wait for the data to be copied from/to V/RAM.

> There's sending the data to the GPU and there's setting/binding the buffers as current. Does the latter cause any data flow?

**GPUs contain a command buffer**, and all API commands are submited to this buffer, notice that this can happen simultaneously with the data being copied to the GPU. The **command ring buffer is a communication queue between the CPU and GPU**, any command that needs to be executed needs to be submitted to the queue so it can be execulated by the GPU. Just like any operation binding new buffers needs to be submitted to the gpu so it can access some memory location.

That's one of the reasons glBegin/glEnd was deprecated, submitting new commands needs queue synchronization (using memory fences/barriers).

As for your other points:

> Buffer creation with initialization

You can allocate a buffer without initialization and keep it for later use. Or you can allocate it a buffer and copy data at the same time (talking about the API level).

> buffer data update

You can use glMapBuffer to update memory on the GPU side. whether the memory will be copied from/to RAM is not actually poart of the standard and will vary greatly depending on the Vendor, GPU type and driver.

> API draw call (here I'd like to hear from you what actually happens there).

My second point in the main question covers this.

> binding the buffer as active (is it just a way to tell the API that I want this buffer to \>be rendered in the next draw call and it doesn't do anything by itself?)

Think of binding as using `this` pointer in any object oriented language, although not strictly the same, any consequent API calls will be relative to that bind buffer.

# Answer
> 4 votes
In general the boundary and the involvement of the cpu versus gpu are specific on the platform, but most of them follow this model: cpu has some ram, gpu also and you can move memory around (in some cases the ram is shared but for the sake of simplicity let's stick to separate rams).

**first point**: The data that you initialize you can choose to keep it in the CPU ram or on the GPU ram, and the are advantages for both. When you render something the GPU has to do the heavy lifting so it is obvious that the data that is already on the GPU mem will provide better performance. for the CPU it must first send the data to the GPU (which can choose to keep it for a while) and then perform the rendering.

**second point**: There are many trick in rendering but the main way thing are done is with polygons. On a frame gpu will render the objects made out of polygons one by one and after finishing that the GPU will send the picture to the display. There is no concept such as objects , there are just polygons and the way you put them together will create an image. the job of the GPU is to project those polygons from 3d to 2d and apply effect(if wanted). The polygons go only wan way CPU-\>GPU-\>SCREEN or GPU-\>SCREEN directly (if the polygons are already in the GPU ram)

**third point**: When you render animations for example it is better to keep the data close to the cpu because there he does the heavy lifting , it would not be optimal to keep the data in GPU , move it to CPU and back every frame. There are lots of other examples like this to count but in general all the data will stay close to whoever is doing the computations. Usually you would want to move as much data as possible to the GPU ram to gain performance.

The actual **sending** the data to the gpu is done by the API you use (directx/opengl or other) and the concept of binding and stuff like this are just abstractions so that the API understands what you want to do.

Edit for the edit:

* `buffer creation with initialisation`: it's like the difference between int `a = new int[10]` and `a[0] = 0,a[1] = 1.... etc` when you create a buffer you make room for the data and when you init the data you put the stuff you want in there.
* `buffer data update` if it's on the cpu ram then you have `vertex * vertices` that you can play with it, if it's not there , you would have to move it from GPU `vertex * vertices = map(buffer_id);`(map is a mythological function that should move data from GPU to CPU ram, it also has it's oposite `buffer_id = create_buffer(vertices)`;
* `binding the buffer as active` it's just a concept that they call `binding` rendering is a complex process and it's like calling a function with 10000 parameters. Binding is just a term they used for telling which buffer goes where. There is no real magic behind this term, it does not convert or move or reallocate buffers, just tells the driver that on the next draw call use this buffer.
* `API draw call` After all the binding and setting buffers up this is the place where rubber meets the road. The draw call will take all the data (or the id's that point to the data) you specified, sent it to the GPU (if needed) and tell the GPU to start crunching the numbers. This is not entirely true on all the platforms there are many differences, but for keeping thing simple the draw will tell the GPU to .... draw.

# Answer
> 2 votes
The most correct answer is, it depends on how you program it, but this is a good thing to worry about. While GPU's have become incredibly fast, bandwidth to and from GPU RAM is not, and will be your most frustrating bottleneck.

> Does its data get sent to GPU memory only once and sit there forever?

Hopefully, yes. For rendering speed, you want as much data to sit on the GPU as you can, instead of re-sending it every frame. VBO's serve this exact purpose. There are both static and dynamic VBO's, the former being best for static models, and the latter being best for models whose vertices will change every frame (say, a particle system). Even when it comes to dynamic VBO's, though, you don't want to resend all the vertices every frame; just the ones that are changing.

In the case of your building, the vertex data would just sit there, and the only thing that changes are your matrices (model/world, projection, and view).

In the case of a particle system, I made a dynamic VBO big enough to store the maximum number of particles that will ever exist for that system. Each frame I send the data for the particles emitted that frame, along with a couple uniforms, and that's all. When I draw, I can specify a start and end point in that VBO, so I don't have to delete particle data. I can just say don't draw those.

> When the model gets actually rendered each frame do GPU processors have to fetch its data each time from GPU memory? What I mean is - if I had 2 models rendered multiple times each - would it matter if I first rendered the first one multiple times and then the second one multiple times or if I rendered the first one just once, the second one just once and kept interleaving it like that?

The act of sending multiple draw calls instead of just one is a much bigger limit. Check out instanced rendering; it might help you out a lot and make the answer to this question useless. I had some driver issues with it that I haven't worked out yet, but if you can get it working, then problem solved.

> Obviously graphics cards have limited RAM - when it can't hold all the model data necessary for rendering 1 frame I guess it keeps fetching (some of) it from CPU RAM each frame, is that correct?

You don't want to run out of GPU RAM. If you do, then change things so you don't. In the very hypothetical scenario that you do run out, it'll probably crash somehow, but I've never seen it happen so I honestly don't know.

> I forgot to make one distinction: there's sending the data to the GPU and there's setting/binding the buffers as current. Does the latter cause any data flow?

Not any significant data flow, no. There is some cost to it, but that's true for every line of code you write. Finding out just how much it's costing you is, again, what profiling is for.

> buffer creation with initialisation

Raxvan's answer sounds good, but it's not quite accurate. In OpenGL, creating the buffer *does not* reserve any space. If you want to reserve space without passing any data, you can call glBufferData and just pass null. (See the notes section here.)

> buffer data update

I'm guessing you mean glBufferData, or other functions like that, right? This is where the real data transfer occurs. (Unless you pass null, like I just said in the last paragraph.)

> binding the buffer as active (is it just a way to tell the API that I want this buffer to be rendered in the next draw call and it doesn't do anything by itself?)

Yes, but it can do a little more than that. For example, if you bind a VAO (vertex array object), then bind a VBO, that VBO becomes bound to the VAO. Later, if you bind that VAO again, and call glDrawArrays, it will know what VBO to draw.

Note that while many tutorials will have you create a VAO for every VBO, I've been told this is not their intended use. Supposedly you should create one VAO and use that with every VBO that has the same attributes. I haven't tried this yet, so I can't say for sure whether it's any better or worse.

> API draw call

What happens here is pretty straightforward (from our perspective). Say you bind a VAO, then call glDrawArrays. You specify a starting point, and a count, and it runs your vertex shader for every vertex in that range, which in turn passes its outputs down the line. That whole process is another essay of its own, though.

---
Tags: rendering, gpu, memory, dataflow
---


# Question
Title: Cross Game Engine Compatibility - Multiple Game Engines for one Game
I am new to Game Development, infact getting started with it, so reading as much as I can. I came across game engines. Now atleast I have an idea of what a game engine is, and what it does.

In order of reading about game engines, I came across various game engines - Paid, Freeware, OpenSource. Some are good for physics, some are good for loading images, some for sound. At last, it always comes to performance.

Now what comes to my mind, can I use various game engines to develop one game? I mean, one for loading graphics one for animation one for physics. Is this possible?

I know, game engine is like a CPU, and what I am talking about is using various CPUs to work on one PC.

But whatever it is, can this be done? **Cross Game Engine Compatibility?**

# Answer
You might be confusing the role of a full game engine with game middleware.

> Now what comes to my mind, can I use various Game Engines to develop one game? I mean, one for loading graphics one for animation one for physics. Is this possible?

I've seen weird mergers of code from different engines before but the result has always been an abomination. Each engine has lots of core utility code (STL container replacements, in-game profiling tools, common object system, etc.) that are very difficult to reconcile sensibly. The end result is that a merger of two engines tends to have lots of duplicate code and data and due to differences in naming/concepts can be very hard for a developer to work with. Especially when, say, one engine is using component-based design and its own STL replacements everywhere and the other is using a classical type inheritance model and makes extensive use of STL/Boost. Just trying to get subsystems from one to even remotely work with the other is a months-long nightmare of a process.

It's also not generally all *that* useful; the physics of both engines are probably just wrappers around some middleware and most of the value of a game engine comes from its highly-integrated toolset. It would be a pain if I had to use one tool for editing terrain heightmaps and then a completely different tool to place objects and spawn points on the terrain. Having one unified tool - which implies one unified engine - is a significantly better story for your content creators. Content creation tends to be the main bottleneck in most games and you should do anything and everything to make it faster and easier to make more and better content for your game. That means putting more effort into your tools and content creation stories up front than in most technology decisions that ultimately don't matter much (e.g., which physics engine you use is mostly irrelevant in the common cases; just pick one and go).

However, the systems you mention can be - and in many cases are - handled as individual middleware packages. You might be using PhysX for your physics, Ogre3D for graphics, and Granny for animation. While using these different middlewares from different organization does again result in some waste and conceptual clashes (PhysX has its own built-in profiling and debugging system different from Ogre's) the overlap tends to be smaller and much more easily wrapped by an engine's preferred interfaces and tools. Ogre3D can quite easily be dropped into an engine that has its own resource manager, object system, and core containers with a minimal of fuss, for example. Almost every major game I can think of has at least some middleware be it as "simple" as TinyXML, AntTweakBar, and Lua or as complex as Telemetry, Havok Physics, and SpeedTree.

Note that some companies like RAD Game Tools or Havok have a wide variety of middleware offerings that integrate very cleanly together. Big projects like Ogre3D have a myriad of satellite open-source library that add physics, audio, and so on in an "Ogre-like" API making the integrations easier and cleaner.

I will note that there is somewhat of a difference between a library and a middleware, though some things considered middleware in general can also be considered a simple library, and the distinctions are not at all official or universally agreed upon. It's difficult to justify calling TinyXML "middleware" but it's a bit of an understatement to call Umbra just a "library."

Short version: merging engines is very difficult to do and has few practical advantages, but using large middleware packages is both practical and standard practice.
> 5 votes

# Answer
No, at least in this case a game engine is nothing like a CPU. Each game engine usually has its own data formats and they're usually encapsulated and closed for either their users' or their creators' benefit.

That means it would be extremely difficult to try to combine more than 1 game engine to work together, if possible at all. No, you stick to one engine that best suits your needs and at best you get plugins for it or modify it (if you can access the source code).
> 3 votes

---
Tags: software-engineering
---


# Question
Title: Selecting a color that will be readable overlapped upon another?
I've got random circles from random colors of RBG (assume they can be any combination of values). I have some text I want to write on top of them but I want the color to be readable on it no matter the color of the bubble. How can I pick a complimentary color?

# Answer
You can pick the opposite color by calculate like this:

```
maximum - color = opposite color

e.g. white(255,255,255) - red(255,0,0) = cyan(0,255,255)

```

You can also solve the problem by using a text with a border e.g. inner color white, outher color black -\> if the background is black, you cannot see the outer border but the inner white. If the background is white, the border shows the text.

Edit: an example is the caption of the site: "Game Development" -\> the inner color is white, the outer color something like gray. The background doesn't matter you can see every character very well.
> 1 votes

# Answer
One simple solution is to pick either black or white depending on how bright the colour is. Something like this:

```
float GetIntensity(float r, float g, float b)
{
    return r * 0.299f + g * 0.587f + b * 0.114f;
}

if (GetIntensity(r, g, b) < 0.5f)
{
    RenderTextWhite();
}
else
{
    RenderTextBlack();
}

```

It has the benefit that you don't need to worry about weird looking text colours, or colour blindness in the viewer.
> 1 votes

---
Tags: color
---


# Question
Title: How to draw a rotated pixel perfect line by hand?
If you have a pixel perfect line like `1:16 pixels`, and you want to draw that same line rotated by a degree, for example `45°`, what would be the correct way to do that by hand?

I know it should have something like n:n pixels, but 16:16 pixels just looks like it is to long to be the same line.

So what would the correct size would be for that pixel? And is there some kind of formula to calculate it with any degree?

# Answer
If you want to draw a line "by hand" then you can use Bresenham's Algorithm. The algorythm take two 2d points and draws a line.

So given point `A` and a length `L` , here is how you compute point `B` to draw the line from `A` to `B` (depending on the axis: x from left to right, y from down to up)

```
point2d B;
B.x = cos(Angle) * L + A.x;
B.y = sin(Angle) * L + A.y;

```
> 3 votes

# Answer
This is just so you understand the logic behind drawing lines, if you understand Bresenham that might be the better option to implement.

A truly perfect pixel line is rather simple, you just need to calculate the ratio like you did in the question, the ratio *is* the angle of the line. A 45° degree line will have a ratio of 1:1.

Imagine moving a brush, if you have a 1:4 line that means for every 4 pixels you move on the y-axis you have to move one pixel on the x-axis.

Code for that could look like this:

```
int width = targetX - startX;
int height = targetY - startY;
// At least one of these will be 1
// Depending on wether width or height is larger.
int wRatio = (width / height) || 1 * (width / abs(width));
int hRatio = (height / width) || 1 * (height / abs(height));
int iterations = max(width / wRatio, height / hRatio);
int i = 0;
while(i++ < iterations)
{
  [... draw line segment (filled rectangle) at x,y with width wRatio and height hRatio ...]
  x += wRatio;
  y += hRatio;
}

```

*However*, sometimes you get don't get around ratios like 1:3.5632, in this case a truly pixel perfect line is not possible. A common approach is alternating between different length line segments and this will also be the case in Bresenham.
> 0 votes

---
Tags: sprites, pixel
---


# Question
Title: How to store generic data in game database?
To clarify things a bit: I want to create a kind of database for my game, that simply is a class that stores all game-state information like object positions, player scores, etc.

The main problem I am facing, that the whole game is to be scripted, to the level of the (lua)script controlling what members should the database have.

The reason for this is that I want to create a game that gives modders complete access to the game via lua scripting.(its one of the core features) For this to be viable I need to be able to add custom elements to the database.

I want to avoid using a 'real' database and roll my own solution.

For example I want to be able to do the following in the script file:

```
-- In function init...
Engine:AddStateEntry( "Score", TYPE_INT )

-- In function update...
Engine:SetStateEntry( "Score", 12 )

```

My engine would then synchronize data between players and render things accordingly.

How could I:

* Efficiently store arbitrary types of data?(including arrays)
* Set up custom interpolation functions

Efficiency and ease of use are my main priorities.(I dont care if the implementation is complex)

**TL;DR:** How to efficiently store arbitrary data that is defined by lua scripts and stored on the c++ side?

# Answer
Seems like this is a matter of implementing an Entity-Component system?

Your "database", or game state, will be incredibly simple: it'll have a container for entities, and that's pretty much it. Each entity will have a unique id, and a container for components. Then, you run the entities through various **systems**.

So constructing the game would involve things like creating a player entity, world entity, camera entity, and so on. They're only shells, though, you need to add things like a collision component, physics component, control component, render component, to your player, and other entities.

Another important point, the **components** are **100%** data, **0%** functionality. Functionality comes from the **systems**.

To elaborate on the systems, they are like machines that take your list of entities as an input, they then make changes to the data, after which the entities go through the next system, and so on (or you can send an entity through all systems, then the next entity, then the next...).

Properly implemented, your gamestate/database will contain *all* your data, with functionality reserved to the various systems. And since entities are created as sets of data, using scripts to add entities, and components to those entities, is a trivial matter.

I could go pretty in-depth on the matter, *or* I could point you to this fantastic answer by Jon Purdy.

The important thing is abstracting the data from the functionality, and entity component systems are the typical way of achieving it. It's how Unity, for example, is built.
> 3 votes

---
Tags: c++, data-structure, lua, data-driven
---


title: Draw wireframe overlay of model in GLSL

text:
# Question
Title: Draw wireframe overlay of model in GLSL
I have a 3D model that has a GLSL script, and I want to draw a line on each border of its polygons in the fragment shader.

What should I do? Note: I am using Ogre3D, so I can't use OpenGL's functions.

So far I have this (just assigns a texture to it):

```
void main(void)
{
  gl_FragColor = texture2D(texture1, gl_TexCoord[0].st);
}

```

This means if I have a cube, I want to render 12 lines, on each border of the cube

# Answer
You may be able to do it in a shader using the linked comment above.

But if that doesn't work, you can still do it by rendering a separate batch of lines *after* drawing your shape.

If this is just a debug mode thing, there is no need to do this particularly efficiently: just walk the triangles of the mesh and draw a line along each edge of each triangle.

If this *is* going to be a runtime thing, you need to eliminate the duplicate edges that will result from adjacent triangles.
> 1 votes

# Answer
If you're using Ogre3D, then why don't you do add another pass to the material technique that is assigned to the model, as in (suppose "ball" is an Ogre::Entity):

```
Ogre::MaterialPtr ptr = ball->getSubEntity(0)->getMaterial();
Ogre::Pass * pass = ptr->getTechnique(0)->createPass();
pass->setDiffuse(1,0,0,0);
pass->setAmbient(1,0,0);
pass->setPolygonModeOverrideable(true);
pass->setPolygonMode(Ogre::PM_WIREFRAME);

```

This will add a red wireframe that gets drawn over the existing material. And if you just want a wireframe, not a wireframe on top of the current material, just substitute "getPass(0)" for "createPass()"

Or, if you would rather do it in the .material file:

```
material general/wireframe
{
  technique
  {
    // first pass
    pass
    {
      polygon_mode wireframe
      ...

```

See:

http://www.ogre3d.org/docs/manual/manual\_16.html#polygon\_005fmode http://www.ogre3d.org/docs/manual/manual\_14.html#Material-Scripts
> 1 votes

---
Tags: opengl, shaders, glsl, ogre
---