Pages

Friday, December 14, 2012

Thoughts on Connecticut

I am always astounded, yet never surprised by the response to something like the elementary school shooting in Connecticut. People always try to place blame while simultaneously calling it a "senseless act". I am not surprised that people try to make sense of something that apparently has none--it's human. But we should know better.

Today I've been inundated with phrases like "what's this country coming to?" and it makes me wonder--what is this country coming to? If you look at the comments section of any major news site's story on this, you see liberals saying things to the effect of "You can blame the NRA for this shooting" and conservatives saying things like "This is why people need to carry guns to protect themselves"--this is not a political issue! Sure, I think Sarah Palin is an idiot, that Mitt Romney is a liar, and that the NRA are a bunch of loons--but that has little to do with the fact that an insane man made a conscious decision that killing children was the next best course of action in his life.

If we want to place blame, let's look at ourselves and our culture. We live in a society where you "suck it up", "pull yourself up by your own bootstraps", "grow a pair"--and ignore the suffering of the poor, homeless, old, sick, mentally handicapped, depressed, and unstable. We largely prefer to avoid interaction with others, not get involved, and worry about ourselves.

Our ego-maniacism has a price. And when these things happen, try to think about what you've done to help others lately. It's not about being a good American, it's about being a good human being.

Maybe, just maybe, if this guy didn't have access to guns some these children might be alive. Maybe he would've used a knife instead, who knows? But almost certainly, if someone had paid attention to the signs or if this guy had gotten the help he needed they would be.

Monday, April 9, 2012

Java System Calls

I'm in the final semester of my CS degree right now, and one of my last remaining requirements is an operating systems design course. As part of that course, I've been tasked with writing a system shell. However, whilst most of the students are writing their shells in C or C++, I decided to attempt to write mine in Java. Java is my most proficient language, but I thought it'd be an opportunity for me to learn how to write system specific code, whereas most of the time, I'm writing system independent code. I'd also never learned how to interface with a system library of system calls, and wasn't sure that everything would work. Turns out, they work just fine! Note that in the code below, not necessarily everything is fleshed out completely. The assignment is not yet due, and I'd rather not post a solution online. What you find below is simply how to interface with a C-library using Java and the JNA library.

An additional motivation for this post is that when you google "Java system call", most of the time you get instructions on how to execute a system command, not a system call. The difference is that the first gets the current Runtime environment (including a system shell) and uses that environment to execute a program, and the latter causes privileged kernel-level execution of some operating system provided functionality. The problem with writing a shell in this method is multi-fold--you get a false sense of success, because anything your shell is unable to accomplish, the underlying environment may accomplish for you without your knowing,there's no way to limit memory or cpu constraints, there's no way to define a custom Runtime environment, and many other issues.

The basic approach taken is that of any C or C++ POSIX compliant unix subsystem, namely:
  1. Import the local libc library, wherever it is on your system
  2. Run an infinite loop that accepts String input
  3. fork()
  4. If pid != 0, wait() on the pid, because you're the parent process
  5. If pid == 0, replace yourself using exec() based on the command input, because you're the child
  6. exit() when done
The specifics with JNA are pretty easy:

  1. Import JNA (as a jar or something) to your project
  2. Create an interface that will be the Java mapping to the native library (SystemLib below is the interface, declared within my Shell class)
  3. Create a public instance variable that loads the library you wish to
  4. Declare function prototypes that are Java mappings to the native functions (note my re-declarations of fork, execve, waitpid, wait, and _exit)
  5. Use them in subsequent code


import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

public class Shell {
    
    public Shell() {
    }
    
    // This will be the interface to the unix subsystem
    public interface SystemLib extends Library {
    
    // Declare our public static object to call system calls on
        SystemLib INSTANCE = (SystemLib) Native.loadLibrary((Platform.isMac() ? "/usr/lib/libc.dylib" : 
                                                            (Platform.isLinux() ? "/usr/lib/i386-linux-gnu/libc.a" : // Designed for linux mint 11
                                                            "")), SystemLib.class);
    
        // A Java mapping of the native API functions we wish to call
        int fork();
        int execve(String commandFilename, String[] args, String[] env);
        int waitpid(int pid, int status, int options);
        int wait(int status);
        void _exit(int status);
    }
    
    protected void run(Command c) throws IllegalArgumentException
    {        
        // Execute the java system command
        String command = c.getCommand();
        String[] args = c.getArgs();
        String[] env = c.getEnvironment().toStringArray();
        
        // Fork a new (child) process
        int pid = SystemLib.INSTANCE.fork();
        
        /********************************************
         * Child process enters right above this line
         ********************************************/
        
        // If the pid is 0, I'm the child
        if (pid == 0) {
            
            // command, args, and env are guaranteed to be with the child process
            
            // Replaces the current process (the child) with another program
            SystemLib.INSTANCE.execve(c.getCommand(), c.getArgs(), c.getEnvironment().toStringArray());
            
            // We shouldn't actually reach here, if we do, that's bad.
            SystemLib.INSTANCE._exit(-1);
        }
                
        // A pid of -1 is returned when running the command has failed
        else if (pid == -1)
            throw new IllegalArgumentException("Command \""+c.getCommand()+"\" failed.");
        
        // Occurs if I am the parent process
        else {

            // The parent process should wait for the child
            int childPid = SystemLib.INSTANCE.wait(0);
                        
            return;
        }
    }

Thursday, December 1, 2011

Game Programming Design Patterns - Factory

Motivation:

I've found through doing some technical phone interviews, a lot of companies seek employees with "strong cs fundamentals". I'm not entirely sure what this means, but I know what kind of questions they ask--Oftentimes it's "write a function that implements quicksort" or "write a binary search tree delete". These can oftentimes be tough questions, especially if it's been some years since you've done those things. To me, what's more important is quality design and implementation of patterns. While quicksort and BST delete are important, they're oftentimes implemented in basic language/system libraries. It seems to me that the only way to build better/more complex algorithms is to know what the fundamental algorithms are, but more importantly, know how to use and build *on top* of them.

So, because I consider design perhaps a more valuable and rare skill, I'm going to begin a series of posts that examine (at an extremely high level) the idea of some basic design patterns in game programming. 
Note: I suggest this book for good explanations of most basic design patterns. I also don't claim to be an expert, so feel free to correct me, and I'll try to update/fix my explanations as necessary.

First: The Factory Design Pattern

The Factory Pattern is a pretty basic pattern. It's when you abstract out a complex object's creation into a class method that generates members of that class. Take for example, the following pseudo-code from my game Total Toads (working title):
class Bug ...
class BugFalling implements Bug ...
class BugFirefly implements Bug ...
class BugMultiply implements Bug ...

In my game, you have frogs at the bottom who want to eat bugs who appear on screen in various ways. Each bug has a distinct look, and even bugs of the same type can have different properties. For example, some BugFalling are static and don't move, some are tutorial bugs, some move quickly, some don't animate, etc. Rather than having complicated and convoluted initialization processes, I can abstract these special properties out into my factory class, which I shall call "BugFactory". The header of BugFactory, given the desired types of bugs I just mentioned, might start to look like this:


// BugFactory creates bugs for specific uses
class BugFactory 
{
  // BugFalling creation functions
  static BugFalling bugFallingStatic();
  static BugFalling bugFallingTutorial();
  static BugFalling bugFallingAtSpeed(float speed);
  static BugFalling bugFallingDontAnimate();

  // Other bugs types might go below...
}


Notice that the BugFactory currently has 4 class methods that return an object of type BugFalling. Whereas before I had to create complicated constructor functions in the BugFalling class, now I have factored that out to having a single constructor, with additional configuration of the object done in the BugFactory. Now we examine one of the BugFactory functions, bugFallingStatic();

static BugFalling bugFallingStatic()
{
  BugFalling bug = new BugFalling();
  bug.speed = 0; // assume speed is a variable that controls the bug's fall
  return bug;
}


As you can see, this is a pretty basic function with a pretty basic purpose. You might imagine that in a more complex game with more complex objects, object creation can get a little crazy. Using a factory allows you to have a singular place in which to examine and modify your object creation. You can also imagine that extending BugFactory to create BugFirefly and BugMultiply objects would not be a huge endeavor (in fact, you should do this). And since they are similar objects (implementing the parent object type, Bug), having a factory makes it convenient and easy to modify their specific creation processes while making complex object instantiation just as easy and convenient.

Tuesday, November 29, 2011

Converting CSV to SQL

So, I came across the need to convert a csv file to MySQL statements for insertion into a database. Looking around the web, I saw a number of paid tools that did some complicated and expensive functions. Instead of buying any of those things, I decided to sit down and pump this out in a couple of hours (maybe even less). Check out the github link below for a download.

https://github.com/rocity/CSV2SQL/

There's two main issues with converting a csv file to sql statements. The first is, what's the name of the database? Second, what's the name of the table? So, to solve these, the script will ask you what the names of the database and tables are. This was a capability that seemed to be lacking in other script I found. Many of the other scripts were also overly complicated. I endeavored to make it simple as possible.

Enjoy!

Friday, September 30, 2011

On Initiative

Throughout my short life, I've had the opportunity to experience some pretty incredible things, and meet some pretty incredible people. Sometimes, people ask me how I've come to meet such interesting people and attend such interesting events, and it really just boils down to one thing: Initiative.

Initiative is a powerful force that drives virtually everything one does. I hate to be one of those people who says, "in the dictionary, blah blah blah" buuuuttt, in the dictionary, initiative is defined as "the power or opportunity to act or take charge before others do." But a word's definition is merely what it is, not necessarily what it means. I'd like to look at what that definition means.

First of all, there's the "power" to act. Wanting something bad enough that you'll take action in order to create for yourself is more than half the battle. It takes ambition. Watch this video if you are unsure about how much you want to be successful. The power to act is the absolute foundation of accomplishing anything--you need to want it and be willing to sacrifice and work hard in order to achieve your goals.

Then, there's the "opportunity" to act. Sometimes, opportunity knocks on your door. Sometimes, it knocks your door down, and sometimes, you wonder if you have a door for opportunity to knock on. Opportunity is a product of work and luck. You need to earn opportunity just like how you earn anything. You need to work hard, think ahead, strategize, have goals, make decisions, and have the strength of will to keep going.

"Take charge". No one is going to be responsible for you or for your ideas or for your successes or for your failures. You have to take charge--this is related to having the power to act. You need to have the power to act, and then you need to have the willingness to act responsibility for whatever happens, that's what taking charge means.

Acting "before others do" is, in my humble opinion, not absolutely necessary. It is interesting to do something no one has done before, but not necessary. Do you think Angry Birds was the first game that did physics based level destruction? Hell no, but perhaps they did it better than anyone else before them. Taking action before others will oftentimes give you a head start, but doing something better than anyone ever has before can be equally rewarding. It's not shameful to be inspired, but it is shameful to steal, so talk about the inspiration for your ideas.

Initiative has driven me to this point in my life...soon to be college graduate, student researcher at NASA, and founding partner in a game company. These aren't my only defining features, but they are the most obvious product of my taking the initiative. If you want to make games, do it. If you want to be a potato farmer, do it. Whatever it is you want to do, do it. The only real mistake you can make is to do nothing.

Tuesday, September 20, 2011

Design Patterns In Game Programming

Preface
Before we start, you should know that the definitive book on design patterns is Design Patterns: Elements of Reusable Object-Oriented Software. My disclaimer is that I am but a student of Computer Science...don't take my word as the end-all be-all. This article (like many of my articles) will be but a scratch upon the surface of this subject. That being said...let us move on.

Motivation
This is a topic I've been struggling with myself. We know that in object oriented programming, design patterns are tried and true solutions to problems we encounter. However, we usually don't employ design patterns to solve problems, we employ them usually without knowing it or because it seems like a good idea and we were taught to do it. This might be ok because it helps us avoid problems, but it simultaneously masks the problems we're (unknowingly) avoiding and makes it difficult to understand why the pattern exists, or why we would choose one pattern over another.

What a Design Pattern Is
Design patterns are generalized solutions to generalized problems that occur with some modicum of frequency when you're creating software using the object oriented programming paradigm.

Why Use Design Patterns
The most basic and condescending answer is: because these solutions have existed for a relatively long time and many experts have used them, they're likely better than any solution you could come up with on your own. And even if you did come up with a solution on your own, it's likely already a design pattern in some way. Knowledge of contextually pertinent design patterns helps you to make good architecture and design decisions.

Common Game Programming Patterns
  • Singleton - You create objects that ensure that only a single instance of which can exist at a time. In my game Total Toads, this is the design pattern used because it was easiest to fit with cocos2d's design. For example, in cocos2d, there's a Singleton CCDirector, CCSpriteFrameCache, etc. It seems this is an often-used panacea in game programming. Though the general consensus seems to be that it isn't a panacea so much as it is a cancer because it actually masks poorly designed architecture. You should probably avoid using this design pattern if you can because there's likely a better way to design the architecture of your game. This can avoid the problem of having multiple instances of objects of which there should only be one, like a "Player" object in a single player game.
  • Factory - You create an object whose purpose it is to create other objects. For example, you can have a factory class called "GameObjectFactory" with static (possibly parameterized) methods to create other game objects like a "Player", "Enemy", "Gun", or "Bullet". The latter classes might have complex constructions that make obtaining a instance of that specific class difficult. The factory can take care of the object's complex configuration (adding to an object pool, adding to physics engine, etc) and simply return a reference to the created object. This pattern helps you avoid the problem of complex object instantiation by keeping these complex configurations in a single place, rather than scattered around in your code.
  • Observer - The object in question maintains a list of other objects that are interested in its state and notifies these listening objects of a change in its state. In Total Toads, we have 3 Frog objects and 3 FrogAnimation objects that can control the animation of the frogs based on their state. In this case, the FrogAnimation objects are observers of the Frog objects. Every time the state variable for a Frog changes, it notifies the associated FrogAnimation object to notice the new state and take an action if necessary (like animating the frog). This pattern helps you avoid the problem of event notification in your game. Since games are user-interaction driven, objects can change state at almost any time. When an object changes state oftentimes that object needs to be animated or have other objects change their state with respect to the new state.
  • State - You have an abstract (empty implementation) class that has subclasses to define the current state. An example of this might be a first person shooter that has a "Player" class who has several possible states like "PlayerInCombat", "PlayerOutOfCombat", and "PlayerInMenu". When the state is changed, the player shall be represented as an instance of the appropriate state class. When the player starts to be shot at, the player object "switches" to an instance of the PlayerInCombat class to take advantage of that class's implementation of the mouse's left button click which makes the player able to shoot their gun. Similarly for the "PlayerOutOfCombat" and "PlayerInMenu" classes, where the mouse might allow usage of items or the clicking of menu options, respectively. This pattern helps you avoid monolithic methods that perform differently based on the object's state by having a bunch of switch or if/elses in your code. Instead, the object just changes and runs its appropriate code. This also simplifies your code and allows you to more easily find problems in your objects behavior since the state is right in the object's class name.
Thoughts
I don't pretend to be an expert game programmer...I'm nowhere even close to one, my first game hasn't even hit the market yet! However, this subject seems to not be extremely well represented or explained on the internet...and I would love an expert book on this specific subject. There's many more patterns than the ones I explained here, and you can find ok explanations in my below references.


References



Monday, September 19, 2011

Book Review - Learn iPhone and iPad Cocos2d Game Development, by Steffen Itterheim

Disclosure Statement/Supporting Story: I *was not* supplied a free evaluation copy of Steffen Itterheim's book. I initially purchased this book through Google Books, but it was DRM bound to adobe's reading software, which was unable to index or search the document for text. I was unhappy with this and emailed Steffen directly asking for a DRM free PDF of the book equivalent to the one being sold by the publisher. I emailed him my receipt and he emailed me back a DRM free PDF of the book. It's hard for me not to support an author who clearly supports his product as much as Steffen does. In any case, find my brief review of the book below:


What to expect

  • Great explanation of cocos2d classes and usage
  • Great examples of working game code, you'll even make a couple of games using this book
  • Clear and perhaps even more importantly, concise explanation of code and concepts
  • Some programming knowledge is required, but you could consider this a beginner's book
  • Explanations as to *why* you do things the way you just did
  • Some professional tips and tricks that are very helpful in making a game (performance considerations, memory usage, etc)
  • A great deal of material
  • Some basic instructions on game center, ad hoc deployment, provisioning, and certificate generation (Apple development account stuff)

What to NOT expect

  • Explanation of technical game design in general
  • Explanation of objective c or the cocoa libraries
  • Explanation of game programming paradigms
  • A book for absolute beginners 
  • Anything related to artwork (with the exception of how to maximize performance and memory usage, as it pertains to artwork)
  • Extremely detailed instructions on deploying your game to the app store
  • Instructions on registering company accounts with Apple


My take
Overall, this was probably one of the best game engine programming books I've ever read. The example games were interesting and relatively non-trivial. The information was generally not fluff--reading the book thoroughly is a must because there's a lot of advice given in the text that will help you with the engine later on. For example, in my game Total Toads, our particle effects were performing extremely poorly. I referred back to this book and immediately figured out from the particle effects section that it was because our particle textures were way larger than they needed to be! This book is definitely a keeper if you plan to make cocos2d games, I refer to it frequently! I'd definitely recommend purchasing this book if you have little to no knowledge of game engine programming, but do have some knowledge of programming in general (in objective-c). Knowledge of the Cocoa libraries are not needed for this book. I would've liked to see more information on generic game programming (i.e. common design patterns and techniques), but this book should be more than sufficient to teach you everything you need to know to make a simple first game. All you need to do is supply a good idea and some hard work.

Monday, September 12, 2011

On Cocos2D Particle Systems

Designing the System of Particles
Particle Designer makes prototyping easier!
It's difficult to talk about the designing of a particle system because there's a lot of parts to it. But I suppose if you break it down, you can see two distinct parts -- 1. How the particles behave and 2. How the particles look. To get both of these things right will require significant trial and error. There's a couple tools to make your life easier, though. You can use Particle Designer to create your system of particles. The main thing to keep in mind while designing your particle system is to keep the particle count low as you possibly can while maintaining the look of the system you desire. Also, play around with things like particle size to see if you can achieve the same system design with fewer particles. To texture the particles, you can use SVG-edit, GIMP (best imho), or really any graphics package to determine how your particles look.

Texturing Your Particles
Using your graphics package, create a texture that will represent your particles. The largest sized texture you can create is 64x64. However, the size of the texture for your particles greatly influences the performance of the particle system, so try to make the texture as small as you can (5x5, 10x10) while still having the particle look as you'd like.

Putting Your Particles In-Game
This is the easiest part of them all. Using cocos2d for iOS, code similar to the below code would get you a working particle system
CCParticleSystemQuad *system = [CCParticleSystemQuad particleWithFile:@"SystemCreatedWithParticleDesigner.plist"];
[YourCCNode addChild:system];

Important Points
  • Keep particle system total particle counts low as possible
  • Keep particle textures as small as possible
  • Use tools if you can, creating the right system by code alone can be tedious

Sunday, September 11, 2011

Create a .CAF Sound Effect

Hello there! Quick tutorial on how to convert a wav file to a caf file. Note: The caf file extension is the same as the aiff file extension. If you have an aiff file, you can simply change the extension to caf. Otherwise:
This keeps file sizes small and quality good enough

  1. Record your sound to a wav file using Audacity or the pre-installed version of Quicktime Player (File->New Audio Recording).
  2. Start up Max and configure out sound formats  (Max->Preferences->Formats). Click the plus sign to add CAF. For my encoder settings I use Linear PCM, 16-bit big-endian signed integer. This keeps file sizes relatively low and sound quality is still probably better than you actually need. Don't forget to click the checkbox next to the CAF encoder setting you just created. 
  3. Convert your sound effect from a wav to a caf using Max (File->Convert Files). It will use the configured output sound format you just created.
  4. The converted files are located in the "Music" folder of your User directory (~/Music).
  5. Do what you wish with them!

Saturday, September 10, 2011

Frequently Asked Questions

These are a few questions I oftentimes get when I'm gaming or when I'm in a coffee shop working.


What does Rocity mean?
You'll probably be sorry you asked...I'm going to try to explain this the geekiest way I can. I once used a hostname naming scheme where the hostnames were generated from words m/at([a-z]+)/ where the hostname was the captured group. So "rocious", "rocity", "ramedes" (WoW reference), and "rophy" were all valid hostnames. Rocity was the coolest sounding word to make a gaming handle out of. So, I chose Rocity as my internet handle.

How do I get started programming for iOS?
I'd recommend a couple of books to get started. First, learn how to program for Macs using this book. Then start learning how to program for iOS using this book. I once took a class that was taught by Apple employees for Apple employees, and these are the books they recommended. I don't have any affiliation with those authors though.


How do I get started with game programming?
You should probably know how to program generally already, but not necessarily in the required language for your target device. iOS is a very easy platform to get started with because of great engines  like cocos2d and kobold2d, but XNA also has great tools if you're comfortable with C++. If I had to choose though, I'd get started with kobold2d. The creator of this suite (Steffen Itterheim, no affiliation) has made some easy to use tools that allow you to more easily manage the more arcane aspects of xcode projects. In addition, Steffen has written a great book on creating games with cocos2d. I guess the most important thing I can impart to you is: There's no way to get around the reading. You will need to buy books, you will need to read them, you will need to understand them, at least at some level. I'm considering writing a concept tutorial on this question relevant to iOS programming, because I know when I was starting out there weren't great answers to this question and I would like to try and create one.