<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>#AltDevBlogADay &#187; Charilaos Kalogirou</title>
	<atom:link href="http://www.altdevblogaday.com/author/charilaos-kalogirou/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.altdevblogaday.com</link>
	<description>Each day a little more #gamedev love</description>
	<lastBuildDate>Thu, 17 May 2012 03:06:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Launching on the AppStore in the year 2012</title>
		<link>http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/</link>
		<comments>http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 20:04:06 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[General Interest]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25310</guid>
		<description><![CDATA[<p>Today is somewhat an important day, as it is exactly 60 days since the day I can officially call myself a published indie game developer! It was February 3rd when <a href="http://bit.ly/getpopcorny">Mr. Pop Corny</a> rushed (actually it crawled thanks to Apple, but I will get to that below) into the AppStore after an 8 month development time, and the dream came true. So it seems now it is a good time to share some of my experiences regarding launching on the AppStore. I will try to provide some insight that I wish I had from other projects prior to launching my own.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/" class="more-link">Read more on Launching on the AppStore in the year 2012&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Today is somewhat an important day, as it is exactly 60 days since the day I can officially call myself a published indie game developer! It was February 3rd when <a href="http://bit.ly/getpopcorny">Mr. Pop Corny</a> rushed (actually it crawled thanks to Apple, but I will get to that below) into the AppStore after an 8 month development time, and the dream came true. So it seems now it is a good time to share some of my experiences regarding launching on the AppStore. I will try to provide some insight that I wish I had from other projects prior to launching my own.</p>
<h2>Background</h2>
<p>Let me start with some info on <a href="http://bit.ly/getpopcorny">Pop Corny</a>. Pop Corny was <a href="http://altdevblogaday.com/2012/02/03/my-game-design-hat/">designed</a> to be a simple and fun casual game, covering the need for short game session experiences that mobile phone games require. </p>
<p>I self funded, developed, published and initially launched the game as a paid application at the $0.99 tier. Later on, it switched to free and monetizing with IAPs, but bare with me for the details of this decision. </p>
<p>Below are some more technical details of the game:</p>
<ul>
<li>Development time: 8 months</li>
<li>Number of developers: 1 </li>
<li>Outside contractors for sound and most graphics</li>
<li>Build using a fork of <a href="http://devnet.sylphis3d.com/">Sylphis3D Game Engine</a> </li>
<li>Support of all iPhone, iPod touch and iPad devices</li>
<li>Source code (gamecode + game engine code excluding third party libraries):<br />
<code><br />
-----------------------------------------<br />
Language    files    blank comment   code<br />
-----------------------------------------<br />
Lua            52     2631    1026  10415<br />
C/C++ Header   77     1209    1111   3718<br />
C++            32      731     882   2552<br />
XML             1        1       0    788<br />
Python          9      170     136    630<br />
Bourne Shell   13       70     167    284<br />
Objective C     2       14      14     25<br />
-----------------------------------------<br />
SUM:          186     4826    3336  18412<br />
-----------------------------------------<br />
</code>
</li>
<li>Game code accounted for 5983 lines of the above LUA code</li>
<li>The total source dataset reached up to 0.4 GB </li>
<li>Resulting “compiled” dataset at 10MB</li>
<li>Initial price $0.99 (50 days) then dropped to free</li>
<li>Total sales in two months: ~150000</li>
<li>IAP conversion rate: ~2.0%</li>
<li>Ratings: 4.5/5 (from 600 ratings, 70% of which are 5 star)</li>
</ul>
<h2>Promotion</h2>
<p>As I said the game was funded and published without any help from the outside. This easily translates to: <i>no money for marketing</i>. Therefore I had to find ways to make the best I could on the cheap. One of the major aids on that seemed to be the famous <b>launch day</b>.</p>
<p>Everyone developing on the AppStore will tell you that the launch day is one of the most important events in effectively publishing your game. You must do the best in your powers not to fail that day. And this is true. I had published 3 more applications on the AppStore prior to this game and the launch day will give you eye balls costing thousands of dollars for free. This is through the AppStore’s new releases list.</p>
<p>My approach was to combine that visibility with all the “social” publicity I could harvest, doing my best to leap as high as I could on the charts. Then possibly some game journalists would notice and write about it, thus keeping the fire burning. To do that I created a <a href="http://bit.ly/cornytrailer">trailer video</a> for the game and one week earlier I created an event on Facebook for the “unveiling of the video trailer”. I invited everyone I could and one week later (on January 31th) I presented the video. That day I also posted the video on every related forum I could. This caused some fuzz but mostly in Greece where most of my facebook friends live in. </p>
<p>The release day was set on February 3rd. I already had approval from Apple and I was already sending out promo codes to game journalists before that. For this I was carefully compiling a list of game review websites and journalists from early on the development cycle. I had these ordered by alexa ranking by review scores and game types. When I got the game approved by Apple, I send out all 40 promo codes I had available, and contacted 100 more without a promo code. </p>
<p>Early on the development cycle I took another big decision based on marketing. That was to support OpenFeint in addition to GameCenter. OpenFeint has its own top games, featured games and new releases, which can give some extra exposure to your new and unknown game. I decided that I needed that extra eyeballs, so I supported both social gaming networks. </p>
<p>In short what I did prior to the release day were these:</p>
<ul>
<li>Created a “coming soon” video trailer</li>
<li>Created Facebook page and Twitter page for the game</li>
<li>Organized a Facebook event for the unveiling of the game video</li>
<li>Send out all 40 promo codes to game journalists (with all media packs, bells and whistles) </li>
<li>Wrote posts in “new releases” parts of forums</li>
<li>Prepared a cross promotion among my other apps</li>
<li>Supported OpenFeint</li>
</ul>
<p>Then all I had to do was wait for the launch day and the sweet success&#8230; or not&#8230;</p>
<h2>Apple spilling the milk</h2>
<p>With everything set and the game automatically scheduled to launch at the world’s AppStores on February 3rd, an unexpected nightmare started for me on February 2nd (since we live in a globe and in New Zealand it was already “tomorrow”). Of course I was viewing the New Zealand’s AppStore waiting for Pop Corny to appear, and it did. Oh! The Joy! After all these months of hard work it was there&#8230; taking its chance! Couldn’t be happier and more stressed at the same time&#8230; however the moments of joy ended shortly after I looked closer. Fear filled my heart when I noticed next to my game’s icon a release day of “Jan 31th”. I rushed to the new releases list like a maniac looking for Pop Corny which was nowhere to be found. What happened? Had the app gone live 3 days ago and I didn’t notice? Hardly&#8230; the app was not live on any other AppStore. I manually checked every other AppStore&#8230; not released&#8230; </p>
<div class="wp-caption alignleft" style="float:left"><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/releaseday.png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/04/releaseday.png" alt="Mr. Pop Corny is a popcorn loving monster" class="size-full wp-image-23798"></a>
<p class="wp-caption-text">AppStore entry showing<br /> the wrong release day</p>
</div>
<p>I was optimistic, these distributed systems are slow to update and initially things like that might happen. However, Feb 3rd started to dawn in more countries and the same story was repeating. Pop Corny was appearing as a 3 days old app. 3 days when you launch on the AppStore is an eternity. I was out of the front page, before I even got the time to get on it. I tried to contact Apple through the support system but that is easier said than done. </p>
<p>It was then I realised how small and expendable I was. There is absolutely no way to solve a situation like this with a system that works by choosing among 15 nested problem categories before you finally get a text box to write down your problem. No way to resolve it with an one day round trip for getting a reply that was canned and had nothing to do with what I described. No way when you can’t -at least- follow up on the answer you get. I tried again and again for the next days by submitting from the start my problem rephrased in the best way I would&#8230; fail. </p>
<p>It was almost 7pm US time when auto-magicaly the release day of Pop Corny rolled to the correct Feb 3rd on all AppStores. However it was too late. Some AppStores were about to go on Feb 5th by then. The icing on the cake however was the reply to my last plea at Apple that told me that they don’t see any problem with the date as it is Feb 3rd. The irony!   </p>
<p>The problem also managed to mess up OpenFeint’s releases system. OpenFeint, once you have the app approved, scans the AppStore to see when your game releases. I guess that was the reason Pop Corny didn’t got on OpenFeint’s lists. One week later I contacted them about the problem and they said that somehow the system skipped my app, and that they had to add it manually. They couldn’t find an explanation, but I could&#8230;</p>
<p>This way I had zero exposure from the AppStore new releases, resulting in next to zero sales. It was a disaster. Apple should really make up to me for this someday by featuring it for a day or two&#8230; I can wait.</p>
<h2>Getting a grip and keep walking</h2>
<p>The above disaster affected all the AppStores in the world. It resulted in Pop Corny selling 10 units on release day in the US. I know crap-ware that were released the same day and sold more (based on their top paid ranking). It was so, because no one knew of my new released game. </p>
<p>In Greece, however, it was another story. Here is most of my “social network”. People knew about Pop Corny and they were expecting it. Several major local iPhone blogs wrote about it and the game took off. In less than 24 hours Pop Corny was number one top paid application. That was among all applications, not just games. 5 stars reviews started coming and it was heaven. A few days at the top and it was also on the local TV media. </p>
<p>This contrast between Greece and all other countries was to me a great illustration of how publicity is king. You must bring your game in front of the players face. And that is hard. It is the hardest part for a small developer. No one will look at you when you are small. Getting big seems like a self fulfilling prophecy. </p>
<div style="width: 300px;float:right;font-style:italic;font-weight:bold;background: #eaeaea;margin: 10px;padding: 15px">Being the number one top paid application in Greece translates to 200 sales a day&#8230;</div>
<p>From the 150 emails I send to reviewers I only got replies from 10 people. 8 of them kindly suggested I pay some fee and the rest two just told me that they were too busy to bother. By monitoring the downloads on the media pack I could see that just two of them bothered to download it. It is clear that something is wrong here. It seems that the only way to get covered these days is through dollars. </p>
<p>Being the number one top paid application in Greece translates to 200 sales a day (yes it is a small store). This is 100 euros a day after Apple’s cut. Does not sound that bad, but given the universal decay law of the AppStore (I will talk about it next), it was not enough.  Meanwhile on all other AppStores the app was doing poorly. </p>
<p>I knew that it was out of my reach to reverse this situation, so I decided to step back, stop desperately trying to push it, and focus on fixing some bugs, implement some new features until the day the game would go free. Going free was in my mind since the development days. The game was actually designed to work as a free game from development day one but the final decision to go paid was taken a few days before the release. </p>
<p>I saw this as a second chance. My means of getting more eyeballs on the game. But I knew that going free is not easy. It is a whole different arena. Going free will give you a big sales boost mainly because of applications like <a href="http://www.appshoper.com">AppShoper</a>. These kind of apps scan the AppStore every day and report to its users which apps has gone free, resulting in many sales. However many is not enough when competing with free applications. You need LOTS more. </p>
<p>There are services out there like OpenFeint’s <a href="http://freegameoftheday.com/">“Free Game Of The Day”</a> that provide you with the extra visibility you need for the day you go free. They feature one game every day, and promote it through their website and their iPhone app. I contacted them, they liked the game and I took the first slot that was available, that happened to be Thursday, Match 22nd (yeap the day Angry Birds Space came out&#8230; no fear!). They are very well organized and the process of submitting artwork was very streamlined and efficient. I submitted the appropriate banners and texts and there was nothing more left to do but wait for the day. </p>
<p>The day came and Pop Corny became free. The effect of this promotion was overwhelming. Pop Corny started to climb the charts all over the world at incredible speeds. It was not much later that it was ranking in the top 10 of more than 20 AppStores, and being number one of its category in 10 AppStores. </p>
<p>At startup the game checks for a .plist file on my server that contains possible news to present to the user. This allowed me to measure the rate of downloads in realtime. It reached a whopping 48 downloads/min. A few hours in the promotion 148apps.com featured it and even more downloads happened. This continued for the whole day (which is actually 48 hours to cover all the globe) and I had the opportunity to correlate the spikes I saw on the news file consumption with mentions on twitter, and posts on blogs, etc. A very educative experience.  </p>
<p>With the game on so many charts it would be stupid to just turn to paid after the promotion day, switch charts, and lose the exposure. Also the revenue from the free version was already a multiple of the revenue with the paid. So I took the decision to keep it free. I believe I did the right thing. The game did 70000 downloads in the weekend following the promotion day, received very good reviews from the users and the revenue from the IAP was climbing. I was totally satisfied. </p>
<h2>The universal decay law of the AppStore</h2>
<p>One of the biggest myths busted by my experience with launching Pop Corny was that visibility on the AppStore is king. It seems like everyone believes that being on the top 10 is the way to sell. That this will translate to visibility and sales in a feedback process that will sustain enough to make a profit. You must do all you can to enter the charts as a way to make your game sell more. For me now, this is the biggest misconception about the AppStore.<br />
With the huge amount of applications in the AppStore and the new ones that enter everyday, the charts only act as a capacitor. They smooth out spikes. Most sales today start outside the AppStore and not inside. The people that will buy your application because they saw it on the charts are not enough to sustain it on its position, let alone to lift it. Therefore we witness “the universal decay law of the AppStore” as I call it. Any application that is not receiving some external to the AppStore’s charts force will follow the graph below:</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/Στιγμιότυπο-2012-04-03-7.34.10-μ.μ..png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/04/Στιγμιότυπο-2012-04-03-7.34.10-μ.μ..png" alt="" width="475" height="177" class="aligncenter size-full wp-image-25340" /></a></p>
<p>Let that be paid or free. The only thing that changes is the absolute amount of downloads, which is orders of magnitude larger when free. How fast is the decay depends on the competition, how much you icon and descriptions attracts buyers and what rating you have. </p>
<p>Bottom line is that the charts cannot sustain you these days. It probably did some years ago, but not anymore. You should never think of the charts as your means to sales. Use it just as an indicator of how well you are doing. The game is played out of this field. Get reviews, tweets, mentions, and of course get featured by Apple. </p>
<h2>Conclusion</h2>
<p>The AppStore is not an easy place to publish in 2012. I was not expecting it to be easy, since Pop Corny was not my first application published there. However I would really love not to have been squashed by that bug with the release day. At least it would make me feel much better if I knew I could efficiently communicate the problem to Apple. </p>
<p>In the end however I think that Pop Corny did very well and will do better with time. I learned a lot through the process, it has almost covered its development costs and also gave me the joy of having hundred of thousands of people playing my game. With a zero marketing budget and being my first game, it certainly exceeded my expectations. It proved that you can still have a chance on the AppStore without some big dollar marketing campaign. However it is getting really hard to do so. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My game design hat</title>
		<link>http://www.altdevblogaday.com/2012/02/03/my-game-design-hat/</link>
		<comments>http://www.altdevblogaday.com/2012/02/03/my-game-design-hat/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 19:48:19 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=23755</guid>
		<description><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/02/hats.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/hats-236x300.jpg" alt="" width="236" height="300" class="alignright size-medium wp-image-23791" /></a>One of the main traits that an indie developer must cultivate is that of wearing many hats. All indie game develepers will tell you about it, and it is the first thing you will realise when going indie. Wearing many hats is usually the result of small budgets. Small budgets mean less heads, but equal amount of hats. What I learned through the course of developing my indie game is that your success depends on how well your head fits those hats. <strong>Your game will simply be as good as the worst fit.</strong> </p>
<p><a href="http://www.altdevblogaday.com/2012/02/03/my-game-design-hat/" class="more-link">Read more on My game design hat&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/02/hats.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/hats-236x300.jpg" alt="" width="236" height="300" class="alignright size-medium wp-image-23791" /></a>One of the main traits that an indie developer must cultivate is that of wearing many hats. All indie game develepers will tell you about it, and it is the first thing you will realise when going indie. Wearing many hats is usually the result of small budgets. Small budgets mean less heads, but equal amount of hats. What I learned through the course of developing my indie game is that your success depends on how well your head fits those hats. <strong>Your game will simply be as good as the worst fit.</strong> </p>
<p>One of the hats I had to wear for the development of <a href="http://bit.ly/getpopcorny" title="Pop Corny">“Pop Corny”</a> was that of the game designer. The closer I had ever come to game design before this, was playing games with a little more inquiring spirit than most players do. This can definitely be interpreted as a bad hat fit. It was clear that in order to have a successful game, I had to find clever ways to improve the fit. This of course could be done by adjusting the head (becoming a better game designer) or by adjusting the hat (adjusting the problem itself to something that I would handle). It was obvious that I had to do the first as much as possible, but without the later I was not going to go far. </p>
<h2>Adjusting the head</h2>
<p>So I went out and absorbed every single drop of knowledge I could on game design. Read blog articles, watched video presentations, hanged posters of Johnathan Blow over my desk, etc :) All these helped, but I knew that I had to bring the battle to my battlefield in order to win. This meant that I had to base my game on a simple (yet effective) gameplay idea, and build on that using analytic methodology where I can be good at. My guidelines were:</p>
<ul>
<li>single touch, simple and effective game mechanic that would make great gameplay for touch devices</li>
<li>The player should be able to start a game whenever he had some time to “kill”, whether that is 1 minute or 10 minutes or half an hour, and enjoy the game equally. </li>
<li>The gameplay should not require too much “brainpower” from the player and depend more on trained reflexes and getting used to, while giving you the joy of acquiring true skills.</li>
</ul>
<p>The process of meeting the above requirements can’t be fully transcribed, as it was mostly intuition based. It was clear that the game had to be an endless runner, which basically means that the player can never finish the game, and getting better would mean better score and more play. This would allow for my “short fun” direction. </p>
<p>I struggled a lot more on what an effective game mechanic should be to produce a great gameplay for touch devices. The simplest of all mechanics on a touch screen is the “tap”. I wasn’t feeling right about it, as it is overused and you probably end up with an experience not so original. Then I looked at swipes. Swipes are simple, but at the same time elaborate enough to resemble real life “game” actions. For example a swipe can be a throwing action in real life. So I centered my thinking around throwing stuff with your fingers. I did some prototypes of throwing circles and hitting rectangles and it was fun. Through an experimentation process I ended up with the “sling” throwing mechanic. You basically swipe in the opposite direction of the intented. This was a revelation. The inverted swipe posed a slight challenge to the players brain, that as one started to get it, it gave a very cool feeling of accomplisment. I went out and gave it to friends so I could test reactions. As people where getting it you could see fingers pointing all over the screen&#8230; fights over the who plays next, etc&#8230; I was convinced. </p>
<div class="wp-caption alignleft" style="float:left"><a href="http://altdevblogaday.com/wp-content/uploads/2012/02/Screen-1-clean.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/Screen-1-clean.jpg" alt="Mr. Pop Corny is a popcorn loving monster" width="338" height="450" class="size-full wp-image-23798"></a>
<p class="wp-caption-text">Mr. Pop Corny is a popcorn loving monster</p>
</div>
<p>The idea of the pop corn, the pop corn loving monster, etc came from my sister during a brainstorming session. So we had a theme. Next we started thinking of ways to enrich the experience and keep the players&#8217; interest for longer time. One of the elements that worked was the “box progression”. I got the idea originally from <a href="http://itunes.apple.com/us/app/tiny-wings/id417817520?mt=8">Tiny Wings</a>, and the way you upgrade nests, but found out that it is a common thing in the iPhone games field. So the user has to complete certain objectives to upgrade his popcorn box and get bigger score multipliers. We also used this progression to teach the player how to get bigger scores, and survive longer. After that we added an extra task of collect drachma coins for the player (an inside joke for my country possibly defaulting to its national currency drachma). He could then use the drachma coins to upgrade bonuses and buy new pop corn boxes that gave extra powers. So the game became more complex and hard to balance, but this was mainly a problem I could cope with as an engineer. I was in my field. </p>
<h2>Do it like an engineer</h2>
<p>Questions like “how much should a bomb cost?” (a bomb is used once and pops all corn on the screen at once) are hard to answer without the right tools. What data is necessary to give a good answer? For the above question you need to know the answer to at least “How many coins does the player get in one game session?” and “How many bombs in a single session does not put the game out of balance?”. An experienced game designer might be able to answer the original question by instinct and get it right. However, I had to do what I can do good. Break down, measure, answer, build and repeat until the required feeling is achieved.</p>
<p>What I did was log all the key elements of game sessions by beta testers, and interpret them with the so handy <a href="http://www.scipy.org/" title="SciPy Python Module">SciPy and related NumPy modules for python</a>. These modules allow you to easily read csv files, process the data with almost every statistical analysis method in the world, produce beautiful graphs, etc. For example lets look below at the number of sessions per coin collected range. These are the samples that were collected for the same player level in the game. </p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/02/normal1.png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/normal1.png" alt="" width="500" height="375" class="aligncenter size-full wp-image-23768" /></a></p>
<p>These follow the normal distribution around the value of 80. This means that most of the times a user will collect 80 coins per game. However there might be caveats if we are not careful enough. For example lets look at the distribution below:</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/02/single.png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/single.png" alt="" width="500" height="375" class="aligncenter size-full wp-image-23762" /></a></p>
<p>If we try to fit a Gaussian function in the above data we will have huge errors in our estimations. Before we go and hit least squares and optimization algorithms, we would always try to think through of what is generating the data. Here the false assumption about our data comes from the fact that we consider them all to be coming from the same “generator”. That “generator“ is the player interacting with the game in order to collect as many coins as one can. However because the game is a beta, and users are beta-testing it, the generators are two. The first is the one I described before, but there is also the sessions that the user tries to test some other aspects of the game and does not collect coins! So what we really have here is two different data sets mixed to one. One from the players trying to collect coins that produces a distribution of values around 80 (the red graph) and one from the players that don’t collect because are testing something and produce a distribution of values around 0 (the green graph). Adding the red with the green gives the original observed blue. The graph bellow illustrates it:</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/02/all.png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/all.png" alt="" width="500" height="375" class="aligncenter size-full wp-image-23767" /></a></p>
<p>So we need to fit the sum of two Gaussians in our data with unknowns the two mean values and the two variances. This way we get the correct value of 80 for the mean coins collected per game session, which would otherwise be detected as 60 or something. So if you want the player to be able to afford 3 bombs every 4 games you set the bomb to cost 100 coins and you are set.</p>
<h2>Conclusion</h2>
<p>This was my approach to designing my game, and it seems to have worked out quite well, with the game receiving great acceptance. The game got to #1 Top Paid Game in the Greek AppStore within hours of its release and #2 Top Paid across all app categories, all 5 star reviews. On most reviews the addictive gameplay was mentioned, which is so comforting when I know that was not my best field. It turns out you can replace part of intuition and experience with analytic tools.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/02/03/my-game-design-hat/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Game Pre-Mortem</title>
		<link>http://www.altdevblogaday.com/2012/01/04/game-pre-mortem/</link>
		<comments>http://www.altdevblogaday.com/2012/01/04/game-pre-mortem/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 12:48:33 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[game development]]></category>
		<category><![CDATA[game engine]]></category>
		<category><![CDATA[gamedev]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[mortem]]></category>
		<category><![CDATA[nlogn]]></category>
		<category><![CDATA[pop corny]]></category>
		<category><![CDATA[pre]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=22325</guid>
		<description><![CDATA[<p>Happy new year everybody! It seems we made it to 2012 successfully! Lets hope this will be a prosperous year for everybody, with many new things to learn and accomplish. </p>
<p>With my game entering the final phase of development, I think its time for a pre-mortem. We all often get to read post-mortems but we seldom see the state of the developer when heading for the release. There is lot that can be discussed there, before the after release discussions kicks in to overshadow everything. So here I would like to share some random “wisdom” I gained walking this path. </p>
<p><a href="http://www.altdevblogaday.com/2012/01/04/game-pre-mortem/" class="more-link">Read more on Game Pre-Mortem&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Happy new year everybody! It seems we made it to 2012 successfully! Lets hope this will be a prosperous year for everybody, with many new things to learn and accomplish. </p>
<p>With my game entering the final phase of development, I think its time for a pre-mortem. We all often get to read post-mortems but we seldom see the state of the developer when heading for the release. There is lot that can be discussed there, before the after release discussions kicks in to overshadow everything. So here I would like to share some random “wisdom” I gained walking this path. </p>
<p>First of all let me provide some background. I started going by coding the game engine in August 2010. This was not starting from scratch as I started by modifying my old game engine Sylphis3D (you can poke around the source here: http://devnet.sylphis3d.com). This was all done in my spare time, with the only goal to see if it would be possible to run in on iPhone. It took a little while to succeed, an endeavor that required lots of code chopping. You see Sylphis3D is a fairly heavy engine for iPhone with its stencil shadows, per-pixel-lighting, normal mapping, etc. </p>
<p>It was around January 2011 when the engine was pretty much ticking with a new low-end renderer, when I got the idea of creating a simple 2D game with it. The game project was started and canceled a few months later because of problems with the graphics artist’s “productivity”. It was clearly my mistake of overlooking several indications of problems coming along. Which is my first lesson learned thought out this project. Never overlook problems and expect them to solve themselves automatically. It is not going to happen. It took a lot of time but it was not all to waste, since the work on the game engine was there to stay. And this involved huge rewrites that would anyway take lots of time. The changes included the migration to <a href="http://altdevblogaday.com/2011/06/23/from-python-to-lua/">a different scripting language</a>, the integration of two 2D physics engines (ended up with Box2D), new renderer, and lots of other minor things. As you understand there is little left that still relates to the original Sylphis3D game engine I wrote years ago.    </p>
<p>Later came the idea of a different game that started from a single gameplay element I thought of and that we later brainstormed along with my sister to a full themed game. This game was supposed to be done in 2-3 months, and here we are a few days in 2012 and the release will happen later this month&#8230; so classic. It turns out you can’t really estimate the human factor in months. Crippling bugs will happen, artists will not deliver on time, the (awesome) music composer and sound effects engineer might <a href="http://electronicartmetal.com/">get caught in an album release</a>, and so on. To all that add the fact that I always seem to forget the time cost of communication in all these. </p>
<p>Through all that we finally managed to be able to make a pre Christmas release, but at the last moment I pushed the big red cancel button. I thought that it might be better to release the game after Christmas despite the huge sales spike the AppStore sees. It occurred to me that with all the big names dropping prices, it would be pointless for a poor, self funded, indie game, to even consider a chance. I hope it was a wise decision. It certainly gives us more time to do tunings to the game progression with more beta testers logging many more hours of gameplay. </p>
<p>Below are the commandments to self for building an iPhone engine and game, feel free to embrace any of them:</p>
<ul>
<li>Go Lua. The iPhone can’t really handle a heavy scripting language like <a href="http://altdevblogaday.com/2011/06/23/from-python-to-lua/">Python</a> for example.</li>
<li>Even with Lua you should:
<ul>
<li>use incremental garbage collection, or even <a href="http://altdevblogaday.com/2011/07/23/predictable-garbage-collection-with-lua/">better a near-realtime gc</a></li>
<li>disable the use of undeclared globals or suffer pain debugging typos</li>
<li>create an object graph walker that will walk all globals, locals, upvalues, parameters, in order to be able to understand how your game is using memory and find leaks</li>
<li>create a custom memory allocator that can also gather statistics of where your memory is allocated. Lua makes tones of small allocations and memory fragmentation will hurt you bad</li>
<li>create a remote debugger for script code</li>
<li>always precompile the lua scripts in the release build, his will pose far less stress to the memory allocator.</li>
</ul>
</li>
<li>Always have in-place a logging facility to be able to <a href="http://altdevblogaday.com/2011/10/21/debugging-hard-to-reproduce-bugs/">replay game sessions</a></li>
<li>Don’t relay on the XCode build system to build/install/debug your game. Create scripts that deploy the game to the iPhone simulator (with rsync for example) and bring the turnaround time to 1-2 seconds when only script code is changed.</li>
<li>Build a solid asset pipeline. It should be possible to build the whole assets directory from the raw source files with a single command. </li>
<li>Use testflightapp.com. This will make the beta distribution as smooth as it gets, coupled with console and event logging send to you for every single session played.</li>
<li>Create a logging facility for key gameplay events (for example how much time does it take the player to clear the first level?). This should log to a remote server so you can collect data from your beta testers, and statistically analyse it later to extract useful information.</li>
<li>Always test the game at the lowest hardware you support. </li>
<li>Always try to watch new players play your game as you must keep in touch with the newbie perspective of your game. If you implement achievements for example at the end of your gamedev cycle you might find out that you create them to be a bit hard to achieve for a new player. </li>
<li>Premature optimization is the root of all evil, but you better assign a day a week or so for checking your “optimization corruption” and fixing it. Even if you don’t “fix” it, it will at least provide you with a more clear insight of how things are going which is a very good thing to have at the back of your head when coding. </li>
<li>And last but not least, don&#8217;t go out making a game without having read all the #altdevblogaday posts!</li>
</ul>
<p>I hope you will find the above canned experience useful for your development. I tried to provide them in almost single sentences for the purpose of forcing myself to extract the essence of my thoughts. I would really like to hear your single sentence kind of wisdom. </p>
<p><em>(edit: The game is now released and you can <a href="http://bit.ly/getpopcorny">get it here</a>)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/01/04/game-pre-mortem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging hard to reproduce bugs</title>
		<link>http://www.altdevblogaday.com/2011/10/21/debugging-hard-to-reproduce-bugs/</link>
		<comments>http://www.altdevblogaday.com/2011/10/21/debugging-hard-to-reproduce-bugs/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 15:07:38 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[replay]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=19048</guid>
		<description><![CDATA[<p>Debugging a game can by quite frustrating some times. What makes it so is the fact that in many cases reproducing a crash can be impossible. How can you pinpoint a memory corruption bug that causes a crash many frames after the incident? How can you replay the exact game until the point right before the crash, then a bit earlier, until you can see what went wrong? You can never play the same game twice and even single a frame lasting longer can have dramatic changes to the execution and the point of crash. </p>
<p><a href="http://www.altdevblogaday.com/2011/10/21/debugging-hard-to-reproduce-bugs/" class="more-link">Read more on Debugging hard to reproduce bugs&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Debugging a game can by quite frustrating some times. What makes it so is the fact that in many cases reproducing a crash can be impossible. How can you pinpoint a memory corruption bug that causes a crash many frames after the incident? How can you replay the exact game until the point right before the crash, then a bit earlier, until you can see what went wrong? You can never play the same game twice and even single a frame lasting longer can have dramatic changes to the execution and the point of crash. </p>
<p>The system I use for such cases is a full replay system. To be able to reproduce a bug, you must be able to replay the exact game. And by game I mean the whole session from execution start, all the way to the point of crash. To do so you must think of the game engine as a deterministic black box that has specific undeterministic inputs. If these underterministic inputs are logged, we can reproduce the exact execution any number of times we like. </p>
<p>The key here is to understand these inputs. The most obvious input is the user input, either that being the controller, or the mouse, or the keyboard. However these are not the only inputs that add randomness to the system. There are some more things that need to be consider as inputs in order to get to a full deterministic behaviour. If your game uses random numbers, the random number generator is an input. You must either log it, or use the same seed as you did in the crash. If your game queries the system time (of course it does!) then you have an other input! We are basically looking for ever point that the game engine reaches out of itself and get data, or it is fed data. </p>
<p>So the inputs are:</p>
<ul>
<li>User controller input</li>
<li>Random number generator</li>
<li>System time</li>
</ul>
<p>You mush hook a logging mechanism to all these inputs and record every single event. When it is time to replay a sequence, you start the game with a log replay mechanism at these hooks, in a way that all calls are answered with the same values as in the original play. This way you will follow the exact execution path that was followed when recording, but this time its like you know the future, and you can stop at any time before the crash to investigate. All these of course hold true in a single threaded environment. You must not allow the undeterminism of the OS’s scheduler get in the way. Tests should be done in a single thread lock down mode. If the crash is not reproducible at all in single thread runs, it is probably a multi-threaded race problem in the first place, and all I wish you is god help you! ;)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/10/21/debugging-hard-to-reproduce-bugs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Optimizing for the instruction cache</title>
		<link>http://www.altdevblogaday.com/2011/08/22/optimizing-for-the-instruction-cache/</link>
		<comments>http://www.altdevblogaday.com/2011/08/22/optimizing-for-the-instruction-cache/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 10:47:57 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[instruction cache]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=14755</guid>
		<description><![CDATA[<p>Everyone on the performance coding front knows it; <strong>the cache will make you or break you</strong>. There is no need to stress it any further that if your data doesn’t fit in the cache and you don’t make sure that your access patterns are such that allows for large cache hits, you are going to suffer from terrible performance.</p>
<p><a href="http://www.altdevblogaday.com/2011/08/22/optimizing-for-the-instruction-cache/" class="more-link">Read more on Optimizing for the instruction cache&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Everyone on the performance coding front knows it; <strong>the cache will make you or break you</strong>. There is no need to stress it any further that if your data doesn’t fit in the cache and you don’t make sure that your access patterns are such that allows for large cache hits, you are going to suffer from terrible performance.</p>
<p>One of the major conversion reasons to DOD <em>-that is an almost “hyped” term these days-</em> is that with DOD you get to focus on arranging the data in cache efficient ways. However we mostly focus on the data cache, and we tend to forget about the instruction cache.</p>
<p>The role of the instruction cache is to accelerate the fetching of instructions from the main memory. This is exactly like the way the data cache is used to accelerate the fetching of data. After all your code is data! The difference is that it is much harder to optimize for the instruction cache than it is to optimize for the data cache. This is logical if you consider that we can freely arrange data in any way we can device. We don’t have that freedom with code layout. This makes most of us turn away from the problem and ignore it, while focusing on the data cache and hope all will be fine. Others don’t bother at all or simply get as far as minimizing code size. However it turns out that doing cache misses for instruction fetching is as bad as regular cache misses. </p>
<p>Don’t get me wrong, minimizing code size helps a lot. And yes; inlining every function will eventually hurt you. So let’s suppose we have carefully minimized code size, what else is there that will affect the instruction cache performance? I always like to start with an example so lets take a look at the code below:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> updateEntities<span style="color: #009900;">&#40;</span>entity_t <span style="color: #339933;">*</span>entities<span style="color: #339933;">,</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> numOfEntities<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> numOfEntities <span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      entity_t <span style="color: #339933;">*</span>p <span style="color: #339933;">=</span> <span style="color: #339933;">&amp;</span>entities<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span>p<span style="color: #339933;">-&gt;</span>type<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> 
      <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">:</span>
        updateEntityA<span style="color: #009900;">&#40;</span>p<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">:</span>
        updateEntityB<span style="color: #009900;">&#40;</span>p<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Consider now that we have two kinds of entities, each with its own update function. The above code runs over an array of entities and depending on the entity type it calls the appropriate update function. Assuming that the entities of the two types are randomly distributed in the array, we can easily see that the execution will alternate in the functions <code>updateEntityA()</code> and <code>updateEntityB()</code>. Now suppose that only one function can fit in the instruction cache at once. <strong>This would mean that for every entity we will be loading instructions from the main memory with 50% probability.</strong>  If that sounds extreme, try thinking of it with ten different update functions alternating at random and running on a device like the iPhone. We can easily see that we can do better that that. What would happen if we grouped together entities of the same type? We could do that by having one array for every entity type, or by having a single array that we keep sorted on the entity type. This will change the code access patterns from:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">updateEntityA<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> updateEntityB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> updateEntityA<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> updateEntityC<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> updateEntityB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>…. … ..</pre></div></div>

<p>to:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">updateEntityA<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>….<span style="color: #339933;">,</span>updateEntityB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>….<span style="color: #339933;">,</span>updateEntityC<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>…..<span style="color: #339933;">,</span> … …</pre></div></div>

<p>Now the CPU will be able to update all entities of type A with the code resident in the instruction cache, then all entities of type B with the code in the instruction cache, and so on. <strong>We effectively reduced the cache misses from the order of the number of entities, to the order of the number of entity types.</strong> </p>
<p>The point to be taken from the above is that there is performance to be gained by <strong>organizing data in a way that when processed the code will follow similar paths</strong>; whether that is by following the same branches consistently, or by dispatching the same virtual method of a parent class with various custom implementations as children. Critical for performance code paths should be tested and optimized for the instruction cache along with the optimization for the data cache. </p>
<p>Optimizing for the instruction cache can be a difficult balancing act, and with the fact that we don’t have the ability to exactly layout the code, we must try to understand what the compiler is doing under the hood and do lots of trials and benchmarks. Inspecting the machine code emitted by the compiler is also crucial. Unroll loops and inline functions with caution. I usually do it incrementally while monitoring the performance. However keeping the code small is not going to help you if you run all over your codebase doing “random” stuff. <strong>Keep it in order, and you shall receive!</strong> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/08/22/optimizing-for-the-instruction-cache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Take your time (off)</title>
		<link>http://www.altdevblogaday.com/2011/08/07/take-your-time-off/</link>
		<comments>http://www.altdevblogaday.com/2011/08/07/take-your-time-off/#comments</comments>
		<pubDate>Sun, 07 Aug 2011 18:49:31 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[General Interest]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=13527</guid>
		<description><![CDATA[<p>Being an independent game developer is about doing your passion. It assumes that you possess the combined virtues of totally different specialities. You have to manage, command and execute all by yourself and your few equally ranked partners. It is like being an army where you get to be both the general and the troop (if there is no emergency that requires you to be the medic of course!). It’s an endeavor that can only fuel itself on your passion. <strong>However, passion does not come with capacity.</strong> Because as Daniel Kristiansen nicely puts it, an indie can easily be just a <a href="http://altdevblogaday.com/2011/07/15/indies-are-morons/">moron</a>. It is highly unlikely that someone can combine expertise at high quantities in:</p>
<p><a href="http://www.altdevblogaday.com/2011/08/07/take-your-time-off/" class="more-link">Read more on Take your time (off)&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Being an independent game developer is about doing your passion. It assumes that you possess the combined virtues of totally different specialities. You have to manage, command and execute all by yourself and your few equally ranked partners. It is like being an army where you get to be both the general and the troop (if there is no emergency that requires you to be the medic of course!). It’s an endeavor that can only fuel itself on your passion. <strong>However, passion does not come with capacity.</strong> Because as Daniel Kristiansen nicely puts it, an indie can easily be just a <a href="http://altdevblogaday.com/2011/07/15/indies-are-morons/">moron</a>. It is highly unlikely that someone can combine expertise at high quantities in:</p>
<ul>
<li>business plans</li>
<li>marketing plans</li>
<li>legal issues</li>
<li>accounting</li>
<li>management</li>
</ul>
<p>Please note that I intentionally left out all the creative talents. I assume that these are there! <strong>Programming, art, music, game design, etc are assumed to be cultured by the passion over the years.</strong> But all the above are well known, and many megabytes of digital ink where wasted about it on articles all over the internet. There is something more there, though. Something more elusive. Something that most of us get wrong. Something that when doesn’t result in hurting the game, it at least hurts the developer. That elusive matter is time management. </p>
<p>It is true that when you mix passion with all the above it can be hard to keep schedules. Time becomes the ultimate enemy. The thing that gets between you and your goal. Somehow time is never enough. You find yourself struggling between coding, managing, promoting, building frameworks, engines, websites&#8230; and it is then that you forget the value of time off. Personally, I can’t remember the last time I “virtually” finished work on Friday afternoon and got back to it on Monday morning. And what does that give me? Two days per week. So a six month project can be done in five. If you stop and think about it, does it make sense? I don’t think it does, <strong>but the distance from theory to practice is small in theory and large in practice!</strong> It turns out that giving yourself time off is one of the hardest things to do, requiring lots of discipline. Realising that finishing a project one month earlier is not going to happen by working weekends, is harder that it looks. Realising that that is going to hurt the project and you is ever harder. </p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/08/greekislands.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2011/08/greekislands-300x225.jpg" alt="" width="300" height="225" class="alignright size-medium wp-image-13536" /></a></p>
<p><strong>We have to understand that time off is part of the process.</strong> It is not a waste of time. It is a required ingredient in the recipe for success. Especially for us doing creative work. We can never be creative when we are consumed in a process. Creativity requires disengaging, stepping away and looking at things from completely wild directions. You can’t do that when you try to squeeze that code optimization at 3:00am in the morning because the next day you must manage the advertising documents. Sometimes you have to force yourself to stop working on the project and do something completely different. Do something completely different, let yourself escape. And “No”, going sailing while tapping the refresh on your twitter app does not count as escaping! </p>
<p>This post will go live on Sunday. I really hope it gets less that 10 views because on Sunday all of us have a life beyond gamedev. Even if that life is in football (which I hate!). I for sure will try to read only about Barcelona, Liverpool and other FCs this Sunday. Nothing about gamedev and preferably on a newspaper (in real paper) while lying on a sandy beach.  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/08/07/take-your-time-off/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Predictable garbage collection with Lua</title>
		<link>http://www.altdevblogaday.com/2011/07/23/predictable-garbage-collection-with-lua/</link>
		<comments>http://www.altdevblogaday.com/2011/07/23/predictable-garbage-collection-with-lua/#comments</comments>
		<pubDate>Sat, 23 Jul 2011 00:00:45 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=11901</guid>
		<description><![CDATA[<p><em>[This article can also be read on my <a href="http://kalogirou.net/">blog</a>]</em></p>
<p>In one of my <a href="http://altdevblogaday.com/2011/06/23/from-python-to-lua/">previous posts</a> I talked about how you can make the Lua garbage collector (GC) more predictable in running time. This is a virtue that is highly valued in a GC used in games where you don&#8217;t have the luxury of going over you frame time. In that post I described a solution to the problem which works fine most of the time, leaving little space for garbage collection times that will hurt the framerate.  However I ended that post with a promise to provide a better solution and in this post, I deliver.</p>
<p><a href="http://www.altdevblogaday.com/2011/07/23/predictable-garbage-collection-with-lua/" class="more-link">Read more on Predictable garbage collection with Lua&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><em>[This article can also be read on my <a href="http://kalogirou.net/">blog</a>]</em></p>
<p>In one of my <a href="http://altdevblogaday.com/2011/06/23/from-python-to-lua/">previous posts</a> I talked about how you can make the Lua garbage collector (GC) more predictable in running time. This is a virtue that is highly valued in a GC used in games where you don&#8217;t have the luxury of going over you frame time. In that post I described a solution to the problem which works fine most of the time, leaving little space for garbage collection times that will hurt the framerate.  However I ended that post with a promise to provide a better solution and in this post, I deliver.</p>
<p>The ideal situation would be to have the GC run for a specific amount of time. This way the game engine will be able to assign exact CPU time to the GC based on the situation. For example one strategy would be to give a constant amount of time to the GC per frame. Lets say 2ms every frame. Or it can be more clever and take into consideration other parameters, like the amount of time it took to do the actual frame. Is there enough time left for this frame? If there is, spend some for GC, if not, hold it for the next frame when things might not be too tight. Other parameters can be memory thresholds, memory warnings, etc.</p>
<p>All of the above depend on a GC that can be instructed to run for an exact amount of time. This kind of GC is what we call a realtime GC. And Lua does not have one. However it turns out that we can get very close to realtime with minor changes to the Lua GC. </p>
<p>The patch below modifies the behavior of the GC in the way we need it:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;"><span style="color: #888822;">--- a/src/lgc.c</span>
<span style="color: #888822;">+++ b/src/lgc.c</span>
<span style="color: #440088;">@@ -609,15 +617,14 @@ static l_mem singlestep <span style="">&#40;</span>lua_State *L<span style="">&#41;</span> <span style="">&#123;</span></span>
&nbsp;
 void luaC_step <span style="">&#40;</span>lua_State *L<span style="">&#41;</span> <span style="">&#123;</span>
   global_State *g = G<span style="">&#40;</span>L<span style="">&#41;</span>;
<span style="color: #991111;">-  l_mem lim = <span style="">&#40;</span>GCSTEPSIZE/<span style="">100</span><span style="">&#41;</span> * g-&gt;gcstepmul;</span>
<span style="color: #991111;">-  if <span style="">&#40;</span>lim == 0<span style="">&#41;</span></span>
<span style="color: #991111;">-    lim = <span style="">&#40;</span>MAX_LUMEM-<span style="">1</span><span style="">&#41;</span>/<span style="">2</span>;  /* no limit */</span>
   g-&gt;gcdept += g-&gt;totalbytes - g-&gt;GCthreshold;
<span style="color: #00b000;">+  double start = getTime<span style="">&#40;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+  double end = start + <span style="">&#40;</span>double<span style="">&#41;</span>g-&gt;gcstepmul / <span style="">1000.0</span>;  </span>
   do <span style="">&#123;</span>
<span style="color: #991111;">-    lim -= singlestep<span style="">&#40;</span>L<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+    singlestep<span style="">&#40;</span>L<span style="">&#41;</span>;</span>
     if <span style="">&#40;</span>g-&gt;gcstate == GCSpause<span style="">&#41;</span>
       break;
<span style="color: #991111;">-  <span style="">&#125;</span> while <span style="">&#40;</span>lim &gt; <span style="">0</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+  <span style="">&#125;</span> while <span style="">&#40;</span>getTime<span style="">&#40;</span><span style="">&#41;</span> &lt; end<span style="">&#41;</span> <span style="">&#123;</span></span>
     if <span style="">&#40;</span>g-&gt;gcdept GCthreshold = g-&gt;totalbytes + GCSTEPSIZE;  /* - lim/g-&gt;gcstepmul;*/</pre></div></div>

<p>The only missing part from the patch above is the <code>getTime()</code> that can be something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">double</span> getTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">struct</span> timeval tp<span style="color: #339933;">;</span>
    gettimeofday<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>tp<span style="color: #339933;">,</span> NULL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>tp.<span style="color: #202020;">tv_sec</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> tp.<span style="color: #202020;">tv_usec</span><span style="color: #339933;">/</span><span style="color:#800080;">1000000.0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I guess however that everyone will want to use their own time function. </p>
<p>The patch modifies the code so that is stops based on a time limit and not based on a calculated target memory amount to be freed. The simplicity of the patch also comes from the fact that we &#8220;reuse&#8221; the STEPMUL parameter that is no longer used to carry the aggressiveness of the GC. We now use it to hold the exact duration we want the GC to run in milliseconds. So the usage will be this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">lua_gc<span style="color: #009900;">&#40;</span>L<span style="color: #339933;">,</span> LUA_GCSETSTEPMUL<span style="color: #339933;">,</span> gcMilliSeconds<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
lua_gc<span style="color: #009900;">&#40;</span>L<span style="color: #339933;">,</span> LUA_GCSTEP<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The above code will run the GC for <code>gcMilliSeconds</code> ms. This way you will never be out of your frame time budget, because the garbage collection took a little longer to execute. Problem solved!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/07/23/predictable-garbage-collection-with-lua/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keep your mallocs close, and your related mallocs closer</title>
		<link>http://www.altdevblogaday.com/2011/07/08/keep-your-mallocs-close-and-your-related-mallocs-closer/</link>
		<comments>http://www.altdevblogaday.com/2011/07/08/keep-your-mallocs-close-and-your-related-mallocs-closer/#comments</comments>
		<pubDate>Fri, 08 Jul 2011 06:37:11 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[memory management]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=10597</guid>
		<description><![CDATA[<p>As you probably know, script languages (most of them at least, like Python, Lua, etc) have the tendency to make a huge amount of small allocations on the heap. Almost everything is stored on the heap, and if you care for performance, you start feeling homesick about your beloved C stack! Anyway, nothing comes for free, and scripting languages have to take something from you in exchange for all the goods it gives you back. <b>So the best you can do is make sure that you have the best memory allocator for the job</b>.</p>
<p><a href="http://www.altdevblogaday.com/2011/07/08/keep-your-mallocs-close-and-your-related-mallocs-closer/" class="more-link">Read more on Keep your mallocs close, and your related mallocs closer&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>As you probably know, script languages (most of them at least, like Python, Lua, etc) have the tendency to make a huge amount of small allocations on the heap. Almost everything is stored on the heap, and if you care for performance, you start feeling homesick about your beloved C stack! Anyway, nothing comes for free, and scripting languages have to take something from you in exchange for all the goods it gives you back. <b>So the best you can do is make sure that you have the best memory allocator for the job</b>.</p>
<p>
Doing too many small allocations and releases on the heap can create memory fragmentation, along with all the evil that comes with this. The common approach is to create a specialized memory allocator that serves small and constant in size blocks of memory to the scripting language, taken from a bigger chunk of memory reserved from the system. This is a common in all “realtime” and intencive applications like games, and something I did many times to gain performance.
</p>
<h2>Can’t beat the standard malloc</h2>
<p>What I discovered with my latest attempt was that it has gotten quite hard to beat the GNU implementation of malloc(). Something that used to be easy in the past when you focused on a specialized case (e.g. small blocks of memory). Not that you can’t do better if you try hard, but at this point the malloc() implementation is already super-fast for 99.9% of applications on the desktop. Rest asured that you will not be able to do much better. However that is not the case for embedded devices that don’t share the same virtual memory benefits as the desktop computers.
</p>
<p>My hand tuned specialized memory allocator for small blocks of memory ( &lt;= 256bytes ) was not able to be more that 1% faster than the native malloc() on the OS X 10.6. And its hard to fragment 8GB of RAM and see huge problems.  However on the iPhone the same allocator was twice as fast as the native malloc() ! Since the target was from the begining the iPhone that seemed like big win! However when I set up a small benchmark in the scripting environment that did some allocations of game engine objects and released then again in various patterns, the results were disappointing. The gain from using my specialized (and twice as fast) allocator resulted in improvement of about 5% in execution speed in a memory intensive benchmark. And at some tests even slower! That was odd and most of all not good!</p>
<h2>Why I was failing</h2>
<p>After some inspections and tests that made the case of me doing something really stupid less probable, I narrowed down the cause.</p>
<p>In most cases of using a scripting language you have some classes defined in C++ that you instatiate in the scripting language. Take for example a 3D vector class “CVector3″ defined in C++. When you instatiate this in the script language you get two allocations. One in the scripting language that allocates the “proxy” object and one in the C++ environment. When giving a new allocator to the scripting language to do its allocations you only “optimize” the first allocation. The one in C++ still goes through the system default allocator.</p>
<p>And since you optimize half of the allocations you expect to have half the performance boost… well… wrong. It turns out that you can even be slower this way. The secret here is the CPU cache. By doing the above, you have two memory blocks that are usually accessed together, but are far apart in memory. This can really hurt performance badly on a device with slow memory and small cache, like the iPhone.</p>
<h2>The solution</h2>
<p>The solution was of course to use the same allocator on the C++ side by overriding the “new” operator of the class. This made the blocks of memory allocated on the script side to be close to the block allocated on the C++ side. This way access to the object only involves accessing one part of the memory and giving nice cache hits. Performance up by 30%, which was nice and expected.</p>
<p>One other interesting thing that I found from this is that, on the iPhone, if I just override the “new” operator of a class and make it allocate the memory with plain malloc() and don’t use my allocator at all, the system is again faster!</p>
<p>This is probably from the fact that “new” does not go through plain malloc() (didn’t bother to check) as the scripting language environment does. So the allocated blocks end up in different arenas at different parts of the memory, with the result of losing performance for the same reason as above!</p>
<p>So, keep your related allocations close together when crossing the language barrier!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/07/08/keep-your-mallocs-close-and-your-related-mallocs-closer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From Python to Lua</title>
		<link>http://www.altdevblogaday.com/2011/06/23/from-python-to-lua/</link>
		<comments>http://www.altdevblogaday.com/2011/06/23/from-python-to-lua/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 00:19:18 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=8842</guid>
		<description><![CDATA[<div>All game developers, sooner or later, learn to appreciate scripting languages. That magical thing that allows for <del>letting others do your job</del>, better scaling of the team, strengthening the game code/engine separation, sandboxing, faster prototyping of ideas, fault isolation, easy parametrization, etc. Every game has to be somehow data driven to be manageable, and stopping at simple configuration files, with many different custom parsers, without going the extra mile of adding a full scripting language, is 90% of the times a bad design choice.&#160;
</div>
<p><a href="http://www.altdevblogaday.com/2011/06/23/from-python-to-lua/" class="more-link">Read more on From Python to Lua&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<div>All game developers, sooner or later, learn to appreciate scripting languages. That magical thing that allows for <del>letting others do your job</del>, better scaling of the team, strengthening the game code/engine separation, sandboxing, faster prototyping of ideas, fault isolation, easy parametrization, etc. Every game has to be somehow data driven to be manageable, and stopping at simple configuration files, with many different custom parsers, without going the extra mile of adding a full scripting language, is 90% of the times a bad design choice.&nbsp;</p>
<p>Today the developer can choose from a large variety of scripting languages, or even go crazy and implement one on his own. It happens that the most favored language for game developers is <a href="http://www.lua.org/">Lua</a>. Its easy to understand why Lua is the favorite but other options are used as well. For example Python and the lately upcoming force of  Javascript.</p>
<p>Here I would like to share some of my experience of moving a game engine from Python to Lua.</p>
<h2>Transition</h2>
<p>My first experience with embedding a scripting language was with Python. More specifically with <a href="http://www.stackless.com/">Stackless Python</a>. When I started implementing my <a href="http://devnet.sylphis3d.com/">game engine</a> I chose Stackless Python mainly because it was my language of choice for all development when not doing it in C++, and due to the support for tasklets. However the last year I got into porting the engine into the iOS platform and actually “pulling” it down in graphical features in order for it to run efficiently on the iPhone. One of the major changes was the transition from Python to Lua.</p>
<h2>Better Memory Management</h2>
<p>Python is a very powerful language will many bells and whistles and has served me well on the “full” version of Sylphis3D. However on the mobile platform the language was making things hard on performance. One of the major problems I was facing was the memory management. For those that don’t know, Python uses reference counting for memory management, coupled with a garbage collector (GC). What reference counting means, is that Python keeps track of the number of references an object has, and when that goes down to zero the object is no longer needed. That works well until you have two objects referencing each other, or forming a cycle of references. The reference count will never go to zero for those objects even if the cycle is not connected to the main object reference graph. So this is work for the GC who finds these lost clusters of objects by waking all reachable objects.</p>
<p>The problem with games is that we have to be fast. Fast and predictable. If you want the game to run at 60 frames per second, it means that you must do all the work in under 16.7ms. Whenever you miss that deadline -even by little- you have to wait for the next screen refresh. The worst thing that can happen is to cross that time limit sporadically and in a random pattern. This will result in motion shuttering, and it is most likely to give the user a better experience by going down to 30 FPS and sticking to it. So how does Python’s memory management system fits into the above picture? &#8211; On mobile&#8230; not so well&#8230;</p>
<p>The reference counting is completely predictable and consistent. An object will be released exactly the moment it is no longer needed. We have predictable and immediate release of resources. This is ideal for game development as long as you don’t create cycles. You have to be careful not to create cycles and if you do, make sure you break them. This however requires the scripter (which can be a non programmer) to be aware of implementation details. The ugly truth is that reference cycles will happen, and when they do it’s hard to find them. You must have a garbage collector, and Python does. However Python’s GC has a mind of his own and of course does not know of our 16.7ms time limit.</p>
<p>Python allows you to tune the GC, you can turn it on and off, but you can’t make it keep the processing low. When it will decide to run you are most likely to skip frames. Very bad.</p>
<p>On a desktop however you can easily get away with the following things combined:</p>
<ol>
<li>Reference counting</li>
<li>Relaxed memory amount constrains</li>
<li>Explicitly calling the GC at key moments</li>
</ol>
<p>Actually this was what I was doing on the desktop version. It turns out that since most of the deallocation of memory will be handled by the reference counting system, and that system is not too constrained on memory for possible reference cycles to be a problem, we can get away with manually calling the GC at key moments (e.g. before level changing). You might get a bit heavier on memory usage, but this is small price to pay for having a predictable frame length.</p>
<p>But on the iPhone you don’t get relaxed memory amount constrains. Memory is tight. There is no page file. You either turn the GC on and get frame skips when it runs, or you run it at least when you get a memory warning. In practise this doesn’t work out well. Not as well as I want it to at least. Which lead us to the decision to try out Lua.</p>
<p>Lua needs no introduction to game developers as it is well known for being lightweight, easy to embed and&#8230; featuring an incremental GC! This was the major push for adopting Lua in the mobile version of the engine. Having an incremental GC basically means that you can spread a full garbage collection cycle over many frames. This way you can keep it under a specific time budget. All you have to do is disable the automatic GC like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">lua_gc<span style="color: #009900;">&#40;</span>L<span style="color: #339933;">,</span> LUA_GCCOLLECT<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>and then do a:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">lua_gc<span style="color: #009900;">&#40;</span>L<span style="color: #339933;">,</span> LUA_GCSTEP<span style="color: #339933;">,</span> <span style="color: #0000dd;">200</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>at the end of every frame to do a single garbage collection step. Depending of how big the parameter you pass to LUA_GCSTEP you will need more or less “steps” to complete a full garbage collection cycle. The choice of the step parameter however is left for the village magician to determine! To quote the Lua documentation:</p>
<blockquote><p>&#8230;larger values mean more steps <strong>in a non-specified way</strong>.</p>
</blockquote>
<p>So you have to play around with the variable to find the sweet-spot that does not use up too much of your precious frame time, and also keeps the garbage generated from the frame to rational amounts. This can be hard, and at the end we get something close to what I had with Python and full GC on, as at some point even a single GC step will spike up to 7ms. And that is logical since the Lua GC has far more work to do that the Python’s one, as it is not backed by reference counting.</p>
<p>But the swich to Lua was not in vain since the problem can almost completely go away by dropping the GCSTEP parameter down to zero and calling the GC repeatedly until a specific time frame expires. Something that looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">double</span> endTime <span style="color: #339933;">=</span> getTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color:#800080;">0.001</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
  lua_gc<span style="color: #009900;">&#40;</span>L<span style="color: #339933;">,</span> LUA_GCSTEP<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> getTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> endTime <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>With the above code we almost get it to run as we want it. However notice that the above code does not turn the Lua GC into a realtime GC. The above will run the GC for a minimum of 1ms. Every frame the GC will takeup _at least_ 1ms, even when there is no need to. That doesn’t feel really good doing on a device running on batteries. Apart from that we have an implementation that will hardly skip a frame due to the GC. And that is a win over the Python version.</p>
<h2>Closing words</h2>
<p>In general the overall transition can be called a success and it was worth the effort. I now have an engine that has much smaller footprint in memory size, more consistent behaviour and I got to keep all the good things. Here someone can raise several arguments like the loss of bitwise operations, native integer number support, even the count from one in arrays. But in the end as it turns out, it is not that much of a problem after all. The true power of Lua lies in its flexibility. The language is so open-ended that allows you to easily mimic any other language contruct (I still do miss the powerful concept of <a href="http://www.stackless.com/wiki/Channels">channels</a> in Python though).</p>
<p>Also the simplicity of the Lua implementation as an interpreter can allow for easy understanding of the inner workings and makes it possible to even make changes right away. For example I was able to improve upon the garbage collection solution I laid out earlier so that I have an almost “realtime” GC, with steps constrained in duration, just by changing a few lines of code in the interpreter&#8230;</p>
<p>&#8230;I will save that for an other post though.</p>
</div>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/06/23/from-python-to-lua/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 1.749 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-17 03:44:41 -->
<!-- Compression = gzip -->
