Controversial Press Releases: How Ubisoft Won and How the Games Industry Lost

Today Ubisoft released the box cover art for FarCry 4. Usually just the cover art isn’t all that interesting and serves as just a picture to go with the announcement. But this one was different. Here, take a look:

far-cry-4-cover-art-high

Yup. It’s all kinds of wrong. And that’s what they were going for.

A simple announcement of “FarCry 4 coming out in 2014” is not all that interesting, the fans might see it and take note. But to get everyone’s attention you have to do something different. And to do that you need to create controversy. Every game twitter personality and game news site is talking about it. Ubisoft’s strategy is working out great; this is one piece of brilliant marketing.

They are stooping to a low, immoral, and racist level here. But maybe they is what they have to do to get noticed? I have seen this before, I see it all the time with games and especially indie games (not necessarily racist though). How do you get the media’s attention when there are hundreds of other games competing for the same spotlight?

Having a normal game name doesn’t cut it anymore, and having just a good solid game doesn’t either. In order for your game to make it on one of the game news sites you need to create a “story”, something that stands out and creates buzz, drama. If you look around on the many indie game blogs and tutorial sites that talk about PR and marketing they all say that to get noticed you have to do something to stand out from the crowd. Talk about the story behind the game, not just the game itself. Did you end up homeless developing the game? Get fired from your job? Get cloned? All of these are great stories that the media will report on. And apparently so is having a racist box cover.

 

So Who do We Blame?

I think there are a few parties we can swing the blame stick at. First are the companies, in this case Ubisoft, for creating the controversial press releases. They could have taken a different route to get noticed that wouldn’t have offended anyone. But with millions of dollars invested in a game can they take the risk of maybe getting noticed and maybe not? Same goes with indie game developers. You spend years making a game, making no money, all to maybe have it seen by a few hundred or thousand people? It’s tough, there’s a lot of risk involved. You want to ensure you have invested your time and money well and often that means you need to generate some zany headlines.

The next party we can blame is the game industry as a whole. There are just so many games out there that competition is heavy. Game quality, polish, and finding your niche is really required to succeed. It is easy to make games nowadays, there are lots of platforms to release on and it is easy to release on them, and everyone wants to make a game. Game developers hear the success stories and want to get in on the money-making action. This is flooding the market.

Finally, I have to place the largest blame on the game media: those of you that report on these stories. When it comes to game exposure on the web and in social media the buck stops with you. If you don’t report on these controversial, racist, and immoral press releases, people won’t see them and if people don’t see them then that media campaign was a bust and the company will hopefully try a new, more appropriate, strategy. What do you do if your kid is throwing a tantrum for attention? You ignore them and don’t reinforce the behaviour.

Right now the game media has walked right into Ubisoft’s trap. The cover box has generated so much controversy, and not just for the art but also for what the story could be about: is there going to be deep political or social narrative? The mystery! The hype! I hate to say it but this is brilliant and successful marketing.

Now not talking about the issue is easier said than done. As a news site you need to get people to read your material, and drama behind the game itself attracts attention. People love drama. Pop magazines, tabloids, reality TV shows, all have no content and subsist off of drama because it pays the bills. If you don’t report on the racist cover box other sites will and then you will miss out on those precious page views! You don’t want to be the only one not talking about it, so you write an article, you tweet, Ubisoft gets hundreds of thousands of eyes on their new game and they win in the end.

I’m not saying that the media should sit idly by and let companies get away with racist/homophobic/immoral press releases. The companies should be reprimanded but not publicly. Reply to their PR representative and explain that their press release is inappropriate and for those reasons you will not post their story.

Ubisoft dropped the bait and you bit. The hook is set and they landed a mother-load of page views. They will come back again with the same bait and the process will repeat. Only until someone decides to not give them attention publicly will this cycle end. Maybe then we can have a more mature and inclusive game industry.

Java 8: Awesome Changes for Game Developers

Java8, releasing March 18 2014, has several great changes to it. One in particular has me interested from the aspect of game development and AI, and that is Lambda expressions.

A common structure in games is an event system. Register an entity or agent to listen to certain events and then respond to them. For example:

eventSystem.registerEventListener(“buildingDestroyed”, listeningEntityID, new EventListener() {
    public void onEvent() {
        System.out.println(“Run away!”); // respond to event here
    }
});
eventSystem.broadcastEvent(“buildingDestroyed”, buildingID);

Here we have an Event System that lets listeners register to particular events and a way to broadcast events to those listeners. In this example there is a “buildingDestroyed” event that is registered by an entity with the ID ‘listeningEntityID’. It’s response to the event is an anonymous inner class, with a single method: onEvent. There is handles the event.

This has been the way Java has handled single-method classes for a long time now (what is known as a Functional Interface). It’s a bit clunky, you end up with another interface class floating around, and there is extra code you just don’t use. There’s just nothing elegant about it.

To overcome this limitation I have extracted a lot of code out to Groovy where I can use Closures to clean it up. But I don’t always want to go into Groovy and set up bindings to the scripts and classes. Luckily Java 8 is giving us Lambda Expressions to clean all of this up.

Here’s what the above listener implementation would look like:

EventListener listener = () -> System.out.println(“Run away!”);
eventSystem.registerEventListener(“buildingDestroyed”, listeningEntityID, listener);

If there is only one line in the lambda, then you can use the expression as I have above, but if you want a more complex response you can surround it with braces like so:

EventListener listener = () -> {
    System.out.println(“Run away!”);
    System.out.println(“Find a place to hide”);
}

Lets tighten it up a little more and inline the whole expression:

eventSystem.registerEventListener(“buildingDestroyed”, listeningEntityID, () -> System.out.println(“Run away!”) );

That’s much shorter and cleaner.

Now we still need our EventListener interface. The implementation of EventSystem.registerEventListener needs to know what parameters it is accepting and it shouldn’t care that is might get a lambda expression. It will look like this:

interface EventSystem {
    void registerEventListener(String eventName, int entityId, EventListener listener);
}

 

Scoping in Lambda expressions

So what variables do you have access to in a lambda expression? Well they are kind of like closures in that sense: you get access to variables outside your immediate lexical scope.

Example:

class Bob {

    private String name = “Bob”;

    public void setupEvents(EventSystem eventSystem) {
        eventSystem.registerEventListener(“buildingDestroyed”, listeningEntityID,  () ->
        System.out.println(name+“ is running away from a destroyed building!”) );
    }
}

 

This would output:

Bob is running away from a destroyed building!

 

Other Uses in Games

Finite state machines are very common in game AI. You want an agent to perform tasks, and to control when it performs those tasks you need to have some method of organization, usually via states. Finite state machines allow an agent to switch between one state to another, say from gather logs to chop firewood.

Usually you would have a State class that has a perform() or update() method that is called every frame. Each state class would have its own implementation of what is is supposed to do. So for the GatherLogsState it would send the agent to a tree and then chop it down; when completed, move to the ChopFirewoodState . The ChopFirewoodState would require that there already be some wood in its possession and would then proceed to chop that wood. When done it would switch to the GatherLogsState.

Defining classes for each state can be a pain and pollute your scripts folder, especially if you are using slightly different different actions for a state that are small to begin with. It can be much cleaner and easier to supply the state’s update() action as a lambda expression:

interface State {
    void update();
}

interface Agent {
    void init();
    void update();
}

class FirewoodAgent implements Agent {

    private State currentState;

    private State gatherLogs = () -> {
        findTree();
        chopTree();
        pickUpLogs();
        currentState = chopFirewoodState; // switch states
    }

    private State chopFirewoodState = () -> {
        pickUpAxe();
        chopLogs();
        currentState = gatherLogs; // switch states
    }

    public void init() {
        currentState = gatherLogs;
    }

    public void update()  {
        currentState.update();
    }
}

That is a gross simplification, but you get the idea.

Method References

Another great feature related to lambda expressions in Java 8 is Method References. Here we can reuse existing code in our classes as a lambda expression; no need to write the code again if we don’t have to.

Say we have a Tree class that describes the type of wood it is composed of. That wood has a moisture level that is more desirable depending on what it is used for. We also define an Axe class that converts a Tree into Logs, where Log also has a moisture rating. We use a TreeFinder interface that picks the best log for the Axe to chop. This interface will have several implementations, each one passed to Axe depending on what is wanted. Finally we have an old TreeUtility class for finding the correct tree for the job at hand. It contains some tree finding code.

class Tree {
    public String name;
    public int moistureLevel;
}

/**
* Find the best tree.
*/
interface TreeFinder {
    Tree find(Collection<Tree> trees);
}

class Log {
    public int moisture;
}

/**
* Converts trees into wood.
*/
class Axe {

    public static Log chop(TreeFinder treeFinder, Collection<Tree> trees) {
        Tree bestTree = treeFinder.find(trees);
        Log log = new Log();
        log.moisture = tree.moistureLevel;
        return log;
    }
}

/**
* Some static utility methods to find the perfect tree for the job.
*/
static class TreeUtility {

    public static Tree getMoistestTree(Collection<Tree> trees) {

        Tree moistestTree = null;
        int moistest = 0;

        for (Tree t : trees) {
            if (moistestTree == null || t.moistureLevel > moistest) {
                moistestTree = t;
                moistest = t.moistureLevel;
            }
        }
        return moistestTree;
    }

    public static Tree getDriestTree(Collection<Tree> trees) {

        Tree driestTree = null;
        int driest= 0;

        for (Tree t : trees) {
            if (dryestTree == null || t.moistureLevel < driest) {
                driestTree = t;
                driest= t.moistureLevel;
            }
        }
        return driestTree;
    }

}

We want to use the Axe to chop trees and produce Logs. The Axe’s chop() method uses the TreeFinder to pick the best tree. Normally we would create separate subclasses of TreeFinder to pick what tree we want and pass them to the chop() method. But since there is a utility class laying around that does that for us, TreeUtility, we can use its code instead.

To do that we use a Method Reference:

Collection<Tree> allTrees = GameWorld.findAllTrees(); // made up utility method
TreeFinder dryTree = TreeUtility::getDryestTree;
TreeFinder wetTree = TreeUtility::getMoistestTree;
Axe.chop(dryTree, allTrees);

This works because, as we can see, the signature of the getDryestTree() and getMoistestTree() methods match the signature of TreeFinder.find(). The code will be substituted in and the correct tree will be found. In this example we are want to chop dry trees.

Conclusion

The way to think about Lambda expressions is “code as data”. Instead of passing around primitive data types and objects as parameters you are new passing around code chunks.

Some care must be taken when architecting your code in this way. In many applications it would just confuse the whole codebase and fragment the logic leaving you wondering “why is it doing this weird thing here in just the one case, and where in the code is it doing this?” Games by nature allow for this fragmented code. Game objects usually have their own implementation of an action or response to an event, especially for AI. So it will feel natural to use lambda expressions throughout your entities and agents.

Method references are a little tricky and I’m not sure how robust they are to refactoring. It was a bit tricky to think up a use-case example for this blog post, but I’m sure there’s a better one out there that applies well to games.

I hope you will be excited to upgrade to Java8 and give these a try! It should make your game development more enjoyable.

Please note that I have not compiled these code examples! Take them as pseudo code.

Conferences: The Good, the Bad, and the ‘Are they worth it’

Game Conferences

Conference and expos are a great place to showcase your game and get feedback. They can, however, be a bit pricey and for an indie developer you might only be able to afford one a year if you’re lucky. So how do you choose the best one and how do you prepare so you can get the most out of it? I will try and explain all that here.

I’ve been to a few conferences now, both as an attendee and as an exhibitor and I have learned quite a lot from them. I will only talk about exhibiting at a conference, not being an attendee.

Exhibiting Costs

The first thing you need to decide when considering getting a booth at a conference is will it be worth your time and money. Booths range from $200 to $2000+ and depend on size and placement on the expo floor. That’s the first main cost. The second cost is travel and expenses. These almost always add up to more than the booth cost, especially when you have several people traveling. Equipment, signage, and handouts are another cost, but are usually less.

I calculated how much it would cost 2 people to travel from Victoria BC and exhibit at the PAX Prime conference in Seattle. Victoria is very close to Seattle, just a ferry ride away. For two people it is around $200; that’s pretty cheap. For conference materials I wanted a few posters and a bunch of handouts: another $300. Equipment would be a TV and cables, I would bring my computer: another $700. Hotel would be $1000 for 5 nights for 2 people. Food another $40 per person per day. Assuming a booth cost of $1500 that is a total of $4100. It really adds up.

But it is totally worth it! Right? Well in a way it is, but probably not how you think. I decided against showing Attack of the Gelatinous Blob at PAX, partially because I couldn’t get into the Indie Mega Booth (they supply equipment and more exhibitor passes), and partially because of the cost of renting a booth myself. But the main deciding factor was what I wanted to get out of the conference, and that wasn’t necessarily to show off the game.

I ended up helping out Dejobaan and Radial Games at their booth. It was a good chance to view the conference from the other side: the exhibitor. But the biggest benefit was meeting the other developers, media, and networking. When it came down to it, networking was what I needed to do more than to show off the game.

During a conference every exhibitor is busy beyond belief. They don’t have time to wander around and try out your game. So your best chance to really talk to them and show them your project is to go to the nighttime events and parties.

If you do decide to get a booth, I highly recommend having 3 people per day to take shifts watching the booth. A multi-day event will exhaust you and you must have relief. Just taking you and one other person will ruin your experience and possibly make you too tired to go to any of the networking events.

But what about showing off a game? While I was volunteering at the booth I kept a count in my head of how many people tried the game we were showing (Monster Loves You). There were 2 tablets with the game on them available at all times, and sometimes 3. From 9am to 5pm I counted 60 to 80 people tried the game each day. Over the 4 days that’s about 300 people. That seems like a lot until you factor in the cost of the conference. I was only going to bring one computer to demo the game, so I would at most have only been able to show it to 150 people the entire weekend. Dividing the cost of the trip by that number of people, it would have cost me $27 per person to show it to them. Since I plan to sell the game for around $15, I better hope that each person would buy 2 copies of the game right there on the spot! But no one sells their games there. They might try to recoup costs by selling merchandise or swag, but it won’t cover the trip costs. More people walk by and look at the game and don’t try it. For those you must have cards or flyers to give them so they can remember your game. The amount of walk-bys amounts to many, many more than those who tried the game and unfortunately I did not keep count of that.

The Benefit of a Conference

So there has to be a benefit to exhibiting or else no one would do it. And that benefit is networking and the media.

When you go to a conference, especially a major one, you must arrange ahead of time scheduled meetings with as many media as possible that will be attending the conference. They will write a story and then thousands to tens of thousands will see your game. Not just the few attendees that walk by and try it out. When you break the conference costs down by including media exposure, a booth makes much more sense.

As I’ve said, networking is huge. The indie game community is incredibly friendly and helpful: they want to see everyone succeed. Talking to them could give you good advice and create friendships that will benefit you and your company. Developers and media will now know you by your name and face. You are a person then and they will respond to your emails and write an article about you.

 

What Conference is Right For You?

Hopefully by now you get what I am saying: “conference are for networking and media exposure”. Yea there is a bit of brand awareness, but that can disappear quickly in the noise of the hundreds of booths at a conference. So what conference should you attend? Travel distance is a huge factor in cost. But if travel cost doesn’t affect your budget much you still need to look at if the money is being well spent.

I recently attended a much smaller conference than PAX. While PAX Prime had over 80,000 attendees, this one only had 3000. It was local however, so travel was nearly free. The booth was free as well as it was hosted by the local IGDA chapter, LevelUp Victoria. My costs were nothing so I cannot complain. But other people’s costs were not free: they paid for booths and set up all weekend. A small booth was about $300.

The conference wasn’t entirely focused on video games and the expo hall was the smallest part of what was being exhibited. There was Warhammer, board games, RPGs, and a LAN party as well there. Throughout the day we had very few people visit the booth. Over the 2.5 days I would say less than 100 people walked by and looked at the games. And I only counted 4 people play Attack of the Gelatinous Blob for the half a day it was shown. With that few of people the only thing to get from them was live play-testing (which is awesome and rare to get).

Not many attendees, players, or walkbys. But that is okay, that’s not what conferences are for! Media and networking is what you want so how did that stack up? Well, there was a media event, but only 10-15 media outlets. And the media event was focused on the conference itself not the individual booths or games being demonstrated. It was also mostly local new outlets reporting so their target audience is probably not the gaming community.

Throughout the event only one media person came by. More might have, it was hard to tell because their passes weren’t noticeably different from a general admission pass. At PAX the media have a bright yellow badge so you can pick them out and start talking to them. The whole time we were waiting for media to show up, do some interviews, and see some stories posted. But that just didn’t happen.

At least during the huge downtime between the occasional person walking by we could network a bit.

So what did I take from this experience? Small conferences not solely focused on videogames are probably not a good venue nor worth the money of setting up a booth. Without individual media exposure there is no point in my opinion. You get some play-testers and can network a bit. From talking to the other developers they said it was a bit of a letdown or “not the right venue.” To be fair the conference is growing, it doubled in size this year, but I think it needs to get much larger to make it worthwhile renting a booth there.

This applies to other conferences as well. Are people there to see new games? Are the media excited about it and will you get a chance to do an interview and get a story posted? Are there after-parties where you can network? Take all of that into consideration when planning your next conference.

What are your thoughts or experiences?

Preparing a Kickstarter Campaign

We just launched a Kickstarter project as you may or may not already know. A lot of thought went into why decided to go this route and not another. Basically it boiled down to if the funding was successful, development could continue at full-time pace instead of dropping to part time. This will have a dramatic effect on the release date. But that’s not what this post is about.

This post is about what we have done to prepare for the launch with some tips, links, and wisdom that could be useful to you too.

 

Page Preparation

People say that it takes much more time than expected to prepare for a Kickstarter campaign. Maybe they are delusional or just inexperienced in creating and delivering projects in general. This is my first Kickstarter and I knew it would take at least two weeks of full time work to get ready. And it did. It is a lot of work.

A great place to start is to read this Reddit post from LobsterSundew.

LobsterSundew covers every aspect, when to launch, what rewards you should have, everything. If you haven’t read it, stop now and read it!

Creating the goals took the most amount of time. I went over them multiple times, scrapped a bunch, down-scoped, and removed rewards, added new ones. The best way to settle on them is to get feedback from friends and other Kickstarters

The graphics for a Kickstarter page make it look more professional. These also take a while to do. Save them till the end after all your goals and content have been decided. It’s not fun to redo the graphic titles.

I only spent about two days on the video. One day to make a demo of it, and another day to record the actual one. I did so many takes I can make a blooper reel from it. One thing I learned is to just leave the camera running, and try again. Don’t stop recording, delete, and try again. That takes just too long, is frustrating, and erodes your confidence.

One of the best sources of feedback I received was from the Kickstarter LIVE! panel at PAX Prime 2013. It was hosted by Cindy Au, of Kickstarter, and contained several illustrious and experienced panelists: Max Tempkin from Cards Against Humanity, Jordan Weisman of Shadowrun Returns, and Luke Crane from Kickstarter. They got a chance to see the campaign and give feedback. Critical and useful feedback that I highly treasure and implemented into the campaign. I was lucky to have this opportunity, but most people won’t be. All I can suggest is to get your preview page (yes there is one when you are creating a project) in front of as many people as possible.

Rewards

Can backers get a copy of your game of just $10? People like to spend $10, give them something good. Add $5 and get your name in the credits; that makes it easy for them to give just a little more. Rewards like that are easy. Physical rewards are not.

We stayed away from all physical rewards because they can be a nightmare to deliver. It is also the most vocal feedback successful Kickstarters give: “do not have physical rewards if you don’t have to!”

There’s a lot that is overlooked with them. The manufacturer might not deliver the items in time, or they might not even deliver them! Some items will be flawed, and you need to send them back and order more. All of this adds to the cost of the reward. Shipping as well is a pain and very time consuming. Some good advice given, by I believe it was Max Temkin of Cards Against Humanity, was to mail the product to yourself first. With the packaging, the packing material, going to the post office, and seeing if it arrived to you still in good condition. Now think about doing that 300 more times to your backers! Doesn’t sound good now does it?

Also, with physical rewards you have to subtract the cost of them, the damaged ones, and the shipping. This is money taken right away from what the pledge; that $50 pledge just turned into $20, less than the lower tier you have. So please think about physical rewards. They cost a lot of money and a lot of your time.

Don’t have your reward system too complicated. Keep it to about 6 or less if you can. And cover the range of rewards under $100. People can always pay you $10,000 if they want, there is no fixed donation amount. And if you have one of those massive $10,00 tiers then the reward will no doubt be something you regret having to deliver. I thought of offering a fishing trip for one day. But the logistics of it would be incredibly difficult, would cost about $400, and the time to do it would take away from development of the game.

Everyone is an expert

I don’t mean this in a bad way, to the contrary. People who have run Kickstarter campaigns are experts on it and can give you some great feedback. But every campaign is different. Did they reach their goal in 48 hours, or was it down to the last 48 hours?

It can all be useful information, but take what you think fits with you. If they see something that you are doing that they did and it didn’t work out, take that advice! But if you find yourself going back and forth on decisions based on different feedback, you might have to tune that part out for the time being.

Listen to Your Friends

They have your best interest at heart, and are hopefully honest. Tell them you want critical feedback and thank them for it. I am lucky to have a great group of friends who were invaluable to the creation of this campaign.

Friends also keep you motivated and your spirits up when it feels like it is becoming too difficult to manage or if you are encountering imposter syndrome.

 

Pre-launch Prep

You have to be ready for this. Get the contact information ahead of time for all websites you want to contact. This takes several days and is exhausting. Keep the info in a spreadsheet, record who you have contacted, when, and if they followed up and if there is a link there.

Be social. You should already have a Twitter and Facebook set up.

Have a web page. Here you want to link to your trailer, Kickstarter page, and if at all possible, the demo.

You do not get the link to your Kickstarter project until you hit the ‘Launch’ button. So you will be in a mad rush to contact media and friends when it does go live. Prepare your press releases ahead of time. Different ones too: casual for friends, ones for gaming sites, ones for other media. Make it easy for yourself to copy the press release, personalize it a bit, and hit send.

And have a press kit set up ahead of time. The media will want to know what your company is about, even if it is just you. I recommend http://dopresskit.com/.

Have a demo of your game ready! People love to see that you have something, anything. It gives them confidence. And they will understand that it is still in development, don’t worry about harsh criticism. It also helps to have a link back to your kickstarter page in the main menu of your demo. People might tweet or email their friends the demo but not your kickstarter so make sure everyone can reach it.

Launch Countdown

It definitely helps to let friends and followers know each day a few days before launch that you are having a Kickstarter campaign. A single tweet saying “we launched” can be missed very easily. Be vocal about it, talk about it a couple times each day.

 

Launch!

Pick a good day. Not during E3 or PAX. Not a Friday. And not during Apple’s surprise iPhone 5s announcement, thanks Apple.

Just make sure you do launch. You can only delay so long. Unless you are building up a huge community before hand, there is no perfect time. Hit that button when you feel ready and go.

 

Good luck!

Voronoi in Games

In Attack of the Gelatinous Blob I recently came across the problem where I needed the human AI to build checkpoints, guard stations, and other defensive positions in appropriate places; but where should they go and how can I calculate that? Obviously I want them in densely populated areas and not in the wilderness, I also want them in as many places as possible so the player can’t flank the locations with blobs.

I remembered back to senior year in university studying computational geometry, in particular a routine to calculate distance relationships between points. If I used houses and building as points of interest, then I can find out what ones are closest, and from that I can determine the dense areas. In that class we covered Voronoi diagrams (and their inverse: Delaunay Triangulations) that do just that. Here’s a picture to demonstrate:

Delaunay_Voronoi

(Black lines are the Voronoi)

The red lines between the points are the center lines, and the Delaunay Triangulation shows the lines between points perpendicular to the Voronoi lines, like so:

Delaunay_Triangulation

With this information I can find out the smallest triangles and these areas will be the most densely populated areas that the humans should place defensive structures.

Back in my first job, in fact the 2nd project in my first job, I had to create a Voronoi diagram generator to calculate the center-line of lakes and river polygons for some GIS technologies. That was years ago, and although the code was open source, the company that we contracted too took it and ripped out our names and hid the source. Bummer. I didn’t want to write it again. So I searched for another Java solution to it, and voila, found one: The Delaunay Applet by Paul Chew. This app does everything I need and more. Along with Voronoi Polygons and Delaunay Triangulations, it also can generate circles from the circumcenter of the triangulation. These circumcenter points are the exact place where I need to place defensive structures and the circle radius tells me how dense that location is. Sweet!

Here’s a quick look at the code.

Triangle initialTriangle = new Triangle(new Point(-2000, -1000), new Point(2000, -1000), new Point(0, 3000));

Triangulation dt = new Triangulation(initialTriangle);

for (Vector3f buildingLocation : all.keySet()) {

// for each human house or building

dt.delaunayPlace(new Point(buildingLocation.x, buildingLocation.z)); // place point

}

// all done adding points, now lets find the smallest circles

for (Triangle triangle : dt) {

Point c = triangle.getCircumcenter();

float radius = (float) c.subtract(triangle.get(0)).magnitude();

// test to see if it is a small radius

// place a defensive structure there

}

Pretty darn easy!

Here is the code in action in AotGB:

voronoi-circles

The red circles are the dense areas.

The code is open source and free to use; no particular license to it. I highly recommend trying it out. And if you aren’t using java, port it over. It will be much easier than writing your own Fortune’s sweep-line algorithm, trust me 😉

Creating a Tech Tree

The next task for Attack of the Gelatinous Blob for me was to create a research tech tree. This would allow the player to upgrade units and unlock other ones. It seemed simple enough: each research item had one or more children, I would simply draw the tree of children and be done. Turns out it isn’t so easy. First off, you want the tree to look good. You don’t want overlaps or large gaps, and you definitely don’t want it to waste too much space on the small realestate of of the screen.

TreeGraphView-Figure7

It became apparent pretty quickly that is was a difficult problem and that someone must have solved it by now. And of course they have! I won’t go into detail about the algorithm here, the page describes it well enough; code and everything.

What I will talk about is how I implemented it. Or more specifically, how I found an open source Java implementation.

 

Welcome to Tree Layout by abego

The Java open source community saves the day again. This library is compact, easy to use, and saved me at least a day implementing my own version. It has the very flexible New BSD License and doesn’t force you to change your data structures in order to use it. Your code stays intact and unmolested by a 3rd party library.

So how do you use it?

First, download the jar file and add it to your class path.

Next you need to give it a means to find children of a particular node, and those children’s parent. This is done by implementing the TreeForTreeLayout interface, however there is a convenience class already there for you called AbstractTreeForTreeLayout and with it you only have to implement two methods:

public MyNodeClass getParent(MyNodeClass n);
public List<MyNodeClass> getChildrenList(MyNodeClassn);

My research objects each know what children they have, and who their parent is. So it was really easy to implement. If you don’t already have a tree structure for your objects, TreeLayout provides ones for you.

With the tree structure complete, and TreeLayout now knows how to access nodes and their relationship with each other, it is time to configure how the tree will look. In particular how large each node will be. Not all nodes have to be the same size, and quite often with a tech tree in a game they won’t be.

treeLayout-example

To achieve this customization you create one more class that implements the NodeExtentProvider interface. This interface has two simple methods:

public double getWidth(MyNodeClass tn);
public double getHeight(MyNodeClass tn);

 For my research nodes the layout size was simple: they have a fixed size. So for each one I just returned 70 (representing 70 pixels).

Finally, you have to configure the gaps between the rows and the nodes, what way you want the tree to face, and node alignment. You can use the DefaultConfiguration class to do this. The direction of the tree is quite important for your layout, and TreeLayout will provide you with 4 options:

treeLayout-directions

Here is what my code for building the tree looked like in the end:

private TreeLayout buildTree(GuiUnitResearchComponent a) {
        ResearchGraphTree tree = new ResearchGraphTree(a, es);
        ResearchNodeExtentProvider extentProvider = new ResearchNodeExtentProvider();
        Configuration config = new DefaultConfiguration(50, 10, Configuration.Location.Bottom, Configuration.AlignmentInLevel.TowardsRoot);
        TreeLayout layout = new TreeLayout(tree, extentProvider, config);
        return layout;
    }

With that code there we have a tree that is built, balanced, and usable. So what do we do next?

Draw Your Tree

With the tree built, you now need to draw your actual elements on the screen. It is first a good idea to confirm what your tree looks like by using the TreeLayout.dumpTree() method. This allows you to verify the parent-child relationships. Next you will want to get the bounds of every node in the tree, as well as the overall bounds of the whole tree.

layout.dumpTree(System.out);
Rectangle wholeTreeBounds = layout.getBounds().getBounds();
Map<GuiUnitResearchComponent,Rectangle2D> nodeBounds = layout.getNodeBounds();

That code is pretty self explanatory. What I end up with in the end there is a map of each node and where it should be positioned. The Rectangle2D class is very convenient with its center (x,y), minX/Y, maxX/Y values and this makes drawing the research boxes a cinch.

The harder part was drawing the lines in between each node. Not an impossible task: find the center point of the parent node and draw a line directly from it to the center of each child node. Or do what I did and instead of using direct lines, use a right-angle stepped line system (there is probably a real name for that). Here is a picture of my end result:

tree-ss

So there you have it. A pretty, balanced, tech tree that took no effort at all to build. I highly recommend you use TreeLayout if you are using Java, and if you aren’t using Java, take a look at the code and port it over. It will be worth it.

 

Ahh! My Groovy Script is Slow

Attack of the Gelatinous Blob uses Groovy scripts for all entities, level configuration, and pretty much most game features. It provides an easy and forgiving way to implement features and reuse them. I’ve also built the game so you can change a script for an entity while the game is running and see the changes in the entity immediately. This has been hugely beneficial.

But that is not what this post is about. This post is about performance when it comes to Groovy scripts and in particular, when loading and compiling them.

I started the investigation into script loading times when I noticed the levels for AotGB were taking longer to load than expected. Especially when many of the same entity were loaded, the time would grow linearly when it shouldn’t have since jMonkeyEngine’s asset manager caches models: once you load it, a clone is returned very quickly. The time to load a level with roughly 400 objects and 600k triangles, texture maps no larger than 1024×1024 took around 17 seconds. This was much too slow to be tolerable.

I had a suspicion that the slowdown was in the Groovy scripts. But just to make sure (as any good programmer should do) I ran the profiler to pin down the time-sink. Sure enough, it was the scripts.

To load the scripts I was doing a little caching: the script files themselves were loaded and cached off of the disk so they could be retrieved from memory quickly. However the compiled script was not being cached. The profiler pointed right to this spot: compile times. These were quite slow and were being repeated for the same script over and over again. That had to change.

I had see the Groovy Script Engine before: an embedded script manager that comes bundled with Groovy. It handles caching for you and checks if a file has changed, and will re-compile the script for you if it has. Great! This exactly what I want. So I slotted it in and ran some loading tests.

Loading times went from 17 seconds to 40 seconds! What happened there? I double-checked if it was running and configured correctly, it was. Some google searching quickly revealed the problem with the Groovy Script Engine, as can be found in this (http://groovy.329449.n5.nabble.com/GroovyScriptEngine-maximizing-performance-td339751.html) discussion. The issue is that it tries to make sure all dependencies are always up to date and that the files haven’t changed.

The script file checking is nice, but I do not really need it since it is only used during development and I enter the script through the groovy console whenever I change it. So that feature can go. All I really want is the pre-compiled script.

The solution I took for this was to just cache it myself. A simple HashMap of the script name and the compiled class.

private Map<String,Script> scriptCache = new HashMap<String,Script>();
...
Script script = getScript(codeKey.getName());
if (script == null) {
    Class<Script> clazz = (Class<Script>) parseClass();
    script = clazz.newInstance();
    cacheScript(codeKey.getName(), script);
}

script.setBinding(binding);
return script.run();

I implemented this and tested it. Load times went from 17 seconds for no caching and 40 seconds using Groovy Script Engine down to 7 seconds! Okay that is much better. The load times are reasonable now.

groovyPerf-chart

There are some things you can do to speed up the Groovy Script Engine, however my solution only took a couple minutes to implement and test, and it will be extremely easy to maintain. So I think I will be sticking with it.

 


			

The Entity System

If you missed my post about Entity Systems on IndieDB, don’t fear! I am posting it here for your reading enjoyment:

An Entity System (ES) is another way of managing all of your entities in a game, specifically how to organize their attributes (speed, damage, hit points, goopiness, etc…). Attack of the Gelatinous Blob uses an ES and in this post I will go into detail how an ES works and the benefits of using one.

What it Replaces

Commonly games will use a hierarchy of Actor classes, where each subclass adds new attributes to that entity/actor. Picture a top-level parent class called Actor, it has some basic attributes such as health, movementSpeed, and attackDamage. Then there is a subclass of actor called Human, where it adds to the attributes: jumpHeight, carriesWeapon, and carryWeight. Now lets say there is another subclass of Actor called Tank; it adds the attributes: armor, and carriesWeapon. Both the Human and Tank can carry weapons, and thus can both attack.

Next we create a child of Human called Blob. We want to subclass Human so we get the carriesWeapon and carryWeight attributes. But a Blob cannot jump! Ug, ok so we can have each class include a check of canJump(), no biggy. Next we add a 4th actor called ArmoredRobot. It has armor, carries a weapon, and can jump. So it could subclass Tank, but it can also carry weight and jump; should it subclass Human then? Either Human or Tank will work, but we have to copy attributes across to the other class. Not ideal as we now have two places where the jumpheight attribute lives.

blog-es-objDiagram1

The really messy part comes when you are accessing these attributes. Suddenly to see if something can jump we need to know if it is either a Human, or an ArmoredRobot(that subclasses Tank), and then get its jumpHeight. Imagine if there were more types of robots, some that couldn’t jump or had some other attributes. Suddenly whenever we want to use these attributes we have to perform lots of checks and object casting and always have to be aware of the entire Actor class tree; when all we care about is if it can jump!

ES Overview

Entities Systems solve this problem elegantly by removing this object hierarchy.
An entity system is broken into 3 parts: The entity, the components, and the systems.

  • An entity is just an ID (AotGB uses integers). Each entity has a unique ID, similar to a primary key in a database table.
  • Components are the actual attributes that an entity can have: hit points, armor value…
  • Systems use the components, and only the components their care about, to do the actual work.

The easiest way to see this is a concrete example:
First we create an entity, it is given ID# 234. That’s all it is! Just a number and absolutely nothing else.
Next we give it a component: a HealthComponent. The HealthComponent has two values: maxHP and currentHP.
Lets give it another component: a MovableComponent. It has two values as well: moveSpeed and turnSpeed.
Finally lets give it an AttackComponent. This has attackRange, attackDamage, and attackSpeed.

blog-es-objDiagram2

Okay, now that entity can move, has hit points, and can attack. Time to send it into the real world and cause trouble.

Systems

The parts of the game that interact with Components are called Systems. A game can have many systems; AotGB has around 30 of them.
One such system is the CombatSystem, the most fun of all the systems.
It runs once every frame, checks if an entity can attack, and if so it will perform that attack, deal damage, and check if the other entity died.

The first part in its update loop is to get all of the entities it cares about, specifically entities with a HealthComponent and an AttackComponent. It queries them like this

java code:
List<entityIDs> = es.getAllEntitiesWithComponents(AttackComponent.class, HealthComponent.class);
 // ‘es’ is the entity sys

 

With this simple query we get all the entities that we care about, and no extra baggage of other attributes, no class casting or instance checks. Super easy, clean, and in one line!
In reality the AttackComponent has a cooldown time, and a counter, so it can track if it is time to attack again. The CombatSystem looks at these values and will attack if the cooldown time has reached zero, like this:

java code:
if (playerAttackComponent.getCoolDownTime <= 0) {
    // time to attack the enemy
    float enemyHealth = enemyHealthComponent.getCurrentHP() - 
                          playerAttackComponent.getAttackDamage()
    if (enemyHealth <= 0) {
        enemyHealthComponent.setAlive(false)
        // play some sound
        // give the player some points
    }
 }

Not all systems run every frame from the game’s main update loop, as the combat system does. Some just run occasionally or are triggered to run. So what is the classification of a system? Anything that uses Components. Usually asking the ES for a bunch of entities with specific components it cares about.

Throw Out That OOP Mentality

The hardest part about ES is throwing Object Oriented Programming out of your head. At least for the entities and Components.
You do not want to subclass a component. For example with the AttackComponent you do not want a PunchComponent that subclasses it. If you do that, then you are back to checking in the systems “if this is a regular AttackComponent, or a punch this time?” You want to have a separate component, called PunchComponent, that does not subclass. You can then have a punch system that deals with it.
This can cause a little bit of duplication of code, but you can use some good design to make sure you aren’t duplicating too much.
It takes practice, and I had to rewrite the ES twice because I didn’t get OOP out of my head when making the first components.

The Back-End

Storing the components is fairly easy. I use a Hash map, but others use database tables. If you picture it stored in database tables then each Componet type (say, all AttackComponents) are stored in the AttackComponentTable:

blog-es-chart

Every entity with an AttackComponent has a row in the table. For example entity 98 has a damage of 7, a range of 2, speed of 0.5, and a cooldown time of 5.74
Performing the lookups is very fast because you can index any of the columns you wish, and you only have to query against only those entities with that particular component, not every single entity out there.

How I Have Found it so Far

  • ES makes your game very modular. If there is a bug with combat not working as intended, then it is restricted to only the CombatSystem class. This has saved my skin so many times and I rarely have a multi-hour long debugging session anymore; I always know where to look because of the modularity.
  • -Modability is super easy with components. A mod can just be a system that updates every frame, checks for a HealthComponent and a BlobComponent, and gives those blobs extra hit points every frame, thus regenerating them. None of the other systems have to care about this new system so the risk of breaking things is small. I’ve also set up AotGB so you can easily add and remove systems. If there is a level where there is no combat (just sneaking around and collecting items instead) I only have to remove or disable the combat system. No side effects; combat just doesn’t happen. And all of this with just one line of code!
  • It does take some practice to get used to ES, especially to not think about OOP as you are building the components. It can also be a little too much for a tiny game; if you don’t have an existing ES to plug in and use. I wouldn’t recommend it to beginners.

So When Should I Use One?

  • If you have a nasty Actor hierarchy.
  • If your combat (for example) code is in many places.
  • if you are doing a lot of class casting or type checking: “is this a jumping orc or a swimming orc”.
  • If you are doing networking. (I won’t get into this here, but in another post)
  • If you are making an MMO. (I won’t talk about this either here)

Conclusion

Well I hope you are a little inspired now to try making an ES or do some more reading. The benefits are many and there are very few downsides, so give it a shot!

Further reading

T-machine.org
Paulgestwicki.blogspot.ca
jMonkeyEngine ES thread

Time for a blog

The character limit on Twitter just isn’t enough any more. There’s lots I want to share and I need a new space for that. So, here it is, my new blog.

First off, a little bit about who I am.

I’m a software developer with around 10 years of professional experience. Most of my jobs are related to GIS, but throughout my career I have been working on games, game engines, mods. No major titles, just dabbling here and there, learning as I go.

One of my larger contributions to the gaming community is my work on jMonkeyEngine 3. I am one of the core developers and created its terrain system.

I am also the creator of an RTS game called Attack of the Gelatinous Blob. It is currently in development is has become my passion. It’s an ambitious project, but incredibly fun to work on.

What can you expect to see on this blog? Anything related to game development that I feel is worth sharing. I will describe techniques and technologies I use, and I will share the development progress of AotGB.

So stay tuned, and follow me on twitter: @sploreg @AotGB for frequent, small, updates.

ss-townUnderFire