Tuesday, December 21, 2010

Scrolling Multi-layered Map

Only the top-left most part of the
generated map
The next logical step for a tilemap is to add scrolling. The problem is you don't want to be drawing every tile in the map all the time so our basic approach will not work for larger and larger maps. We need a solution that will only ever loop through and draw the tiles that are going to be visible. This snippet makes sure that only the visible tiles in the background layer are drawn. Its limited though because all the foliage tiles are drawn, however a quick bounds check might be enough to skip the expensive render calls but we would want to find a way to remove those loops entirely.

See Rendering Multi-layered Map and Rendering Basic Tiled Maps for details on other pieces in this snippet.

What's Different
Larger section of the same map
Using scrolling
The map generation is pretty much the same aside from keeping around the mapping of integers to tiles the method discussed the previous map snippets. Sorry to say it's not a very good implementation but that is an area that can be improved upon in a future snippet :) . It works for the time being.

A new update method has been added and the unused passed variable in the render thread is now being used to passed the number of seconds passed each frame to the update method. NOTE: this isn't the most accurate way of time keep as it is directly effected by frame rates and could cause jittery and inconsistent animation. But then we're not worried about animation here so it doesn't really matter. I added a keylistener to track when and which arrow keys are down in order to scroll the map. The update method handles the actual calculations to move around the map based on the keys that are pressed, it's just simple input handling nothing special. Here is the update method implementation.

/**
  * This method will move our position in the map.
  *
  * @param d
  */
 protected void update(double d) {

  Dimension screenSize = getPreferredSize();

  if (up) {
   y -= scrollSpeed * d;
  } else if (down) {
   y += scrollSpeed * d;
  }

  if (right) {
   x += scrollSpeed * d;
  } else if (left) {
   x -= scrollSpeed * d;
  }

  //clamp display area to inside the map
  if(x < 0) {
   x = 0;
  }

  if(y < 0) {
   y = 0;
  }

  // handle what happens when we reach over the edge of the map
  if(x + screenSize.width > mapSize.width) {
   x = mapSize.width - screenSize.width; //revert to last position
  }

  if(y + screenSize.height > mapSize.height) {
   y = mapSize.height - screenSize.height; //revert to last position
  }
 }

So there is some extra handling if we try and scroll outside the visible area of the map. There is bottom and left edge handling which works pretty accurately. So no matter what our speed is we ensure that as soon as the visible area is outside the map we will reset them to be exactly at the edge and never beyond.

The rendering method has been altered heavily for this snippet as it now needs to be able to handle a larger map.

/**
  * We only want to render what is currently visible on screen, so we need to
  * take into account the current starting x,y coordinates which will be used
  * to scroll through the map during updates. Our world object holds the
  * tiles in terms of a single index value
  *
  * @param g
  */
 protected void render(Graphics2D init) {
  // draw only the tiles that are visible, the visible area is given by
  // the size of the component and the current x,y starting position on
  // screen.
  Dimension screenSize = getPreferredSize();
  Graphics2D g = (Graphics2D) init.create();
  g.setColor(Color.black);
  g.fillRect(0, 0, screenSize.width, screenSize.height);
  g.translate(-x, -y); // move the graphics object to the new position

  // this will give us the row in the map grid we are starting from
  int sRow = (int)y / tileHeight;
  int sCol = (int)x / tileWidth;
  int cols = 1 + screenSize.width / tileWidth; // total number of columns
  int rows = 1 + screenSize.height / tileHeight; // total rows
  int row, col;
  Tile t;
  int index = 0;
  for (int i = 0; i < rows * cols; ++i) {
   row = i / cols;
   col = i - row * cols;

   // transform to new position in the map
   row += sRow;
   col += sCol;

   index = row * (mapSize.width/tileWidth) + col;

   // we are outside the bounds of the map, safety check
   if(index >= tiles.size()) {
    break;
   }

   // draw the tile at the given index
   tiles.get(index).render(g);
  }

  // keeping it simple, and fast
  // TODO: Optimize to only loop over visible objects in the world
  for (Tile tile : world) {
   tile.render(g);
  }
  g.dispose();

  // draw debug string on top of everything
  g = init;
  g.setColor(Color.black);
  g.drawString(String.format("%.2f (%d), %.2f (%d)", x, sCol,y, sRow), 10, 10);
 }

One of the benefits of using the HashMap approach is evident here we can pull the tile to draw from this map with O(1) constant time lookup. This is huge here because we don't need to rebuild a list of all visible tiles nor do we have to partition the map in any way. We've kept the background tiles in a single collection increasing memory efficiency and locality, hopefully. After working with Java's HashMaps you begin to wonder what you would ever do without them. 

How it works?
Going back to a previous snippet "Rendering Basic Tiled Maps" I outlined a way of indexing tiles from top-left to bottom-right.

+-x 0   1   2
y .---.---.---.
0 | 0 | 1 | 2 |
  |---|---|---|
1 | 3 | 4 | 5 |
  |---|---|---|
2 | 6 | 7 | 8 |
  '---^---^---'
Basically we will create an index like this for the visible area which is only a subset of the larger map.
+-x 0   1   2
y .---.---.---.
0 | 0 | 1 | 2 |      0   1
  |---@@@@@@@@@ => .---.---.
1 | 3 @ 4 | 5 @  0 | 0 | 1 |
  |---@---|---@    |---|---|
2 | 6 @ 7 | 8 @  1 | 2 | 3 |
  '---@@@@@@@@@    '---^---'
    Full Map        Visible
                     Area
We will iterate through the indexes of the visible area grid 0,1,2,3 and for each column and row of that visible area which will be 0-0, 1-0, 0-1 and 1-1 respectively we will add an column and row offset to them based on the visible areas position in the larger map. The offset in the example above would be 1,1 now the corresponding indexes into the larger map will be (0+1) * 3 + (0 + 1) = 4 then (0+1) * 3 + (1+1) = 5 now we move down one row (1+1) * 3 + (0+1) = 7 and the last is (1+1) * 3 + (1+1) = 8. Pretty neat huh, well at least I thought so when I came up with it years ago while making my first small game in Visual Basic 5, yeah it's been a long time since then.

Where's the Snippet
So here it is, a bit lengthy now at 639 lines but it's all in a single source file if you've been following along with the previous examples it shouldn't be hard to pickup and use these concepts in your own way, if you find them useful. I of course would love to hear more opinions on this method or better implementations. Always looking for more efficient ways to do things and squeeze every nanosecond out of that CPU. Happy Holiday coding everyone!

Tuesday, November 23, 2010

Game Engine Design: Game Contexts

I have been working on game engine design for the past... um... hmm I can't remember when I started... well lets just say it's been years. Typically I have entity objects, and a Game State Machine implementation. The entity objects became the base class for all other game objects. Entity objects would have been able to be updated and rendered. This allowed me to do everything I needed specific to each entity.

For rendering I would pass only the graphics object to each entities render method. Something that looks like public void render(Graphics2D g). For updating I would pass the time passed since the last call which looked something like public void update(double dt). Each entity would have their render/update methods called at least one per frame.

How it used to be!
As I was working on a few games using my work-in-progress engine code, I came across situations where it would be easier for the entities to already have all the information they need and have spawn and kill functions. A game entity needs to know information about the world, other objects, screen sizes, etc. Also I needed the ability for an entity to change states of the game system. But that is only because the entities were checking input and doing game logic.

The system worked fine the way it was, it was just very painful modifying constructors and adding parameters to methods, I had even modified the render methods sometimes to be passed the time and dimensions of the screen. I constructed a Spawner interface which essentially was implemented by my world container class and allowed objects to have a spawner and to spawn other objects. The spawner was really really nice because it allowed any entity to create new ones on the fly the creating entity could hold on to them and then kill them if need be. The problem with this approach is that each object contains a reference to a spawner, which had to be set and could potentially not have been set causing errors or lots of additional null checks.

Enter Game Contexts
I am a big fan of Design Patterns and after experimenting with different design patterns in games such as the Composite, Observer, Visitor and Mediator. I found that what my entity objects needed was a mediator between them and the rest of the game system. So I figured I could put all the methods and information needed by the game objects into an interface to be implemented by the main game class. It turned out to look something like this
public interface GameContext {

    // the width of the screen
    public int getWidth();

    // the height of the screen
    public int getHeight();

    // the input manager
    public InputManager getInput();

    // the time passed in seconds between frames
    public double getTimePassed();

    // spawn a new entity
    public void spawn(Entity e);

    // kill the entity
    public void kill(Entity e);

    // switch game states
    public void changeState(State next);

    // return the graphics object used for rendering
    public Graphics2D getGraphics();

    // set fullscreen mode
    public void setFullscreen(boolean fullscreen);

    // return whether the game is fullscreen or not
    public boolean isFullscreen();

}
This interface gave each game object the methods it needed to do a lot more than they could before. The render/update methods now changed to
public void render(GameContext gc);

public void update(GameContext gc);
It really does make a lot of difference when creating new entities and you can add lots more to the GameContext. For instance you could have a method for collision detection or initiating certain effects etc... It is also just as efficient as the previous method since only one parameter is being passed to the game objects.

I hope to show a full runnable snippet using this idea sometime in the future. This should be enough to get you started if you already have something in place. If you have an alternative method to share it would be much appreciated, or if you've already used something like this it would be nice to know as well.

That's all for now, getting ready for Turkey day.

Tuesday, November 16, 2010

Rendering Multi-layered Map

Similar to the previous snippet only now the
green squares and diamonds represent some foliage.
Note: That the map generation algorithm still needs
a bit of work to make decent looking terrain.
When using a map in a game you always are going to want to draw items equipment and perhaps buildings and structures on top of terrain. This is known as layering, you may be familiar with it if you have done used photoshop or perhaps in making your own games. It is even used in GUI programming although it is usually referred to as z-ordering. You want to use it anytime you have a rendering order in which something you are drawing will appear on top of a part of something else but doesn't fully cover it. In 3D graphics many times you don't have to worry about the order in which you draw objects since the graphics card will automatically determine per pixel drawn if it is covered by something else, that entails using a depth buffer.

If we wanted to we could implement our own depth buffering system on the CPU side, however it would take a lot of processing power and be inefficient. So we will draw in top left to bottom right order drawing the bottom layer and then each layer above that separately.

Ordering

So how do we determine this order and make it flexible for pretty much any game we want to create. Ones first instinct is usually to make a list or map of layers each layer containing all the objects to be rendered on that layer, and traverse these nested lists in order. This results in some nested for loops which I try to avoid at all costs. So my solution is to order each rendered element when you insert it into the collection of all elements to draw. This makes the rendering loop a single continuous loop we can't get much more efficient than that. The only other optimization we can do is to make sure we only draw what is visible on the screen, and nothing we draw is unnecessary, sometimes the cost of removing those unnecessary loop cycles is to expensive so it's best to just try and determine them beforehand or not at all.


Code Snippet

This snippet is based off of the previous snippet Rendering Basic Tiled Maps. Not much has changed between the two except the tile class, map generation function, and tileset generation function have added support for layers demonstrated by some placeholder images. The map generation algorithm I'm afraid is a little bit confusing.

How Layers Work

This implementation sets each tile with a layer integer that is used in the TreeSet red-black tree sorting. Which makes it efficient because you are going to order the tiles and layers when creating the map and you don't need to touch it after that. Another way of doing this would be to use an ArrayList or any other sortable collection in the Java Collections package and sort when you need to, especially if you need constant time access into the collection. Alternatively you can create another collection of the tiles or containers of subsets of the map in order to do whatever you need. I choose to use TreeSet as it is simple enough for this example, and I won't be needing to do anything but draw the list of objects on the map.

The rendering loop remains the same, just as simple as we can possibly make it.
protected void render(Graphics2D g) {
  // keeping it simple, and fast
  for (Tile tile : world) {
   tile.render(g);
  }
 }
Any simpler and it'd just be a completed list drawing each tile individually in the order we wanted.

The real meat of this snippet is in the compareTo function of the Tile. Because the TreeSet either requires a comparator to order the elements or requires the element type to implement the Comparable interface we need to provide one of the two. For simplicity I choose the later of the two, even though making a Comparator would be advantageous because then it would be easier to add different types of objects to our map other than just Tile objects.
/* (non-Javadoc)
   * @see java.lang.Comparable#compareTo(java.lang.Object)
   */
  @Override
  public int compareTo(Tile o) {
   if (layer > o.layer) {
    // this object should be displayed after o because it is
    // on a higher layer than o
    return 1;
   } else if (layer < o.layer) {
    // o should be displayed before this object because it is
    // on a lower layer than o
    return -1;
   } else {
    // if there are on the same layer sort them top,left to bottom
    // right order
    if (y < o.y) {
     return -1;
    } else if (y > o.y) {
     return 1;
    } else if (x < o.x) {
     return -1;
    } else if (x > o.x) {
     return 1;
    } else {
     // their in the same position same layer, this is probably
     // not intentional, but could happen
     return 0;
    }
   }
  }
 }
A bit messy but it gets the job done efficiently. So we compare the layers, if the two objects are not on the same layer there is no need to go any further we return 1 meaning that the tile compareTo was called on should come after the tile o because its on a higher layer, and -1 if it should come before the tile o.

If they are on the same layer we are going to order the objects from top-left to bottom-right order. So we compare the coordinates of each tile. This is actually something that can be handled by the indexing method I explained in the previous post.

So here is the snippet for you to play around with comments are welcome as always.



Tuesday, November 9, 2010

Rendering Basic Tiled Maps

Auto generated map and tiles it's a
bit rough though.
O.k! So this snippet is a little lengthy, I could not find an acceptable way of showing the map without either using a random map generator or including code for loading a map from a file. I choose the former but the algorithm didn't quite turn out the way I had hoped. It's a bit messy as I tried to avoid recursion and also the generated maps don't really look spectacular. Although it should get the point across and provide a basis for much more work to be done with it.

Tiles
The tiles are a bit complex and I hope to show much easier and cleaner ways of both representing and rendering. While there is nothing wrong with a loop through all tiles drawing each in it's own known position. It doesn't provide the flexibility we need to add features such as layers, smooth scrolling, at least not in an efficient way. We later we will want to limit our drawing to only show the part of the map that is actually visible, and maps can get large.

Inevitably these limitations will force us to make trade-offs for game performance. If we draw more we will have less time to devout to updating enemies and objects that aren't even on screen yet. And the levels can get larger and larger. Which is why there are concepts like check points and areas where the level is split up. It's not so much keeping that in memory as it is updating those objects every frame. Unfortunately for most game concepts you can't remove unneeded updates to those objects easily unless your game is designed for it. This is most true in strategy games and simulations where the drawing only accounts for a small fraction of the total number of updated objects. But more on these later.

Oddities in Snippet
A couple things you might find odd about the way I coded the rendering algorithm or my coding style in general. First of all I dislike large procedures so I will try my best to keep every method simple, though there have been a few lengthy ones but they have almost always been cohesive. I avoid nested loops like the plague, so for the creation of the map I use a little mathematical trick I conjured up myself.

I take the x, and y coordinates and transform them into an index into a grid. The index counts left to right from the top, left tile to the bottom right. All you need to know is the width of the grid and you can calculate what the index is for a given x and y value. You can do the same with the index but it's definitely odd to see in the code.

For instance in a 3x3 grid the index of the last element or position (2, 2) in the grid is given by
i = y * cols + x

i = 2 * 3 + 2

i = 8 (qed)

Meaning that you count up starting from 0, 1, 2, ..., 7, 8, and for a 3x3 grid you get 9 indexes as you should.

So now to reverse this craziness. This is where we have the i value say for a 3x3 grid the i value is 4. Where on the grid x,y might i fall if we were to count starting with 0 from the first box on the grid and go left to right till we got to 4. We need to calculate y first as it will be used to calculate x.

y = i / cols

y = 4 / 3

The trick here is that the result is truncated. So

y = 1

More mathematically correct is the following formula for y.

y = floor(4/3)

In code if we use integers the result of the division will automatically be truncated. Now to the confusing part finding x.

x = i - y * cols;

x = 4 - 1 * 3

x = 1

So in a 3x3 grid where x and y start go from 0 to 2 each, index 4 is the point 1,1 or the second row second column.

+-x 0   1   2
y .---.---.---.
0 | 0 | 1 | 2 |
  |---|---|---|
1 | 3 | 4 | 5 |
  |---|---|---|
2 | 6 | 7 | 8 |
  '---^---^---'

As you can see the math does work out, provided we use the floor function in our calculations, in code we just have to use integers. This can be useful for representing a grid using a Map of integers to tiles where the integer key is the index in the grid.

There are quite a few different ways to use this for our drawing purposes as well as converting between coordinate systems, i.e. mouse position to grid position.

O.K! So now that I've managed to completely confuse you here is the code.

Thursday, October 28, 2010

Morning Coffee: Fun Projects

Screen capture of a 230x130 section of the heightmap below.
the 126,161 blocks are instanced using a single opengl VBO
Just thought I would share some of the personal projects I have been dabbling with these days. I just started looking at the game Minecraft, and Dwarf Fortress. Some of you are probably wondering "where have you been". Well DF (Dwarf Fortress) was started during my college years and probably didn't gain popularity and stability in the game till I graduated so theres that, and Minecraft is a recent development and quiet popular.

They are very interesting concepts and my mind has been spinning since I was introduced to them by a guy at work. So my project is to make my own game based off these two games. I have always liked the idea of an infinite gameplay world where the player can build pretty much anything they want and create a completely unique experience for themselves. Basing things off a simple set of blocks seems like the easiest way to go. I could just play DF and Minecraft but there are too many things I know I would like to have or different ways I would have done things as it is with most games I play.

Oh that and the fact I am pretty broke atm, too many bills to speak of, darn economy. So paying for Minecraft didn't sound good at this point though I will probably give it a try when I have that extra $15. I have started playing DF but I'm afraid the game is really involved and will take me a while to get into it. I am slowly beginning to learn how to play. So I decided I'd start by using JOGL (hehehe).

634x427 Procedurally generated heightmap using perlin noise.
4 octaves and 0.205 persistence
I ran into some issues with the Depth Buffer not working correctly. I basically took a simple cube example from Nehe and fixed it up a bit. It was Lesson 05 and I had to fix up the code a little bit because of the changes to JOGL for the most recent aggregated build. And I used a perlin noise generator I wrote based off of pseudo code from an article on perlin noise. So the image above is the generated world, with only a small 250x130 section of the heightmap generating 842,456 blocks, and further reduced to only about 126,161 being drawn. Performance is pretty bad right now because I am drawing all 126,161, no fog or visibility culling. But then lighting isn't turned on which is my next task and will probably kill my Nvidia GeForce 8400 GS.

I also implemented the Quaternion Camera Class from the Nehe Lesson: Quaternion Camera Class. I had to implement the quaternion of course I was kind of surprised JOGL does not have an implementation for Quaternions. But then it's supposed to simply be Java bindings to opengl.

Angled View: All 126,161 also notice the cutout portion at the bottom.
Apparently the algorithm needs some work, I don't need the blocks
on the bottom, or on the sides.
Since I have done a couple implementations of terrain generators and various other land, maze generation it wasn't that hard to implement. I hope to provide from useful snippets for procedural map generation soon. Today's post was actually going to be about 2D map/level rendering, but I didn't have the snippet ready so I decided I'd write about this little side project instead. By next Tuesday I should have a series of snippets on 2D map and level rendering done. My plan is to go over ways to rendering 2D maps and levels drawing only the visible area, showing a really nice way to draw layers, and how to do smooth level scrolling. After that it's on to collision detection algorithms, and then after that I can finally get to the meat and reason for creating this blog and show the really interesting gameplay snippets and talk about the fun part of game programming.

Side-View: The removing the side and bottom layers of blocks
should reduce the amount of blocks even more
Ok that's enough rambling for this morning.

Tuesday, October 26, 2010

Angular Character Movement

So as you've probably noticed the past few posts have been about character movement, the first being Basic Character Movement where I went over briefly a few movement style options you have for making a game. This post is going to be another extension of the character movement snippets, where the character will only be moving forward but this time the right and left arrow keys will turn the character right or left. This gives you full 360 degree movement.

Implementation
The code changes are fairly minimal as we still are only interested in whether the up, left, or right arrow keys are pressed. We need to utilize some trigonometric functions sin and cos to determine the amount to move the characters position in the x and y directions, respectively. Here is the new update function:
// angular movement is based on a radian angle for direction

  if (right) {
   this.direction += -0.2; // angular turning speed
  }

  if (left) {
   this.direction += 0.2; // angular turning speed
  }

  if (up) {
   // the movement calculations, sin and cos are used to get the
   // distance in x and y directions respectively. We multiply by the
   // timed passed so that we get more accurate movement and then the
   // speed variable controls how fast the block moves. And it has
   // specific units which are pixels per second.
   basicBlock.x += Math.sin(direction) * dt * speed;
   basicBlock.y += Math.cos(direction) * dt * speed;
  }
As you can see it's not that many lines of code, the right and left arrow keys will change the direction angle which is in radians. You can put it in degrees if you want but radians gives us more precision.

Upgrades
You might want to play around with this snippet a little and try enhancing the turning speed. If you multiply the amount to turn the character by the time passed you can make movement a bit more smooth and consistent. You can also easily add in some basic collision detection and make a nice little game out of this snippet. Combine it with the Game State Machine and the Keyboard Input: Polling System in Java possibly the Toggle Fullscreen Mode and a few other snippets I've posted and you've got a decent basis for a nice little Java game. Then the only limitation is your creativity in gameplay.

So here is the snippet for you to play around with:


Next -> Mouse Movement

Thursday, October 21, 2010

Character 8-Directional Movement

Eight directional movement is where the character can move in any of the following either directions: north, south, east, west, northeast, northwest, southeast, and southwest. This is a common top-down RPG style movement. Of course each game is free to modify and create it's own type of movement. For instance the classic game Asteroids, your ships movement was propelled by a rocket in the rear of the ship thus it always moved you in the direction your ship was facing for the time you applied thrust. You could turn left and right rather quickly but forward momentum always kept carrying you in the same direction. Momentum and friction are used commonly enough in movement it will be worth covering at some point.

In order to make 8 directional movement using the previous Basic Character Movement snippet, some pretty small changes need to be made. It isn't much and you possibly already know what those changes are, or have made them yourself if you've messed around with previous snippet.

So we are already capturing the keyboard state for the keys we care about and they are all the arrow keys and in order to do 8 directional movement we only need to know whether those keys are being pressed or not.

// 8 directional movement, n,s,e,w,ne,nw,se,sw

  // direction variables used to determine whether to move the block in
  // either the x or y directions.
  int dx = 0;
  int dy = 0;

  if (up) {
   dy = -1;
  }

  if (down) {
   dy = 1;
  }

  if (right) {
   dx = 1;
  }

  if (left) {
   dx = -1;
  }

  // move the block by multiplying the amount of time in seconds that has
  // passed since the last update by the speed constant and by the change
  // in x or y directions which will either will result in += 0 or
  // dt * speed negative or positive.
  basicBlock.x += dt * speed * dx;
  basicBlock.y += dt * speed * dy;
As you can see above the difference between the previous snippet and this one is that in the previous update code only one of the if statements would be handled and so if dx was non-zero then dy would always be zero which means no movement in the y direction. Now we allow dx and dy to both be set to anything depending on the arrow keys that are currently pressed.

So here is the snippet for you to play around with:



Tuesday, October 19, 2010

Basic character movement

Moving a character is probably the first thing that you want to do when making a game. There are many different ways to move a character however. This time I will only cover a very basic way of moving a character, I will post more movement examples later. But its good to start from a simple example and it should be enough to get you started making games.

Movement Types
This snippet will show 4 directional movement. Which means the character is will only move in one of four directions. This is an extremely simple movement type but is still very applicable for a lot of games. Platformers for example only use 2 directional movement, right or left, with the added jumping and climbing mechanics in some games. Pacman is an example of a game that uses 4 directional movement even though you are limited to continue moving in that direction until you hit a wall. More complex example of movement are ones such as 2D shooters which either have 8 directional movement or 360 degree movement. Almost all utilize the arrow keys on the keyboard, or a D-pad/thumbstick on a gamepad. Some like the point-click movement only use the mouse. New styles of movement are possible with the emerging multi-touch screens and are especially applicable to iphone and android game developers.

So this snippet needs to handle events, for simplicity I will only use the basic KeyListener interface in java.awt.event. It works well enough for a demonstration of movement. If you want a more game oriented input system see my Keyboard Input Polling System In Java post which goes over how to turn the interrupt driven awt event system into a polling system.

Aside from character movement there are other types of movement some simple and some complex. For instance, click to move here types of movement, these can actually be a bit more complex and utilize path-finding algorithms (i.e. A* for shortest path), which I hope to cover later as well. There is also tactical movement or tile based movement, used mostly by turned based games, where the play field is a grid partitioned into tiles and each turn a character has a specific number of movement points or speed which allows them to move a certain number of tiles in certain directions or along a path around the play field.

Buggy Movement
I remember when I first started coding games my movement code was hideous compared to what I use now. One of the first implementations I used was to increment the characters (x,y) position every key pressed event. The problem with this approach is that it relies heavily on the speed and number of interrupts. I also used to do a lot more in the KeyListener interface, like doing collision detection and almost all the game logic using the key events instead of a timed update call. Those are just a couple examples of things that might create some buggy movement. A much more subtle cause of buggy movement for more advanced game implementations is due to tying the amount to increment (x,y) to a single update. So depending on how many updates you get per second the character will move that much. This can become a problem if the updates happen to take longer than expected or shorter than expected. So tying an objects movement, not just characters, to how much time passed between calls will fix most problems. Of course determining when an by how much to move an object each frame can get quite complex.

Example Details
The snippet for this post uses the KeyListener interface which many know is interrupt driven meaning the operating system your running under sends your program key events, through whatever it's underlying system may be. We don't want to do much at all when we get a key event and certainly no incrementing of anything that affects the game. We simply want to change the state of the keyboard and only the keys we care about. For instance the up-arrow key, we will store whether it's pressed or not. Right now for movement we only really care about doing something specific for the length of time it is being pressed. So we simply save a single boolean state (true/false) for each key we care about. So for 4-directional movement we just want to know if the up, down, left, right arrow keys are pressed (true) or not (false). This makes it simple to write code that only happens when a specific key is down (pressed).

Simple enough so what do we do while the key is down? Well since this is an example of player movement we move the player...in one of 4 directions either north, south, east, or west. Ok well here is the basic character movement snippet, it is based off of the BufferStrategy snippet.

Thursday, October 14, 2010

How to use BufferStrategy in Java

One of the things I didn't know when starting Java programming was the state of the hardware acceleration support. Java does provide hardware acceleration. In earlier version the double buffering was a bit buggy but since jre6 it works very well in swing. It also uses DirectX and Opengl under the hood which you can enable/disable. Hardware accelerated drawing is enabled by default on most systems where it is properly installed. To take advantage of this hardware acceleration you want to use a java.awt.Canvas component. You can let swing do the double buffering which entails simply repainting the screen and not worrying about using the BufferStrategy class. It seems to perform well, so you should test both methods out and see which works best for you. In this snippet I will not mix swing and awt so I use a Frame instead of a JFrame. I noticed from an early access release of jdk7 that if you use a Canvas component inside a JFrame nothing will draw, unlike jre6 and below where it doesn't present an issue. I do not know whether this is intentional to try and keep native resources and lightweight resource from conflicting or some other such implementation detail but it did cause me a headache for a little while.

VSync Improving Visuals or Triple Buffering
This is a minor annoyance when running in windowed mode for a game. Occasionally the display and the drawing of the window will become out of sync and cause some tearing or jittering of the constantly refreshing window. It happens due to not being able to refresh the window contents at the exact same rate the display is actually refreshing the entire screen. This isn't too noticeable with such high refresh rates on monitors, but just in case you need to be able to do this, there is a function. I didn't really know about it till recently, it's in the java.awt.Toolkit called sync(). You can also create a buffer strategy with 3 buffers, or triple buffering, which is known to almost eliminate the need for the sync so that your program isn't in the middle of drawing to the buffer while the display is drawing from the buffer.
EDIT: Use java.awt.Toolkit called sync() to update the display buffer (whatever that really is) to be the most current drawing surface in the buffer strategy. Should help ensure the user sees the latest and greatest from the application.

Other Useful Options
A number of different options are also available as System Properties for java2d. For instance the trace property which tells you how long and specifically which drawing functions are called. This will let you know whether the hardware acceleration drawing layer in Java is being called at all.
java -Dsun.java2d.trace=log
Setting System Properties in the code
A nice thing to be able to do is to use a configuration file loaded by your program to save/load these types of graphics options or other kinds of options that your program may allow the user to change but are used by the Java API before the application starts. I like to use static initialization blocks for this. So I will have something like the following in my main class.
// performance settings.

static {
    System.setProperty("sun.java2d.transaccel", "True");
    // System.setProperty("sun.java2d.trace", "timestamp,log,count");
    // System.setProperty("sun.java2d.opengl", "True");
    System.setProperty("sun.java2d.d3d", "True");
    System.setProperty("sun.java2d.ddforcevram", "True");
}

You can set it up however you like and even get complex with it, loading the settings from a config file like I mentioned above, or popup a nice little window with selectable options for d3d versus opengl. The trace line specifies the format of all output from java2d as described in the system properties link.

Using BufferStrategy
Use the createBufferStrategy(int numBuffers) in the canvas component only after the frame has been created and displayed. You can control how many buffers to use for rendering, the most I'd suggest would be 3 any more than that is overkill, imho. Creation of the strategy may cause a java.lang.IllegalStateException to be thrown if the canvas does not have a parent who is being displayed. Meaning you need to add the Canvas component to a Container and make sure that container is visible.
// create a strategy that uses two buffers, or is double buffered.
  this.createBufferStrategy(2);

  // get a reference to the strategy object, for use in our render method
  // this isn't necessary but it eliminates a call during rendering.
  strategy = this.getBufferStrategy();

To use the BufferStrategy for rendering you want to use the strategy's getDrawGraphics and show methods. The getDrawGraphics creates a Graphics2D object that will draw to one of the buffers, if you are using 2 or more buffers this will be an offscreen buffer, allowing you to draw everything completely before displaying it which eliminates flickering and allows you to clear the buffer without the user noticing, and being able to redraw everything. Clearing and redrawing is essential for animation as you want to redraw the entire screen when objects move or change.

Example drawing code from the snippet:
// the back buffer graphics object
  Graphics2D bkG = (Graphics2D) strategy.getDrawGraphics();  
  
  // clear the backbuffer, this could be substituted for a background
  // image or a tiled background.
  bkG.setPaint(backgroundGradient);
  bkG.fillRect(0, 0, getWidth(), getHeight());

  // TODO: Draw your game world, or scene or anything else here.

  // Rectangle2D is a shape subclass, and the graphics object can render
  // it, makes things a little easier.
  bkG.setColor(Color.green.darker());
  bkG.fill(basicBlock);

  // properly dispose of the backbuffer graphics object. Release resources
  // and cleanup.
  bkG.dispose();

  // flip/draw the backbuffer to the canvas component.
  strategy.show();

  // synchronize with the display refresh rate.
  Toolkit.getDefaultToolkit().sync();

Precision and high frame rates
To make a good game you really do not need more than 60 frames per second. There is a lot of discussion about the subject and many say that the human eye will always be able to see screen refreshes. I think that it has nothing to do with the frame rate as much as with the movement and update timing. As long as the animation in your game is smooth without noticeable and often glitches then it will still be professional. You can always try and aim for a higher frame rate I think I have seen suggestions about around 100fps and I don't know why it's that number, jumping from either 30 to 60 and then all the way to 100. That's 1 frame every 10 milliseconds. While you can do a lot in 10 milliseconds there is a lot you can't do, so find what works best for your game and try and keep the amount objects moved every frame to change at a steady rate relative to their speed. So if an object is moving really fast across the screen small fluctuations in the rate of change in position every frame will cause jittery and jerky movement.

For this snippet I will not show the particulars of creating smooth movement that is for later snippets, where I will go through different kinds of movement. So at long last here it is:

Monday, August 23, 2010

New Layout & Design

Just thought I would play around with the template designer. It's nice that they added customizable sidebar sizing amongst other things, including being able to add custom css without messing things up too much.

I hope to add a few pages about game design and development, perhaps even game engine architecture and object-oriented design, suggestions are always welcome.

Monday, July 19, 2010

The Morning Coffee: Status Update

Hello, just thought I would take some time during my morning coffee and paper reading to give a little status update. Well not so much coffee and paper these days as coffee and internet news reading.

Every morning I usually sit down at my computer with my coffee and read industry news, blogs, articles, and do some web surfing. It's a good way to keep myself up-to-date with the game industry. Lately I've been looking into the Android games market, which looks very promising, especially for a Java veteran like myself.

Recently I've been engaged in a Java 2D game project with an artist friend of mine. We have been making slow but steady progress, as my full-time job and summer family activities have taken up mush of my time. For this project Java has proven a more than capable language and platform for 2D games, with hardware acceleration using DirectX and Opengl allowing for good performance. There are a few subtle points such as which collections classes to use (i.e. Lists versus Sets versus Maps, and don't forget queues). Care must be taken in removing objects from these collections as they all are expensive except for using queues.

I've been toying with a few articles to post here to help beginners and veterans alike. A couple being bare bones getting started with directx, and how to achieve different player movement styles in games. These have been slow going as my time is quiet precious. But I do hope to have these posts published at some point.

The most important thing I think for any indie or hobbyist game programmer is to just make something, it doesn't have to be extravagant or the next triple A title or even next generation graphics. Games are still engaging even without spiffy graphics. These are some of my words of wisdom and they apply as much to myself as hopefully they do for all my readers. A finished polish game even a text-based one is worth a lot and helps to provide confidence and understanding into the process of completing a game.

As positive encouragement you can always go back and update past abandoned projects. I know I find myself looking back at my 100 or so java projects in eclipse and occasionally looking at my code and updating a few lines here or there, fixing some issue recoding somethings. It helps to relieve some of the stress of other projects when they get halted or uninteresting or just have no direction left.

Another word of wisdom is that prototyping games can be done with a text-based game. I find them easy to write and a good test of ones game designing skills. As a programmer I sometimes find it hard to work with a game idea without adequate art content but it's better to either forgo waiting for that process to happen by using placeholder images or just by simply doing a console prototype. Even if you have a text-based prototype of a game that can be a good step forward into making it a 2D or 3D game. It is more valuable than a completed game design document, in my humble opinion. And you can use any text-based games you've made as stepping stones for larger game projects.

So in conclusion of my coffee and morning blog post. I will be touching more on game design and mechanics as they are a passion of mine, as well as words of wisdom from my experience as a hobbyist game developer. I would also like to touch on game engine design in the future so look for some posts about that as well.

Good luck to all the indie and hobbyist game developers out there! Keep up the good work!

Tuesday, June 22, 2010

Silverlight Room Escape Game Prototype

Thought I would post an old Silverlight project, I worked on a few years ago. It isn't much but it shows the basics of making a Room Escape game in silverlight, with ExpressionBlend.

Postmortem

Room escape games are not that hard to create in Silverlight and aren't performance intensive. Making one based on this example shouldn't be entirely difficult. However a large room escape game might be hard to manage as puzzles become more complex. The project got kind of swept under the rug, there was a plan to make an editor to provide a way of managing the puzzles and images better. I believe an editor would be necessary for any lengthy room escape game. Although if you are doing the project by yourself and don't plan on making more than one room escape game I would suggest not trying to make an editor as it won't really be worth it.

RoomEscapePrototype1

Tuesday, April 20, 2010

How to make games?

Here is a list of 10 steps I put together to help focus your efforts in making games. And to give some idea of a process for creating games.

Step 1: Get an idea for a game, do some storyboarding, some web diagrams even.

Step 2: Choose a technology you know or want to learn Game Maker, Unity, Construct, RPG Maker, Ogre3D, jME, Irrlitch, XNA, directX, opengl, jogl, lwjgl, pygame, Source SDK, UDK, CryENGINE and for modding visit ModDB or search for how to mod games you own.

Step 3: Choose a image editor that you know Paint.NET, PhotoScape, Photoshop, PaintShopPro, GIMP.

If you want it to be a 3D game choose a modeling program

Step 4: 3D Studio Max, Maya, Blender, ZBrush, TrueSpace, Softimage, SketchUp Pro.

Step 5: Depending on the technology you chose, you need to choose file formats, image sizes and of course other scope issues, make sure those file formats are supported by the technology you chose. Other scope issues like how many levels, weapons, types of enemies, types of characters, different screens. This will help keep things structured, and give you a good idea when your done.

Step 6: Design a 1st level this must be complete all the way through no gaps. Don't hold yourself back because you think something can't work, just try it and change it later if you find it doesn't work.

Step 7:
If you are programming it yourself or even if you are doing a MOD or using a game making application, work on making the core gameplay mechanics first such as shooting enemies and gaining points. Getting and completing quests and leveling up etc.

Step 8: Once you have a playable 1st level with place-holder images and models and other content. It's time to finish it up, with placeholders of course, just use place holders everywhere don't worry about it looking horrible you can always make it prettier.

Step 9: Now you can make it pretty, smooth out the graphics a little, do some performance enhancements, etc... Make the art style consistent add in more effects, to make players give the "cool" and "I like it". This would be known as polishing. Remember it's only that first level.

Step 10: Depending on which technology you chose you want a Level Editor unless all your content is randomly generated in code in which case this list may not do anything for you. This is the step where you churn out content after content, basically the part of the game making you really wanted to do.

Friday, April 9, 2010

Site traffic report

I know I like seeing this on other blogs to get an idea of where I am comparatively. So I figured I'd post some averages for those who have their own blogs.

I get on average about 10 visits per day, 15 pageviews leading to a high bounce rate which probably means I don't have enough cross links or interesting posts, hehehe sorry about that gotta work on it a bit. I've always kind of struggled determining the what to post. Hope to improve that in the future.

So as you can tell from the daily average I get around 300 visits per month. My adsense revenue is extremely low due to poor site placement and for a while I had way to many ads and can't get them into more prominent positions. If your interested in reading on improving your own adsense revenue I found this article confirmed all other research I have done on the subject.

Simple Changes Doubled My Adsense Revenue

So my adsense revenue is less than 5 cents per month. Sorry I can't quit my day job and become a net millionaire just yet, lol. My goal is to provide more useful posts that help you make games from my own experience and knowledge. I can't say that I am the smartest game making hobbyist but I have been programming games in my spare time for the past 10 years or so and have picked up a few tricks, as well as learned more programming languages than I care to admit, hehehe.

I hope that anyone visiting the site for whatever reason can help me help them, spend some time make some comments, what would you like to see more of, where have I failed, what needs improvement etc...

Tuesday, March 23, 2010

Eclipse Tips

Eclipse Shortcuts I use the most:
Ctrl + Click = Source Browsing (absolutely amazing)
Ctrl + Shift + F = auto format
Ctrl + Shift + O = auto organize imports
Alt + Shift + R = Refactor Rename
Alt + Shift + S = source menu
Alt + Shift + T = Refactor menu
Ctrl + 1 = Quick fix proposals
Ctrl + 2 +  F, L, R = Assign to field, local variable, or rename
Atl + / = Auto complete word
F4 when caret is on a class = brings up Hierarchy
Ctrl + O = quick outline, very useful for moving to a function or seeing implemented functions as well as the outline tab.

General Windows Document Navigation Tips:
Ctrl + Arrow Keys = Right Arrow – next word
        Left Arrow – beginning of word
        Up Arrow – End of Line (same as End key)
        Down Arrow – Beginning of line (same as Home key)
Ctrl + Shift + Arrow Keys = Same as above but selects words or lines
   Exceptionally useful is Ctrl + Shift + Up Arrow selects the whole line
Ctrl + Home = Goto beginning of document
Ctrl + End = Goto end of document

Thursday, January 28, 2010

Jogl: Texture Transparency

So here's another JOGL example for drawing transparent textures. The code is a bit lengthy but the comments should help guide you to the important parts.

The most important piece of code is turning on blending.
  gl.glEnd();

// Really basic and most common alpha blend function
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);

tpTexture.bind();

gl.glBegin(GL.GL_QUADS); // the gl draw mode
One thing you must note here is that the texture binding is done outside the glBegin and glEnd calls as well as telling the device to turn on blending and setting the blend function.

Other code to note is the creation of a texture from a BufferedImage, which is covered in a previous post so take a look at that first, Drawing HTML with JOGL Part 1: Textures. This example is based off of that code.

NOTE: Also, be sure to pay close attention to the order in which transparent textures are drawn.

And now the code:
This example uses JOGL version 1.1.1a and should work with the NetBeans plugin you can obtain the version from JOGL's website go to the "Archived Builds" page from the navigation menu on the left. Then find the jsr-231-1.1.1a folder

Monday, January 4, 2010

Image Transparency

How to make an image transparent in Java?

Here is one method for making a specific color transparent for any image.
public BufferedImage clearColor(Image image, Color color) {
int width = image.getWidth(null);
int height = image.getHeight(null);

BufferedImage bImg =
new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);

// transfer the source image a new 32 bit per pixel
// image need to give some images a 8 bit alpha
// channel, makes our images uniform, color depth
Graphics g = bImg.getGraphics();
g.drawImage(image, 0, 0, null);

// go through all the colors
int total = width * height;
int x = 0, y = 0;
int c[] = new int[4];

WritableRaster wr = bImg.getRaster();
for (int i = 0; i < total; ++i) {
// avoid nested loops
y = i / width; // truncated
x = i - y * width;
wr.getPixel(x, y, c);
if (c[2] == color.getBlue() &&
c[1] == color.getGreen() &&
c[0] == color.getRed()) {

//clear the color at x,y
bImg.setRGB(x, y, 0);
}
}
return bImg;
}
Another method would be to edit the image in an image editor and make the background color transparent saving the image to a format that supports transparency.

Here is the example snippet: