Pages

Saturday, October 26, 2013

Creating a pixel font for your game

I recently sunk about two full days into using FontForge to develop my own custom pixelated font. Most font tutorials weren't designed for pixelated fonts, so there was a bit of a learning curve. I thought I'd post a tutorial outlining what I'd learned, both for posterity and for myself when I inevitably forget all of this in a month or two.

My font currently looks like this:


You'll notice that I've replaced a lot of the latin-1 character set with standard RPG symbols like swords, shields and potions. You may have also noticed that the & symbol is a heart. An advantage to making your own font is the freedom to add whatever symbols your game requires.

In this tutorial, you'll learn how to create a font, how font sizing works, how to draw glyphs by outline, and how to use the bitmap strike editor to draw your font pixel-by-pixel. I'll then cover two options for converting bitmap strikes to outlines so that they'll be rendered correctly by other applications, with a custom shell script I wrote for this purpose that will trick FontForge into tracing pixelated outlines of your bitmaps for you. Note that this tutorial is not so much about how to design the appearance of the font, but in the mechanical aspects of creating a TrueType font that can be rendered by standard text libraries.

We'll be using FontForge, a free font editor that's quite powerful and easy enough to use once you get the hang of it. Note that I'm doing this on a Linux system; FontForge works on Windows and OS X, but some of the minor details might be different, so you'll have to figure those bits out yourself.

After you install and start FontForge, you have two choices: either use an existing font as a starting point, or create everything from scratch. To create a new empty font, choose File > New - this gives you freedom at the expense of making things a bit more difficult. To use an existing font, just open it with File > Open.


Font Sizes

One thing you need to understand right off the bat is how the final pixel size of your font will be calculated. Knowing this will allow you to get everything pixel-perfect from the beginning.

The size, in pixels, of a character in your font is given by this formula:

    pixel width = (glyph width / em size) * font size

The glyph width is set on a character-by-character basis by choosing Metrics > Set Width from the menu. The em size is a font-wide property. You can change the em size by choosing Element > Font Info from the menu, clicking on the General tab, and changing the value in the box, which by default is 1000. (Strangely enough, if your em size is not a power of 2, FontForge will complain, so by default it's going to complain about the em size! You can safely ignore these warnings - you probably don't want an em size that's a power of two, unless the pixel resolution of your characters is also.)

If your goal is just to turn an existing pixel font into a fixed width font, it's pretty easy: select all the glyphs you're going to use or use Edit > Select > Glyphs Worth Outputting, Metrics > Set Width to the maximum width, and Metrics > Center in Width to center them all.

Getting the size right from the start is important. If your pixel font ends up being a non-integer number of pixels across, you'll have spacing issues. As an example, I was originally using a maximum glyph width of 400 but left the em size at 1000. With a font size of 24, 400/1000 * 24 = 9.6 pixels. This resulted in uneven spacing until I corrected the em size.

You have a couple of decisions to make from the offset: the resolution in pixels of your font, how many points you'll use in FontForge per pixel, and whether the font will be fixed width or not. There's no special setting for fixed width - to make a fixed width font, you just set the width of each character to the same value.

My example font is designed to be a maximum of 10x10 pixels. I decided to make capital letters, punctuation, and numbers fixed width, but lower case letters variable width (this lets me have nicely aligned menu screens that use all capital letters, but saves space when displaying other text.) The font I used as a starting point was using roughly 40 points per pixel. So, my em size is 10x40 = 400. When the font is finished, I'll use it at multiples of 10 points (the same as the number of pixels) so that everything is an integer: if a glyph is the full 400 points, it will span 400/400*10=10 pixels; a 6 pixel glyph would take up 40*6=240 points for 240/400*10=6 pixels, etc.


Editing Font Outlines

From the onset, if you're starting with a blank font, all of the glyphs will have red X's in them. To create a new glyph, first set its width by clicking on it and selecting Metrics > Set Width. To demonstrate, we'll create the capital letter I. Since my capital letters are fixed width, I'll set the glyph to have the maximum width, which is my defined em size, 400.

After setting the width, double click on the empty I box to bring up the outline editor.




You can mouse over the tool icons to find out what they do. We'll use the rectangle tool to draw a simple outline of the letter I:



This is definitely not pixel perfect right now. Click on individual points or edges and you can see their exact point coordinates in the upper left corner of the window; you can use the arrow keys to adjust them one pont at a time until everything is a perfect multiple of 40. Choosing Element > Overlap > Remove Overlap from the menu will merge the overlapping rectangles into a single shape.

The letter I is not particularly challenging, which is why I chose it. Letters like Q, R, S and W are going to be incredibly tedious to draw using rectangles and manipulating things point by point.

"There has to be a better way," you may be thinking. Well, there is - sort of.


Bitmap Strikes

A "bitmap strike" is a bitmap version of your font at a specific point size. It allows you to draw, pixel by pixel, exactly what your character should look like at a given size.

Choose Element > Bitmap Strikes Available from the menu and the bitmap strikes window will pop up - add the desired font size to the "pixel sizes" list (in our case, 10.) Make sure the "create rasterized glyphs" box is checked and press OK. Now, choose View > 10 pixel bitmap to leave the outline view and see your new bitmap glyphs. Double click on any of them to bring up the bitmap editor:



The green outlines are the rectangles I just drew, but you can also see a 10x10 grid. I can click on individual grid cells to fill or erase them. This makes drawing individual glyphs much easier, as it's similar to how you would draw them in GIMP or Photoshop or Paint.

Now, here's the catch - programs don't always seem to respect these bitmap strikes. For one, Adobe Flash doesn't seem to. In order to ensure that your font displays properly, you really should have outlines for all of your characters. So, after drawing glyphs in the bitmap strike editor, we need to convert them into outlines.

Save your font as a TTF by choosing File > Generate Fonts. Now, import the font into itself. Choose File > Import, find your font, check the "import as background" box, and press OK. Your glyphs now have a background image generated from the bitmap glyphs you created earlier. This background image doesn't do anything on its own - it's just there to help.

We have two options here. First: you can use the rectangle tool to trace this background image. This is a bit easier than trying to create the glyphs freehand in the outline editor.

The second is more automatic but also a bit more involved to set up.


Autotrace

FontForge supports "autotracing" vectors from bitmaps, which is a feature we'll be abusing. You'll need the Autotrace or Potrace tools installed (refer to FontForge documentation.) When editing an outline, if you have either of these tools installed, you'll see the menu option Edit > Autotrace. Click on it and it will create an outline from the background bitmap image.

You'll notice, however, that the new outline isn't pixelated! Autotrace and Potrace aren't designed to trace pixels, they're designed to smooth them away, which is not what we want. To fix this problem, we'll need to trick FontForge.

I'm using Potrace for autotracing. When FontForge calls Potrace, it runs an executable called potrace on my system path with a set of arguments. This means I can trick FontForge into calling a custom executable by renaming potrace to potrace-bin and creating a new executable shell script at /usr/bin/potrace.

The script will look like this. What it does is first magnify the background image passed in by 10 times, then trace the resulting magnified image. This means that what previously was a pixel is now a 10x10 square of pixels, and potrace won't smooth these over.

Now when I use Edit > Autotrace, this script is called. Voila!

We're not quite finished, though. Ideally, my script would also scale the resulting outline down to 1/10th of the size, but I wasn't able to figure out how to do this - so you'll need to do it yourself. Choose Element > Transformations > Transform from the menu. Choose "Scale Evenly" and enter 10%, then set the origin to "Glyph Origin."

Okay, so that was a bit involved. The good thing is that you only have to do all of this once. Draw all of your bitmap strikes, save your font and import it as a background, select each glyph you want to create an outline for, Autotrace, and Transform. FontForge will apply these same operations to every glyph, and you'll have a new set of pixelated glyph outlines. Save your font and load it into your game!

If you're on Linux or OS X, this should work. If you're on Windows, I can't help you, but hopefully you could use a similar strategy with msysgit or cygwin.


Conclusion

To wrap up: it is absolutely feasible to create a pixelated font for your game. Expect to spend a few hours getting used to FontForge's interface and drawing the glyphs; if you're able to use a Linux or OS X machine to do the design, the shell script I've written should save you a lot of time generating pixelated outlines.

Hope this helped! Leave any questions in the comments and I'll do my best to answer them.


Comments on Reddit

Saturday, October 12, 2013

Pixel art tutorial: making a logo for your retro game in GIMP

Edit: thanks to everyone who (politely) pointed out the error in the title - this isn't "pixel art" per se, as pixels aren't being deliberately placed. It's a way to make a logo that fits in with a pixelated graphical style.

Today I thought I'd post a simple guide to creating a logo for your pixelated game. We'll be designing a logo for a fictitious game titled "Science Quest" - an RPG where you play a resourceful life sciences grad student attempting to secure grant money in an uncertain funding climate. We'll be using GIMP, the GNU Image Manipulation Program, which is a free and powerful alternative to Photoshop.

Now, I don't consider myself a fantastic pixel artist - I think what I do is passable, and maybe ~1/2 of the current art for Last Legend will make it into the final game, with the rest being redone by someone with more talent. But my lack of artistic talent has forced me to find simple artistic workflows that can generate passable programmer art quickly.

With that in mind, let's get started!

First, we need to pick a resolution. This won't be difficult as there are likely already some resolution constraints set by the game. For example, if the game will be a 640x480 Flash app with a scaling factor of 3 for jaggieness, that gives us 640/3 = about 213 pixels to work with. Since there will be margins, and for simplicity, let's just round down to a width of 200 pixels. The logo will be wider than it is tall, so I'll go with 200x150 - that should give me plenty of space to work with.

We'll create the image in GIMP, using a transparent background:




The next step is to decide on a font to base our logo on (yes, spoiler alert - the easiest way to generate text is to render it from an existing font, not draw it yourself one pixel at a time.) We want to find a "sciencey" font for this logo, which can be a bit subjective. An easy way to get a sample of what fonts are on your system would be to open a word processor, write "Science Quest," and try some out. You may also have a font browsing and editing tool on your system, but this is by no means required. I decided to go with "Old Standard TT Bold" for this - it looks like something from an old scientific manuscript.

Using the Text tool in GIMP, click and drag to make a rectangle that spans the width of the image, and type "Science Quest". Adjust the font size until the logo fits the exact width of the image. Don't worry about the height as much - remember that it was our width that was constrained. Finally, uncheck the box in the tool options that says "antialiasing" - you want things to look a little jaggy at this point.




Since smaller font sizes didn't look so great, I decided to put "Science" and "Quest" on different lines.

Completely removing anti-aliasing doesn't always look great, so at this point a little pixel-by-pixel touchup may be necessary. Use your best judgment and the Pencil and Eraser tools to smooth the edges of your letters and eliminate any stray pixels. For Pencil (keyboard shortcut N) and Eraser (keyboard shortcut Shift+E), set the size to 1 to work with individual pixels; for the eraser, check the box that says "hard edge" so that pixels are erased completely.


If you look closely, you can see that I've done some very minor cleanup and thickened some lines, notably on the c's and e's.

The logo is a little flat and uninteresting. To add a little depth, we can add a drop shadow. Make a new layer, copy your logo, and paste it into the new layer. Select the Bucket Fill tool (shortcut Shift+B), check the box that says "fill whole selection", change the color to grey, and click on the logo to fill it grey. Using the Move tool (shortcut M), move the layer exactly one pixel down and to the right (don't try to do this with the mouse - you can move one pixel at a time using the arrow keys.)




We can add even more depth by coloring the logo with a gradient. I'm going to color the words "Science" and "Quest" individually with a white-to-light-grey gradient. Switch to the layer containing the black logo text and click the "Lock Alpha" button directly above the list of layers - this will prevent us from coloring outside the lines. Using the Rectangle Select tool (shortcut R), select a rectangle containing the word "Science." Then select a foreground and background color and use the Blend tool to fill the word from top to bottom. Click on the top of the tallest letter, drag a line down to the bottom, and release. If you hold CTRL while dragging the mouse, you can constrain the gradient to a perfect vertical line. Do the same for the word "Quest" - for mine, I'm reversing the direction of the gradient.




Now, the perfect, smooth gradient makes this look a little less retro. We can remedy this by decreasing the numer of colors used with Posterize. In the Menu, select Colors > Posterize, and choose a number of levels that you think looks good.




Finally, we'll throw in some special effects. I added a Gradient Flare (Filters > Gradient Flare) to the drop shadow layer, and posterized the result with 12 levels to get a nice lighting effect that looks like it's from the SNES era (reduce the number of levels if you want to further limit the palette):





And voila! On a black background and scaled up x3, here's our completed logo:




Feel free to get a little more creative - throw in a beaker, use different colors, fonts, or lighting effects, etc. There are a million and one ways I could've done this, and with GIMP it's easy to quickly create a few different prototypes and pass them around to friends to see which version they like best.

Well, that's it for now. Hope you found this helpful, and feel free to ask any questions in the comments or via e-mail.


Comments on Reddit.

Saturday, October 5, 2013

Introducing Last Legend

The project I'm working on right now is an online, old-school RPG called Last Legend. I'm planning a series of posts on the concept, the technical aspects, etc. - this post is about the idea, where it came from, and the road to getting to its current conception.

The "t" is a sword. Not the most original thing you're going to see today.

Last Legend has existed in some form for a little over a year, as I've been playing around with the concept and trying to get it just right. The idea is to recreate the feeling of the classic Final Fantasy series (i.e. 1-6) and turn it into something that can be played with your friends. (The name Last Legend, if you didn't catch it, is a thinly-veiled reference to Final Fantasy.) These were my favorite games growing up. Some remakes have featured a half-assed multiplayer mode where player 2 can control certain characters, but only during battle. If these games had been remade with a proper multiplayer mode I would've loved them, thus the inspiration for Last Legend.

The idea behind Last Legend dates back to July of 2012. While working full time over the summer, I decided to try to create an online RPG for National Game Development Month in my "spare time." Needless to say, I bit off a little more than I could chew, but I did in fact have a playable client/server demo by the end of the month that could be played over a local network. You could fight, gain experience, raise your skills, and die. You could attack anyone, including other players or NPCs, but if you attacked a non-enemy you'd be marked as a criminal - this meant that you'd be killed on sight by guards, and other players could attack you without penalty. Upon your death, the mark would be removed. An early bug removed the mark a little too early in the death process, resulting in the guard that killed you getting a mark himself. The guards would turn on him, and the one who delivered the final blow would get a mark himself. Thus an eternal battle of guards would commence. You could even join in yourself for some sweet XP - just don't make any killing blows.

The game was originally written in Python. Because my time was limited, I saved time designing the UI by combining wxPython and PyGame in the same application - a feat that proved difficult and was rife with platform inconsistencies. For networking, I threw in Twisted. Any Python programmers out there will note that all three (wxPython, PyGame, and Twisted) have their own main loops and want to "own" the entire application. Getting them to play nicely together was not an easy task. (If you're wondering, it was wxPython that was the neediest of the three, so its main loop won out - I would run that and call the update functions of Twisted and Pygame manually.)

PyGame on the top left, wxPython surrounding it, and Twisted behind the scenes. Don't try this at home! (I also can't recommend throwing a bunch of town guards into the sea, but when you're a level 100 ogre, you can pretty much do what you want.)

Eventually, I had issues getting everything to work properly on Windows (I develop on Linux) and was hitting up against a maximum framerate of about 20 FPS so I decided to scrap the wxPython portions and rewrite them using PyGame. This led to a focus on simpler gameplay, with streamlined stats and skills and a simple, more retro-style interface:

Goddamn spiders with their goddamn poison damage.

The original game was also a bandwidth hog and really only feasible to play over a local network. After the elimination of wxPython, I did some major rewrites of the networking portions, implementing my own TCP protocol to transfer data between players and the server to try to minimize the amount of bandwidth required to play. The same protocol exists in the current version of the game, which I'll go into more detail about later.

A few things about the game still just didn't feel right. One was the battle system - right click on an enemy, and your character will approach them and start attacking; press a number to change the type of attack you're using or use special abilities, and then just watch the charge-up/attack cycle typical of so many similar RPGs to play out. It felt like a simplified modern RPG and didn't evoke the classics I was trying to emulate. The class and stat/ability system also felt too complex and out of place. Finally, the smoothing algorithm I used (2xsai, which you can see in the previous two screenshots) and other graphical tricks that weren't possible in the SNES days, while cool in isolation, detracted from the nostalgic feeling I was trying to capture. The more I thought about these problems, the more I realized that in order to be true to my original vision, a fairly substantial rewrite of the game mechanics was going to be necessary.

Additionally, although I fought admirably, I ran up against some insurmountable problems using Python. Performance was one issue - the game ran just fine as long as everything was stored in memory. As soon as I tried to back up the game state to a permanent store like a database or the hard drive while the game was running, everything slowed to a crawl. I also knew that in the end I'd face the difficult prospect of packaging the application. While solutions like py2exe, py2app, etc. are great, they're trivially easy to decompose into actual Python source code if you know what you're doing, and for an online game, I thought this was too much of a security concern to accept. I am working on a project that aims to build a Python interpreter that can be statically linked against with custom builtin-packages and contributed to another that tries to bring PyGame to the browser via Java (ha), but I don't know how successful these will be or how long they will take, and didn't want these experiments to hold up the game.

With that in mind, and with many fundamental changes to make, I decided to move development to Haxe, the language I'm using now. One big benefit is its focus on cross-platform functionality from a single code base. There will be a flash client, lowering the bar for interested players to try the game out. I also love the performance of compiled Haxe code, the relative ease of writing code in the language (it's like AS3 plus a bunch of modern features that AS3 lacks like typedefs, enums, generics, comprehensions...), and the accessibility of the Haxe developers and developers of major libraries. I love Python and PyGame, but for my purposes it feels like a major step up.

The current game, running in the browser on Flash. The code for both the client and server are written in Haxe.

I plan on also releasing the code for the Python version - both the PyGame-only rewrite, as well as the old wxPython UI code - under an open source license. I'm waiting until the game is completed and released so that I can make sure there's nothing sensitive in the old codebase that could cause problems for the new if it was to get out. If anyone out there is interested in using PyGame and Twisted to create a (probably simple) multiplayer game, I hope you'll find it useful.

Hello, world! (Starting a gamedev blog)

Hi there! My name is Ben Morris, and I'm a graduate student in Biology, a developer, and a hobbyist indie game developer.

I began programming as a kid. The thing that drew me to programming was and has always been making my own games. I've been developing games since I could type at about age 7. I started out making modifications to the iconic Nibbles and Gorillas QBasic programs that came with DOS, trying to change the Nibbles snakes to lizards and the gorillas in Gorillas to dinosaurs. As a kid, I ran a popular online Pokemon "sim" (a very 90's term, a web-based game involving finding and battling Pokemon) and developed some Pokemon fighting games in QBasic and Visual Basic. Most of the games I created in the old Basic days never saw the light of day beyond my room, school, and my local circle of friends. (By the way, if you ever played Charmander's Lost Forest back in the 90's, give me a shout! I bet I can still remember your username.)

My coding chops have come a long way since - I have a B.S. now in computational biology and am working on a PhD that involves computational data analysis and synthesis. I use about a dozen languages with some level of proficiency. In my spare time, I continue to develop games. A few years ago, I released my first game professionally (Summoner on Android - related blog post on my personal blog) on the Android market. While the game is fun and brought in some nice "take the wife out to dinner" money, it wasn't something I could quit my day job over (and to be fair, that was never the goal.) I learned a lot from the release process, and realize that if I had put a little more time and effort into the game before and after release, particularly into the social aspects of developing a game and building up a community, I could've seen more success, possibly a lot more. I have a couple other projects currently in progress.

With that in mind, I'm starting a new development blog where I'm going to post updates and technical overviews of my current projects. I used to post intermittently about game development on my personal blog, but now I'm reserving that for more academia- or life-related posts and am creating this blog exclusively for game dev content.

Thanks for reading, and stay tuned! I'd like to generate content that the readers, either indie developers or indie game enthusiasts, will enjoy. Please shoot me an e-mail at ben [at] bendmorris.com if you'd like to chat or have any suggestions or questions - I'd genuinely love to hear from you.