Starting some more code for fun

Haven’t done any games programming in a while, so I kicked off a new project using libgdx. It provides a bunch of utilities for making cross-platform games, and I especially like the JSON loading utilities and the Pixmap utilities for drawing.

Since I’m just doing this for fun, and I’m an awful artist, I started by playing around with some Link’s Awakening spritesheets to see if I can replicate a 13-year old game. Loading the image is trivial with libgdx:

Pixmap image = new Pixmap(Gdx.files.internal("filename.png"));

This gives you access to a Pixmap object that can be used to draw into other pixmap objects. Once you’re happy with your drawing you can write it to a Texture and draw it on the screen. I wrote some quick code to extract the individual tiles and drew some random art to the screen.

Random Tiles

Obviously not the most useful but fun to look at. Even the code calls out the uselessness of the method.


// Not a very useful method.
public Tile getRandom() {
Random random = new Random();
return get(random.nextInt(tileCols), random.nextInt(tileRows));
}

In order to do something useful with it, I needed to create maps from the tiles that I was using. I decided to add a layer of abstraction around the concept of a tile, so that it’s not just a graphic. So I broke it up into spritesheets – purely graphical objects – and tilesets – which contain gameplay semantics.

The JSON interfaces that libgdx provides allow files to be loaded with a small amount of code. I whipped up a quick tileset description and a loader for it to describe the various tiles that were available in the sprite sheet.


{
spritesheet: {
image: "overworld.png",
},
tiles: {
grass_ul: {
c: 0, r: 5,
passable: true,
},
// ...
house_roof_blue: {
c: 8, r: 2,
passable: false,
},
// ...

Once the sprite sheet was loaded, I created a map object that would be the actual method of interaction with the game, and created a loader for a test map that I made as well.


{
tileset: {
file: "overworld.tileset.json",
},
width: 10,
height: 8,
tiles: [
[tree_dr, grass_l, grass_h, grass_h, grass_h, grass_h, grass_h, grass_h, grass_h, grass],
// ...

After a bit of organization, and about an hour or so of work, I had something that looked a bit more pretty, if less chaotic.

House

Playing With Graphics

In High School – years ago – my passion was graphics programming. I enjoyed doing things that, back then, were close to the bleeding edge of graphics. Being able to replicate an effect I saw in a AAA game of the time (The battle transition from FFX, if you want to know) was exhilarating.

Flash forward a few years, and I wanted to see what the new video cards can do, as well as making sure I can keep my skills sharp. I look up what I remember working with – OpenGL – and quickly discovered that many of the things I learned no longer apply.

You see, when I learned, the most common approach to graphics programming was to send commands directly to the Graphics library. ARB_texture_buffer_objects were just being developed, and most people were happy to send individual vertex commands to the card. (Shout out to NeHe’s tutorials as they helped me learn the fundamentals well.

Now, however, sending individual vertices to the card is called – at best – quaint. Because the hardware is much more powerful than before, the weakest link is no longer the CPU sending the commands, or the card receiving the commands – it’s the bus that allows data to be transferred between the two. [1]

I thought a good test was to build a nice simple game.

A 2d sprite-based RPG perhaps?

So of course I chose the best microscope I had available to bash in that nail. I jumped immediately to LWGJL to play around with it. A low-level native abstraction around OpenGL. Incredibly overkill for a sprite-based game. But I saw a challenge and wanted to learn all of the cool new things.

LWGJL did actually release a new version since I looked at it last, and the documentation for it was very sparse. I found a good introductory tutorial to the low-level library and played around with porting that example.

After an hour or two of tinkering I finally had something usable!

triangle

Well, it’s almost like a teapot.

LWGJL is a good native layer for OpenGL in Java, and I look forward to seeing the tool – and the developer community – expand. In some cases, the Java binding is actually easier to understand than the original API call.

For example, this is the basic code to create a VAO in C++:

GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);

And here’s the equivalent Java code:

glBindVertexArray(glGenVertexArrays());

Sure, I’m cheating a bit by using the response of glGenVertexArrays anonymously, but this is the type of improvement that’s insignificant really, but smoothing rough edges is something that’s appreciated in all libraries.

I’m not sure whether Java is the right tool for game programming, but it has definitely improved over its past reputation. If critical low-latency applications can be built with it, why not games? 16ms is a perfectly reasonable latency target for rendering a frame of a game.

[1] Citation needed.

1D Tetris – Part 1 of 1

So recently at work, my coworker installed a light strip in our office. Because it’s not enough to install shiny toys for people to play with, he hooked it up to his desktop and exposed the interface to the strip to the internet. Now that’s a challenge I couldn’t pass up!

The strip itself was simple – a set of 60 LEDs arranged in a row, and each LED could be set to any RGB color. The interface to the tool was even simpler – a REST POST to a port on my coworker’s LED would update the entire strip. If you sent a single color triplet, such as [[255,0,0]], it would set the first light to red, and the rest of the strip turned off. If you sent [[255,0,0],[255,255,0]], it would set one light to red and one light to yellow. And so on. An open API, ready to attack play with!

Of course, the first thing I did with this API was to whip up a quick Java program to interact with it. The code was not meant to be production-ready, and just sent requests to the server followed by sleeping a small amount of time. I’ll say it looked something like…

Yup! I’ve recreated the experience (well, in some browsers, on some resolutions) of my first experiment here. I’ll be going through examples of how to make it work.

Most of my day-to-day development is in Java, so I chose Java to implement my DDOS tool animation script in. I already had Eclipse running and it seemed like the quickest way to get something going. Plus, it’s dead simple to send a POST request in Java.

URL obj = new URL(url);
HttpURLConnection c = (HttpURLConnection) obj.openConnection();
c.setDoOutput(true);
c.setRequestMethod("POST");
c.setRequestProperty( "Content-Length", String.valueOf(array.length()));
OutputStream s = c.getOutputStream();
s.write(array.getBytes());
System.out.println(c.getResponseCode());

I’m sure there’s a Perl one-liner someone can write for this, or use some Python::Library::3/10 to do the same thing, but I don’t need to defend my language choices here!

As soon as I tried sending dummy requests, such as setting a pixel, and testing how fast I could send requests (quite quickly), I wanted to code up something quick. Nothing better than moving colors, right? I quickly set up a representation of the strip in memory and wrote some helper methods to continue sending the my state of the world in the right format. The glue is left as an exercise to the reader! (I’ve always wanted to say that. I think I’ll be saying this a lot more.)

final int max = 60;
int r[];
int g[];
int b[];
void clear() {
  for (int i = 0; i < max; i++) {     r[i] = 0;     g[i] = 0;     b[i] = 0;   } }

So now that I had a way to keep a state updated, I wanted to make something interesting happen. The simplest way to make something animate is to just update a position in a loop. This was quite easy to do, and I then had a red dot moving around on the light array.

int rPos = 0;
int rDir = 1;
while (true) {
  rPos += rDir;
  if (rPos <= 0) { rDir = 1; rPos = 0 }   else if (rPos >= max - 1) { rDir = -1; rPos = max - 1; }
  
  clear();
  r[rPos] = 255;
  send();
  Thread.sleep(50);
}

What's more impressive than one dot though? Well, you saw it earlier -- five splotches instead of dots! In order to get that effect, I just updated the positions right next to the ones that were tracked and set darker shades of the individual moving dots. So for the dot that was [255,0,0] (Red!), the lights right next to them were set to [128,0,0] (Dark red!), and one more point further were [64,0,0] (Very dark red!).

If you're interested in how this code actually worked, feel free to look at the JavaScript used to implement this page. I'll wait.

...

I will admit the code I actually used was more hard-coded than the JavaScript you looked at, and even this could have been made even better.

This is all the time I have for this now, but in the next part I'll walk through (and reimplement for your enjoyment) the next step of the animation!

The post-script: Do not try embedding arbitrary css and script tags into WordPress. It doesn't like that.

Well, then.

It’s mid-November, so the crunch of last-minute prep work is in full effect. Of course, that’s the perfect time to procrastinate by working on something I’ve been procrastinating on for too long.

This is my new personal site, for whatever I want to put here. I actually got permission to write this from my current job, so I can even share code snippets (that are from personal projects) It only took 5 months, too. Legal departments are awesome. (I’m not even kidding. If you’re a company with 50k employees, and your legal team can actually look at an individual request for blogging, well, that’s quite a lot of work.)

There’s a lot of parenthesizes in this post. I suppose my current work project trains me to use them all over the place. (Prolog-like languages!) (Or should that be ‘(! prolog-like languages)’?)