Blog posts: The Measure of Enthusiasm

Good ol’ Hacker News is a great source of procrastination but amongst all the rubbish that somehow gets on there (and by rubbish I mean articles that have nothing to do with technology i.e. Mandela articles, geopolitics, travel blogs (seriously?!)), there are a few absolution gems.

One of those gems is the notion that writing about (I don’t like the word blogging) your project is one of the best ways to stay enthused. I can’t even remember the rationale behind it but I can guess that it has something do with:

  • Bringing clarity of mind by going through the process of putting chaotic thoughts to writing.
  • It’s a great way to show off work that you’re doing to your friends or, if you get lucky, a much wider audience. The feedback loop gets the creative mind excited.
  • Each post is like this little piece of marketing (and programmers aren’t typically the best marketers).
  • The idea that each post is like this extra (non-code) commit to your repository.
  • Writing about what you are doing keeps you focused on individual tasks. Instead of thinking “I’ve done all this work, what should I write about?” it will be, “What should I do this week so that I can write about it?” Knowing that progress is being made always helps the self-esteem.
  • It’s always fun to look back and reflect on how far you’ve come.

The last point is quite important to me. Sometimes I wonder where the hell my 20s went and I need to dig back up some photos or think really hard to account for that entire decade of my life. The same can be said of software projects. Mobile Assault feels really dated now but upon reflection there is a sense of satisfaction in how much we created; the game started as a PSP hack and turned into a 25+ mission PSP/iOS game in English, French and Italian with graphics that really pushed what could be rendered on a Homebrew PSP system. Historical screenshots through the versions are a great reminder of some of our milestone releases.

So this is why I’m endeavoring to write something every week about Failed State; I’m going to create the modern day journal of all the adventures and misadventures. Come October, which I’m optimistically targeting for release, I can look back and reflect on all the work that’s transpired yet during the journey, share progress with friends, colleagues and the odd random stranger who happens to stumble across my site.

Advertisements

New Game Kick Off

It’s been a lethargic last 4 months from a personal project point of view. I dabbled in some web based languages just to scratch an itch but have come to the realisation that what I really want to do is get stuck into this map based war game. I’ve been thinking about it for years, years because time flies and suddenly I’m a lot older, more of the house is paid off and my face is not looking so 20 something any more (though strangely I’m the fittest I reckon I’ve ever been courtesy of me trying to overcompensate for being a desk-jockey during the day).

But I digress. The point of this hacked together post is to finally kick off my new game project which I’m probably going to call Failed State. I’m pretty confident that that name is in the clear for iOS and Android but I do notice that there is an open source project using the name. And here I was thinking I was being original.

Time: Enemy no. 1

All part time code warriors fight time. That cursed 7-8 hours of sleep required to maintain one’s sanity means that there is about 2 hours max per evening to hack something together and that’s on the proviso that the screen at work hasn’t sucked the soul of enthusiasm. Going to the gym frees the mind somewhat, although that sacrifices another 60 more valuable minutes.

And where am I at with Failed State? Well, I have a rough ‘world’ being rendered using pre-downloaded Open Street Maps data of Auckland. Cool huh? Not that that makes a game; I’m miles from a game and that’s why I need to devise a strategy. I need to know what the heck I’m doing and how to go about doing it.

Program like an author

You can’t edit what isn’t already written down.

I can’t remember the exact words but essentially the idea is that, as a writer, you just have to keep writing and writing despite the likelihood that what you’re writing could ultimately be edited out. The important part is that something existed to be edited in the first place. There’s no such thing as a perfect draft.

The same thing can be said for a game project and I’ve come to the realisation that that first pass is not cutting code; there’s a quicker way of actually getting to the end of that first draft.

What I need is drawings, mockups, ideas; I have to flesh out the entire scope. I have to actually make a game on paper first. I’d love to be writing that in the past tense but the reality is that despite having drawn a few things, I’m nowhere near the finish line. The process then raises even more questions about game play. Good. That means there is less chance of coding myself into a corner.

I’ll admit that I’ve been a little guilty of spending too much time doing my OSM map importer. Sure, it’s work that had to be done and understood but it’s a slow way to get to the finish line; a slow means of doing the first draft. That being said, it’s been great for show and tell with the guys at work. My sister says it’s too dark.

Auckland CBD (landscape)

Balsamiq Mockups

After paper sketches will probably be the digital equivalent. Balsamiq Mockups seems the perfect way to bring order to my mass of sketches. The good thing about Balsamiq is that the output still looks like a rough prototype; it will be my second draft.

Planning for AI

I haven’t even dared to think too far into this. I need to make some decisions trees or something. Ah… so much to do.

Everything else

Scope! What is the scale of the game? Individual units like Command & Conquer? Squads of infantry like World in Conflict? Grand strategy like Civilisation? Touch controls like Autumn Dynasty? Airstrikes? Reinforcements? Is there base building? Air units?

There’s so much to decide. I kind of know what I want but that’s why these paper mockups are so important. From them I can get a sense of scale and scope and how much work will be required to get to the end. Multiplayer? Doubt it. I’d love to finish something by October and I have to cut as much scope as I can to make an entertaining game.

Porting a Cocos2d-x iOS game to Android

I admit, making an iOS and Android version of a game in parallel is usually a preferred option, but I wanted something out fast, cocos2d-x was new to me and I didn’t want to stuff around with Android.

Gosh I despise working on Android, at least at the moment. Sure, provisioning profiles, certificates and a $140 NZ iOS licensing fee is a bit of a nuisance, but that is trivial next to the cluster-f*** which is Android development. Android Studio, based off IntelliJ was released in pre-release just recently, but I see there is no built in C++ support, just Java.

XCode and the Cocos2d-x project templates makes getting Cocos2d-x set up and running for iOS a breeze next to Android and why the powers that be don’t act upon the fact that Apple is making stupid amounts of money on paid apps (yes, emphasis) through their app store because of a robust application development and delivery eco system, is totally beyond me. Maybe Android Studio is a step in that direction, but it seems 2 years late. Good thing we have short memories, so once it’s finally ready for prime time, maybe all us devs will forget that Android as of June 2013 was a pain in the ass.

To make the Android project I followed the tutorial from Ray Wenderlich, which required the use of the create-android-project.sh script.

Here is the list of gotchas I had to deal with when porting this “cross platform” game to Android.

No STL Libraries

Why this just doesn’t work is beyond me.

Error:
‘int64_t’ has not been declared
(or anything else std related)

Solution:
Add
APP_STL := stlport_static
to the Application.mk file. It may already have
APP_STL := gnustl_static.
Don’t use that, it doesn’t work.

Using boost shared_ptr

Boost is an incredibly useful C++ toolkit that all devs should be aware of. Will it work with Android ‘out of the box’. Of course not, we’re coding for Android!

Error:
…/boost/smart_ptr/detail/shared_count.hpp:106: error: undefined reference to ‘boost::throw_exception(std::exception const&)’

Solution:
Go to the Application.mk file for your project and add
APP_CPPFLAGS := -frtti -fexceptions
APP_CFLAGS += -DBOOST_DATE_TIME_NO_LIB -DBOOST_REGEX_NO_LIB

Source: Stackoverflow

OpenGL ES header issues

I have some custom drawing code for debugging purposes (rendering box2d shapes, I think).

Error:
fatal error: OpenGLES/ES1/gl.h: No such file or directory
compilation terminated.

Solution:
#ifdef TARGET_OS_IPHONE
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
#else
#include <EGL/egl.h>
#endif

Cocos2d-x bugs

In version cocos2d-2.0-x-2.0.4, which is what I’m using, there seems to be some missing code.

I get this when trying to use CC_ASSERT
Error:
error: ‘CCMessageBox’ was not declared in this scope

Solution:
Go into platformandroidCCPlatformDefine.h and change line 11 so that
CCMessageBox(content, "Assert error") becomes cocos2d::CCMessageBox(content, "Assert error")

Source: Cocos2d-x forums

TTF Font Loading is different

Problem:
It turns out that when using cocos2d-x functions that require a font, e.g. CCLabelTTF, that iOS uses the name of the font whereas Android requires the file path of the font.

Solution:
I used some constants and platform specific defines
#ifdef TARGET_OS_IPHONE
const char* FONT_AWESOME_TTF = "FontAwesome";
#else
const char* FONT_AWESOME_TTF = "fontawesome-webfont.ttf";
#endif

Source: A blog post by Jordy

The emulator crashes on startup

If the emulator was running on a secondary monitor, then there’s a chance that trying to restart it on the secondary monitor will result in a crash before it can fully start.

Error:
emulator64-arm quit unexpectedly

Solution:
Open ~/.android/avd/[The name of your virtual device].avd/emulator-user.ini

and set window.x to zero, i.e. window.x=0

Source: A blog post from ‘an IT dad’

Game Center Replacement

I ended up just caching score to a text file for the initial release. Cocos2d-x has a method for telling you where abouts on the Android device data can be cached. From there, simple C File IO calls can be made.

std::string path = CCFileUtils::sharedFileUtils()->getWriteablePath();
FILE* f = fopen(path.c_str(), "r");
...
...
fclose(f);

Logging

printf is not going to work in Eclipse. Instead Cocos2d-x has a CCLOG call that will print output to LogCat.

Solution:
Add #define COCOS2D_DEBUG 1
To the top of any source file, but just before the #include “cocos2d.h”

CCLOG(“Print somethingn”);

Analytics

I use Localytics as my analytical tool. The instructions are quite straight forward so I won’t repeat that here. The Cocos2d-x specifics however are:

  • The .java Activity file that you will want to edit is the ${COCOS2DX_HOME}/cocos2dx/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java file. If you’ve followed this tutorial then it’s located in the Eclipse project tree under cocos2dx-src > org.cocos2dx.lib
  • In the same way that the cocos2dx source was linked to the Eclipse project, copy the Localytics com folder (and its contents) somewhere and link to it in Eclipse using Project Properties > Java Build Path > Source Tab > Link Source. It’s going to look like com.localytics.android in the project tree.

Final thoughts…

That’s enough drama for one post. The main drama was actually messing with file paths because the create-android-project.sh script inside the cocos2d-x download package created a structure that was inconsistent to the XCode templates I’d used for my iOS version.

This ultimately meant

  • a copy past of asset files
  • The C++ source files from my iOS version (in its own separate .git repo) being linked across to the Eclipse/Android project.

Once I figure out what paths the create-android-project.sh has hardcoded into the Eclipse project, I’ll try and consolidate all the files.

Binding C++ to Lua Using Swig

Scripts are great. They’re a means of creating executable functionality without the burden of compilation and linking. Sure, that’s a simplification because there’s always some kind of setup required to get scripts going, but compared with working with much lower level languages like C/C++, scripting languages like Lua and Javascript are a refreshing departure from dependency hell.

So why not just use a scripting language all the time?

Answer: Raw, low level, unadulterated power! Okay, so that’s an exaggeration, and there are always tradeoffs when dealing with languages so close to the bits and bytes and hopefully that’s where a scripting language can help us out.

Binding two worlds

For the following examples I’m going to use C++ with Lua, just because I’m a C++ guy and Lua is something that I’ve been meaning to play with for a while. To bind the two together, I’ll be using swig. (Note that swig’s official lua documentation is here)

Here is an analogy to do with building a house. No, let’s make it a skyscraper; a 100 story high skyscraper. Now, that skyscraper isn’t built 100% on site. Much of it is prefabricated off site, and many of the floors are likely to be identical to each others. In summary, there are the following features.

  • The skyscraper is made of prebuilt components
  • The building components could have been made at anytime, by any manufacturer.
  • The building is scalable; so many of the floors are just repeated. Design one floor then stack 99 more on top (let the interior designers do all the showy stuff like paint it lime green or whatever the fashion is for those guys on level 17).

…Okay, so this is starting to look like an example in Object Oriented programming, but bear with me…

Your perfectly modular code that you’ve created in C++ land (because, you know, we all make perfectly modular code) is the equivalent of the components that make up the skyscraper.

So here’s a Skyscraper and Floor class followed by a super basic C++ program that uses them.

#ifndef Skyscraper_H
#define Skyscraper_H

#include <vector>
#include <string>

#include "Floor.h"

class Skyscraper
{
public:
	Skyscraper();
	virtual ~Skyscraper();
	
	void setName(std::string name);
	std::string getName();
	
	const Floor* getFloor(unsigned int floorNumber);
	Floor& addFloor();
	
	void print();
private:
	std::string mName;
	std::vector<Floor> mFloors;
};

#endif // Skyscraper_H
#include "Skyscraper.h"

#include <iostream>

Skyscraper::Skyscraper(){}
Skyscraper::~Skyscraper(){}

void Skyscraper::setName(std::string name)
{
	mName = name;
}

std::string Skyscraper::getName()
{
	return mName;
}

const Floor* Skyscraper::getFloor(unsigned int floorNumber)
{
	if (floorNumber < mFloors.size())
		return &mFloors[floorNumber];
	else
		return NULL;
}

Floor& Skyscraper::addFloor()
{
	mFloors.push_back( Floor() );
	return mFloors[mFloors.size()-1];
}

void Skyscraper::print()
{
	for (int i=0; i<mFloors.size(); i++)
	{
		Floor floor = mFloors[i];
		std::cout << "Storey: " << i << " Fibre: " << (floor.getHasFibre() ? "y" : "n") << " Carpet Colour: " << floor.getCarpetColour() << std::endl;
	}
}
#ifndef Floor_H
#define Floor_H

#include <iostream>
#include <string>

class Floor
{
public:
	Floor();
	
	unsigned int getCarpetColour();
	void setCarpetColour(unsigned int colour);
	bool getHasFibre();
	void setHasFibre(bool hasFibre);

private:
	std::string mTenant;	
	unsigned int mCarpetColour;
	bool mHasFibre;
};

#endif /* defined(Floor_H) */
#include "Floor.h"

Floor::Floor() : mCarpetColour(0x00FF0000), mHasFibre(true)
{
}

unsigned int Floor::getCarpetColour()
{
	return mCarpetColour;
}

void Floor::setCarpetColour(unsigned int colour)
{
	mCarpetColour = colour;
}

bool Floor::getHasFibre()
{
	return mHasFibre;
}

void Floor::setHasFibre(bool hasFibre)
{
	mHasFibre = hasFibre;
}

If one were to make use of these objects, some C++ code may look like the following.


#include <iostream>
#include <time.h>
#include <stdio.h>

#include "Skyscraper.h"

int main(int argc, const char * argv[])
{
	srand ( time(NULL) );
	Skyscraper skyscraper;
	skyscraper.setName("Cloud Hugger");
	
	for (int i=0; i<99; i++)
	{
		Floor& floor = skyscraper.addFloor();
		floor.setCarpetColour( rand() % 0x1000000 );
		floor.setHasFibre(false);
	}
	
	Floor& floor = skyscraper.addFloor();
	floor.setHasFibre(true);
	floor.setCarpetColour(0xFF);
	skyscraper.print();
}

Basically we’ve just created a 100 floor skyscraper where the top most penthouse has a red carpet and a fibre optic internet connection. Awesome.

So where does lua and Swig fit in?

Swig is a tool that creates the wrapper/”glue” between our C++ classes and Lua. Here are the basic steps which will be elaborated upon next.

  • Install/Compile swig (http://www.swig.org/)
  • Compile Lua and link its lib file to your C++ project
  • Outside of your project, make a new markup file that exposes the parts of your C++ classes you want to be used with Lua. This is going to create a lua module. For our example, lets call it building_contruction.i
  • Run swig on that building_construction.i file. This will create a building_construction_wrap.cxx
  • Add building_construction_wrap.cxx to your C++ project.
  • Add some lua setup code to your C++ project so that lua is initialised and can find the module that swig has created for us (more on this further down).
  • Create a lua script
  • Compile and run

The basic way to create the Swig file is just to expose all your class to it (rather than just individual methods and member variables). Notice the need for including some standard template library header files. These are built into swig for our convenience (phew).

/* File : building_construction.i */

%module building_construction
%include "std_string.i"
%include "std_vector.i"

%{
#include "Floor.h"
#include "Skyscraper.h"
%}

/* Let's just grab the entire header files here */
%include "Skyscraper.h"
%include "Floor.h"

To create our wrapper/binding code, run this with Swig using something like:

"path_to_swig_binary"/swig -c++ -lua "path_to_module_file"/building_construction.i

This will create a building_construction_wrap.cxx file. Add this to your project.

Now, the following is the modified main.cpp with all the lua setup code. Note that this app requires a command line argument that points to your .lua script.

#include <iostream>
#include <time.h>
#include <stdio.h>

#include "lua.hpp"
#include "lualib.h"
#include "lauxlib.h"

extern "C"
{
	int luaopen_building_construction(lua_State* L); // declare the wrapped module
}

#define LUA_EXTRALIBS {"building_construction",luaopen_building_construction},

int main(int argc, const char * argv[])
{
	lua_State *L;
	if (argc<2)
	{
		printf("%s: <filename.lua>n",argv[0]);
		return 0;
	}
	
	L=luaL_newstate();
	luaopen_base(L);  // load basic libs (eg. print)
	luaL_openlibs(L); // load all the lua libs (gives us math string functions etc.)
	luaopen_building_construction(L);	// load the wrapped module
	if (luaL_loadfile(L,argv[1])==0) // load and run the file
		lua_pcall(L,0,0,0);
	else
		printf("unable to load %sn",argv[1]);
	lua_close(L);
	return 0;
}

Almost there. Now for the .lua file. That code above that created our 100 story skyscraper, here it in in lua form.

[ruby]
— Assemble a 100 floor skyscraper made up
— of 100 floors where the topmost floor is a
— penthouse.

skyscraper = building_construction.Skyscraper()
skyscraper:setName(&quot;Cloud Hugger&quot;)

print( skyscraper:getName() )

— Add 99 floors with random carpet colour and no
— optical cables (gutted)
for i=0,99 do
floor = skyscraper:addFloor()
floor:setCarpetColour( math.random(0,255) )
floor:setHasFibre(false)
end

— Build the penthouse which has red carpet (think Palpatine)
— and with fibre, because Palpatine likes fast internet.
floor = skyscraper:addFloor()
floor:setCarpetColour(255)
floor:setHasFibre(true)

— Print the result
skyscraper:print()
[/ruby]

…and that’s it. Hopefully something printed out the console.

Essentially we’ve coded the start of an amazing “skyscraper building app” that no longer has to be compiled and linked every time we wish to tweak some attributes to our skyscrapers. Hopefully this promotes good modularity of your C++ code and aides productivity by being able to tweak functionality via the scripts.

For more thorough documentation on using swig with lua, please refer to their documentation here: http://www.swig.org/Doc2.0/Lua.html#Lua_nn12