Virtual worlds – It’s how you use them

Virtual worlds – It’s how you use them

Virtual worlds..

They’ve been tried
They didn’t catch on
They will remain a niche

I don’t think so, but why haven’t they caught on yet?

The problem isn’t “cartoon class” visuals. Heck, there are iPhone and Android games that aren’t even 3d, let alone providing cinema class visuals. That hasn’t stopped them from becoming insanely popular among millions of people. People are willing to overlook visual fidelity when something is fun and engaging. Shoveling the same boring experiences with fresh graphics might help the situation for a while, but in the end, people still need reason to want to be inside a virtual environment.

The problem isn’t technical. Though there are a fair share of technical issues in the MMO/3d space, people are still willing to keep trying and keep coming back as long as the platform is fun and engaging. We should do our best to remove the technical hurdles, continue to fix problems, and try to provide a high quality product. But we must also realize that more importantly, the product must continue to offer new and compelling reasons for people to come back to really make an impact on the world.

In a long run of virtual world platforms, most companies have never really tried to answer the question “what can we use this for?”. Rather they’ve always left the actual activities of the world completely up to the users. This is great to a point, and we want to remain hands off as much as possible, but people also look to those running the virtual worlds for leadership and ideas. They want to know ways they can develop compelling environments that will bring in visitors. They want to show off the awesome stuff they’re building.

I think there has been too much hands off, and too little direction given to people to say “Hey, we have this really cool platform, and now we want to try this idea, will you help us?”

That is the direction we’re moving in now.

An example of this is InShape. This smartphone software combined with virtual worlds will allow people from all over the globe to start having fun during their boring exercise routines. We’re hooking your treadmill, elliptical, and exercise bike motions up to a virtual environment and making your avatar run and bike her way around long beautiful trails inside the InWorldz virtual world. On those really crappy snowy winter days when you cant even get out of the house, InShape will let you run along familiar beaches with your friends from all over the planet.

But what about the current residents and customers of InWorldz? What about the people in the virtual world that aren’t keen on exercising?

Perhaps this can be a motivator to get residents moving, but more importantly, they can still be a huge part of making InShape a success! We need people who are dreamers to create the best running and biking trails in any world. We need dreamers to create the fitness accessories that people are going to want to put on their avatars while they’re working out. We need dreamers to create exercise equipment that uses the InShape data to provide new and exciting experiences and virtual exercise equipment that hasn’t even been invented yet!

The more we utilize the virtual to enhance the real, the more that the power of virtual worlds becomes clear. I can’t wait to start attending regular exercises classes with all my real, and virtually real friends!

This is only the beginning. Let’s work hard to show people all the awesome things that can be done with virtual worlds!

See more on the InShape beta test forum.

Staying on the horse

Staying on the horse

Software development can be exciting. We learn new things. We get to explore new ideas and see them come to life.

Software allows us to share our talents with people from all over the world. We get to see the things we create  put to use sometimes in ways that we never considered.

But software isn’t all fun and games. Sometimes software development can be downright monotonous and annoying. For any project of sufficient size, we seem to start off excited, but then once we get far enough into it, it becomes work and takes a lot of willpower to want to continue. Time keeps ticking by, the project gets larger and larger. It gets more difficult to fit it all into your head, and development becomes “real”.

I was thinking about this today, and trying to enumerate all the times that I felt like I didn’t want to touch a particular project ever again. I came up with a few suggestions on preventing project burnout that I hope can be useful to some of you out there working long hours in software.

Change code that is causing repetitive typing

If you find yourself frequently having to type some kind of boilerplate code, or typing the same basic pattern of code over and over again, it’s time to take a look at a refactoring to remove the cause of your pain. Over time, this will sap your willpower to continue on the project since most of your time will be spent pounding out pages and pages of nothing but supporting structure, without getting any forward moving work done.

If refactoring doesn’t work for one reason or another, or the cause for the repetition is beyond the builtin power of your language to solve, try code generation. Use something like Cog to make your life easier and get back to actually making progress on your code instead of doing the boring work yourself.

Refactor confusing code

If you keep bumping into a chunk of code that is confusing or that you always have to think about before you can make changes, it might be time to refactor and come up with a simpler way of doing the task. For example, you might have a class where in each method callback you need to check the status of a connection or other object before proceeding. Over time when adding new methods eventually this is going to be forgotten introducing subtle bugs into your code. If you have to keep remembering things, find a way so that those memories are embedded in your code.

Encapsulate behaviors

If you have to remember to “do X” before each call to a certain library, see if you can encapsulate the doing of X into an easy to reuse chunk. For example, if you’re using a C library and you keep having to remember to do your own cleanups, use a unique_ptr with a custom deleter to create RAII objects. Just because a library didn’t come with an easier way to use it, doesn’t mean you shouldn’t build one.

Don’t just code. Write unit tests

If you’re not into test driven development, or are adverse to the extra coding that unit testing creates, you are missing out on an opportunity to pull yourself from “programmers writers block”. Completing and executing unit tests regularly while creating software  is a great way to pull yourself out of the code code code code cycle for a bit and creates a higher quality product in the end. It also will end up saving you debugging time.

I hope this post can help you to prevent coding burnout. Remember that if you’re starting to feel like you don’t want to work on a project, many times there is a problem causing it that you can take steps to resolve. Do your best to finish the projects that you start. Programming is more rewarding that way.

Code generation with cog

Code generation with cog

I was always taught that if you find yourself repeating the same basic code over and over again, even with minor variations, you’re probably not taking full advantage of the tools made available to you by your programming language of choice.

In many cases this is true. For example, in C++, you can use templates to eliminate a lot of copy/paste/minor change style code. C# has generics, and though they’re not as powerful as C++’s templates, they also can go a long way to limit the amount of code you have to write when it comes to dealing with objects that happen to share similar interfaces, or when you want to use an object regardless of its type in a similar manner.

An example of the power of C++’s templates can be found all over the web, and in C++ boost where they are used extensively. But even templates don’t solve all of the problems that may lead to copy and paste.

In C++, you can get a little bit further by utilizing the preprocessor, but compared to templates, it is arcane and easy to use improperly in ways that introduce subtle bugs into your code. There are even libraries available to help tame the preprocessor and make it more useful (see: boost.preprocessor )

I recently found when working on network software with new messages being added every few days that neither the preprocessor, nor templates prevented the code repetition that was being caused by handling new message types in similar, but slightly different ways. An example from the project is listed below:

void messageutil::switch_dispatch(message_context_ptr ctx)
        {
            switch (ctx->type)
            {
                case MT_ANSWER_CHALLENGE:
                    messageutil::template_dispatch(ctx, std::make_shared<AnswerChallengeMessage>());
                    break;

                case MT_AUTH_ACK:
                    messageutil::template_dispatch(ctx, std::make_shared<AuthAckMessage>());
                    break;

                case ...

Because the library I’m working with doesn’t support the visitor pattern, I have to create an identity based switch statement to extract the message type and create the messages based on their IDs. This creates a large switch statement and me having to write boilerplate code for every new message that is added.

I could’ve used preprocessor macros and/or templates to make the amount of typing slightly less, but it still wouldn’t eliminate the core problem, which is that I have to write SOMETHING for every new message type that gets created, even though I’m executing what is pretty much the same factory code over and over.

This brings me to the point of the article: cog. Cog is a library written by Ned Batchelder to generate code in a variety of different languages. The cog website where the basic operation is described can be found here.

The cog syntax is python, and in fact, you can use any library that you can use in python to assist you in code generation. Since I know that all the network messages that I’ll need to handled are first written as *.proto files, I realized I could use that as a basis to form the set of messages from the filenames.

The first example on the cog website looks like this:

// This is my C++ file.
/*[[[cog
import cog
fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
for fn in fnames:
    cog.outl("void %s();" % fn)
]]]*/
// ------> your generated code will end up here <------
//[[[end]]]

cog.outl() will write lines of text directly to your source file between the ]]]*/ and //[[[end]]] tags. After “cogging” the file, the cpp source will end up looking like this:

// This is my C++ file.
...
/*[[[cog
import cog
fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
for fn in fnames:
    cog.outl("void %s();" % fn)
]]]*/
void DoSomething();
void DoAnotherThing();
void DoLastThing();
//[[[end]]]

Let’s take a look at how we can apply this same technique to generate some message dispatching code for us! Below is an excerpt from my project:

/*[[[cog
def underscore(name):
   import re
   s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
   return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).upper()

# (fnames is the list of protobuf file names
# provided from other cog code above this)
for fn in fnames:
   rawname = os.path.splitext(os.path.basename(fn))[0]
   enumName = rawname
   if enumName.endswith('Message'):
       enumName = enumName[:-7]
   else:
       continue

   enumName = underscore(enumName)

   cog.outl("case MT_%s:" % enumName)
   cog.outl("    messageutil::template_dispatch(ctx, std::make_shared<%s>());" % rawname)
   cog.outl("    break;");
   cog.outl("");
]]]*/

What the heck are we doing here? Lets step through this.

First we define a function called underscore that takes the camel case file names and turns them into their equivalent capitalized underscore versions. Eg. MyGoodMessage becomes MY_GOOD_MESSAGE. We’ll use this later.

Then, we’re using a list of all the *.proto files in a specific directory called fnames and getting just the basename of the file which is the filename without path information. We then apply splitext which splits the filename into a list of [filename, extension] and take the [0]th element of that which is the filename without the extension. We then trim off the “Message” portion of the filename. Eg. AwesomeCoolMessage becomes AwesomeCool.

Then, before we start to output code, we apply our previously mentioned underscore function to the name. So enumName = AwesomeCoolMessage then AwesomeCool and finally AWESOME_COOL.

Now, we start outputting code directly into the cpp file:

cog.outl("case MT_%s:" % enumName)
#outputs: case MT_AWESOME_COOL: followed by a newline 

cog.outl("    messageutil::template_dispatch(ctx, std::make_shared<%s>());" % rawname)
#outputs: messageutil::template_dispatch(ctx, std::make_shared<AwesomeCoolMessage>()); then a newline

cog.outl("    break;");
cog.outl("");
#outputs: break; then a newline

When we put this together in the actual project with the messages that are currently defined, we get the following output:

case MT_ANSWER_CHALLENGE:
    messageutil::template_dispatch(ctx, std::make_shared<AnswerChallengeMessage>());
    break;

case MT_AUTH_ACK:
    messageutil::template_dispatch(ctx, std::make_shared<AuthAckMessage>());
    break;

case MT_CHALLENGE_RESPONSE:
    messageutil::template_dispatch(ctx, std::make_shared<ChallengeResponseMessage>());
    break;

case MT_GET_CHALLENGE:
    messageutil::template_dispatch(ctx, std::make_shared<GetChallengeMessage>());
    break;

You can see the cog code and output generation both embedded in the source file here.

Cog is awesome, and has already saved me a ton of time. Thanks a TON to Ned Batchelder for developing it!