<?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>voyce</title>
	<atom:link href="http://www.voyce.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.voyce.com</link>
	<description>Programming and debugging tidbits</description>
	<lastBuildDate>Sun, 15 Jan 2012 13:10:46 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>30 years ago at CES&#8230;</title>
		<link>http://www.voyce.com/index.php/2012/01/15/30-years-ago-at-ces/</link>
		<comments>http://www.voyce.com/index.php/2012/01/15/30-years-ago-at-ces/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 13:10:46 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Gaming]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[retro]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1455</guid>
		<description><![CDATA[How different did things look at CES 30 years ago? Very.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.voyce.com/wp-content/uploads/2012/01/candvg_logo.png"><img src="http://www.voyce.com/wp-content/uploads/2012/01/candvg_logo.png" alt="candvg_logo" title="candvg_logo" width="200" height="167" class="alignleft size-full wp-image-1456" /></a>The other day while I was looking through some of my ancient copies of Computer and Video Games magazine (&#8221;the first fun computer magazine!&#8221;) I discovered some coverage of the 1982 Consumer Electronics Show. It&#8217;s such a contrast to today&#8217;s shiny, immaculately produced, PR-fest that I couldn&#8217;t help but scan it in for everyone to see.<br />
<span id="more-1455"></span><br />
To get things into context, this is 1982: The state of the art in home computing is ZX81s sold in kit form, Vic20s, PET 8K, Tandy TRS-80. But as the magazine says, home computing&#8217;s not where it&#8217;s at in the US:</p>
<blockquote><p>
&#8220;The 25th Consumer Electronics Show&#8230; showed very clearly that one thing continues to dominate the media and electronics business in the USA. This is not the personal computer &#8211; which seems to be causing far more interest in Europe than in America &#8211; but the video game.&#8221;
</p></blockquote>
<p>So while in the UK we were busy typing in listings from games magazines, in the US Atari, Mattel were creating ready-to-play cartridge based games.</p>
<p><a href="http://www.voyce.com/wp-content/uploads/2012/01/frogger_small.png"><img src="http://www.voyce.com/wp-content/uploads/2012/01/frogger_small.png" alt="frogger_small" title="frogger_small" width="195" height="250" class="alignright size-full wp-image-1459" /></a>Getting compelling press coverage was made difficult by the fact that it was impossible to get decent screen shots. Think how much of the pages in modern games mags are covered with glossy, full-colour, high-resolution screen shots. Without these, you&#8217;re left with nothing but words to describe these visual wonders. Luckily, you didn&#8217;t need much of a vocabulary to describe the games of the time; they were either based on existing analogue games, or they were derived from the small pool of original video game ideas:</p>
<blockquote><p>
&#8220;Munchie, which is similar to PacMan&#8221; &#8230; &#8220;Cosmic Raiders is a fast-action Defender style games&#8221; &#8230; &#8220;Solar Conqueror is an Asteroids game.&#8221;
</p></blockquote>
<p>Of course, some of this &#8220;re-purposing&#8221; was pukka; Coleco made table-top versions of things like PacMan, Donkey Kong, and Frogger (image above). You can imagine how faithful these arcade conversions actually were&#8230;</p>
<p>We&#8217;ve made quite some progress in the last 30 years, both in terms of game mechanics and graphics. It&#8217;s best summed up by 2 images, I&#8217;m sure you can guess which is from 1982, and which from 2012?<br />
<a href="http://www.voyce.com/wp-content/uploads/2012/01/frogbog.png"><img src="http://www.voyce.com/wp-content/uploads/2012/01/frogbog.png" alt="frogbog" title="frogbog" width="269" height="200" class="alignnone size-full wp-image-1463" /></a><a href="http://www.voyce.com/wp-content/uploads/2012/01/zeldahd.png"><img src="http://www.voyce.com/wp-content/uploads/2012/01/zeldahd.png" alt="zeldahd" title="zeldahd" width="356" height="200" class="alignnone size-full wp-image-1464" /></a></p>
<p>Click through these images for the full scans on flickr.</p>
<table>
<tr>
<td>
<a href="http://www.flickr.com/photos/ianvoyce/6700584931/" title="C&amp;VG March 1982 cover by ianvoyce, on Flickr"><img src="http://farm8.staticflickr.com/7003/6700584931_2d8a0a4c60_t.jpg" width="71" height="100" alt="C&amp;VG March 1982 cover"></a></td>
<td>
<a href="http://www.flickr.com/photos/ianvoyce/6700587409/" title="C&amp;VG CES 1982 coverage 1 by ianvoyce, on Flickr"><img src="http://farm8.staticflickr.com/7174/6700587409_65b6a1a129_t.jpg" width="71" height="100" alt="C&amp;VG CES 1982 coverage 1"></a></td>
<td>
<a href="http://www.flickr.com/photos/ianvoyce/6700589945/" title="C&amp;VG CES 1982 coverage 2 by ianvoyce, on Flickr"><img src="http://farm8.staticflickr.com/7011/6700589945_4bc78d3843_t.jpg" width="71" height="100" alt="C&amp;VG CES 1982 coverage 2"></a></td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2012/01/15/30-years-ago-at-ces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tax Avoidance 2.0</title>
		<link>http://www.voyce.com/index.php/2012/01/06/tax-avoidance-2-0/</link>
		<comments>http://www.voyce.com/index.php/2012/01/06/tax-avoidance-2-0/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 00:05:21 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Finance]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[facebook]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1430</guid>
		<description><![CDATA[Tax avoidance is rife in the new (and existing) generation of tech companies.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.voyce.com/wp-content/uploads/2012/01/dislike.png"><img src="http://www.voyce.com/wp-content/uploads/2012/01/dislike.png" alt="dislike" title="dislike" width="210" height="95" class="alignleft size-full wp-image-1443" /></a>Warning: This is a bit off-topic for my blog, but I had to write it and get it off my chest. </p>
<p>In these times of financial woe, people love to complain about all the big, nasty, faceless companies avoiding paying tax. They inevitably moan about it on Facebook, Google and Twitter (and sometimes even do something about it in the real, physical, world). But what about those companies themselves? The Web 2.0 behemoths are now some of the largest companies in the world, and they&#8217;ve decided &#8211; just like the evil old companies &#8211; that they don&#8217;t like paying all that tax. Don&#8217;t be evil&#8230; and don&#8217;t pay any tax if you can help it. But how do they do it?<br />
<span id="more-1430"></span></p>
<h2>The Numbers</h2>
<p>An Irish Times <a href="http://www.irishtimes.com/newspaper/finance/2011/1223/1224309416349.html">newspaper article</a> caught my eye the other day. It discusses the rapid growth of Facebook&#8217;s Dublin operation in 2010, whose accounts have just been published (as they must be by law, despite FB&#8217;s apparent reluctance). The headline figure is that:</p>
<blockquote><p>
[Revenue] is up from €15.2 million to <b>€229.1 million</b>
</p></blockquote>
<p>That&#8217;s a pretty significant increase! But that&#8217;s only revenue, how much of it was left over as profit?</p>
<blockquote><p>
Facebook Ireland generated a pretax profit of <b>€1.9 million</b>
</p></blockquote>
<p>What?! Where did the other €227 million go? </p>
<p>According to the article it mostly disappeared into a mysterious black hole known as &#8220;administrative expenses&#8221;:</p>
<blockquote><p>
Administrative expenses increased &#8230; to €221.6 million as a result of &#8230; royalties paid to other Facebook entities for services provided during the year.
</p></blockquote>
<h2>How do they do that?</h2>
<p>Is it me or does that sound suspicious? Well, it should do, because it is. </p>
<p>It turns out that Ireland&#8217;s significantly lower rate of corporation tax (12% vs 26% in the UK, and one of the lowest in the world) isn&#8217;t the only reason why companies like Facebook, <a href="http://www.guardian.co.uk/business/ireland-business-blog-with-lisa-ocarroll/2011/mar/24/google-ireland-tax-reasons-bermuda">Google et al move there</a>. There&#8217;s also the very useful fact that, unlike most developed economies, Ireland chose not to introduce any legislation to prevent companies siphoning off their revenue to low-or-no-tax regimes like the Cayman islands or Bermuda.</p>
<p>So that&#8217;s where the &#8220;missing&#8221; €221 million has ended up: it&#8217;s been paid from the Irish part of the business to the tax-haven subsidiary, leaving only a small amount subject to corporation tax in Ireland. This practise is known in tax circles as the &#8220;double Irish&#8221;, and it (along with its Dutch equivalent) seems to be fairly widely used and well understood, even having its own <a href="http://en.wikipedia.org/wiki/Double_Irish_arrangement">wikipedia entry</a>. Of course Facebook now funnels as much as possible of the revenue from the UK (its second biggest market) through the Ireland operation to get the most out of this arrangement. That explains the large increase in the numbers since last year. </p>
<p>There are many high-profile tech companies that have Dublin operations and may be avoiding tax in this way, including:</p>
<ul>
<li>Facebook</li>
<li>Twitter</li>
<li>LinkedIn</li>
<li>Google</li>
<li>Microsoft</li>
<li>Oracle</li>
</ul>
<p>That&#8217;s quite a roll call.</p>
<h2>The Result</h2>
<p>The result of all these shenanigans for Facebook? It pays a ridiculously small effective tax rate of less than 1%, even better than <a href="http://www.businessweek.com/technology/google-tax-cut/google-terminal.html">Google&#8217;s 2.4% rate</a>.  And given Ireland&#8217;s <a href="http://news.businessweek.com/article.asp?documentKey=1376-LXBO661A1I4H01-4A40DCQ22ID111VEL291CSBQT6">current economic state</a> I can&#8217;t imagine their government will be introducing more restrictive tax legislation any time soon in an attempt to crack down on it. They can&#8217;t risk these big companies abandoning their new homes in Dublin&#8217;s <a href="http://www.irishtimes.com/newspaper/finance/2011/0930/1224305000761.html">Silicon Dock</a>.</p>
<p>Of course, you should feel free to &#8216;like&#8217; this blog post on Facebook, after all, what will it cost you?</p>
<p>(* Disclaimer: These are solely my opinions, not those of my employer or anyone else).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2012/01/06/tax-avoidance-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Looking back at 2011</title>
		<link>http://www.voyce.com/index.php/2012/01/04/looking-back-at-2011/</link>
		<comments>http://www.voyce.com/index.php/2012/01/04/looking-back-at-2011/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 23:07:47 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[2011]]></category>
		<category><![CDATA[kinect]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WinDbg]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1408</guid>
		<description><![CDATA[A quick look back at some of the stuff I've been doing this year.]]></description>
			<content:encoded><![CDATA[<p>Well, we&#8217;re a few days into 2012 and no armageddon yet, so it&#8217;s probably safe to take a quick glance back over our shoulder at some of the technical stuff that&#8217;s flashed past in the preceding 12 months.<br />
<span id="more-1408"></span></p>
<h2>Work: Using F# in anger</h2>
<p>During working hours (and sometimes beyond) I&#8217;ve been developing a large project using lots of F#, a little bit of C# and a bit too much XAML. It&#8217;s quite an interesting mix, with technologies that have a vastly different outlook on life: F# with it&#8217;s strong, compile-time type checking and XAML with its, err, not-so-strong type checking. In fact, XAML and WPF play so fast and loose with types, that errors in the binding mechanism only happen at run-time and are almost always eaten silently. As you can imagine, this makes for some fun debugging. All I can say is thank goodness for <a href="http://snoopwpf.codeplex.com/">Snoop</a>.</p>
<p>We have a quite a substantial amount of ViewModel code in F# (tens of thousands of lines), much of it using <code>Async</code> to allow us to create responsive UIs without requiring tons of boilerplate code. Generally it works nicely, but I do have some concerns about the amount of thread hopping going on, and how that will affect performance. Especially as we break things down into pretty small pieces of functionality, sometimes just a few simple operations, and each is run on the thread pool. I don&#8217;t have any concrete figures to go on here, and I&#8217;m hoping we don&#8217;t end up in a situation where we sacrifice user productivity for developer productivity. Time (and perfmon) will tell.</p>
<h3>Debugging</h3>
<p>I&#8217;ve done less hardcore WinDbg stuff this year. In fact, a couple of times I&#8217;ve been guilty of jumping in with the debugger where it probably would&#8217;ve been more effective to take a high-level look first. A case of having a debugger-shaped hammer, and everything looking like a nail.</p>
<h3>Moving to 64bit</h3>
<p>A very positive thing that happend this year was the move to 64-bit Windows 7 for development at work, meaning that Visual Studio actually stays up without crashing for more than an hour. Previously I&#8217;d been having a terrible time: the combination of a couple of large-ish F# projects and 32-bit XP caused frequent VS out-of-memory errors, which was very frustrating. Luckily the move to Windows 7 has resolved it, and I can even run more than a handful of apps at the same time; what a luxury. </p>
<h2>Home: iOS</h2>
<p>After a long day at work, I finally get to go home, put the kids to bed and then my feet up, and break-out Xcode for a bit of iOS hacking. This year I&#8217;ve been feeling like I&#8217;m finally getting my head around some of the things that are fundamental in iOS development; from Objective-C concepts like release/retain semantics to iOS specifics, view controllers, table views etc. Previously I&#8217;ve been guilty of some copy-and-paste coding, mostly because it&#8217;s pretty slow going getting up to speed with new tech (and the myriad iOS APIs) when you&#8217;re only getting to do it for a few hours while knackered after work. Well, that&#8217;s my excuse anyway.</p>
<p>I&#8217;ve been trying to finish off some of the apps that I&#8217;ve started, but not shipped. I tend to procrastinate a bit (massive understatement), and of course things aren&#8217;t helped by the development &#8216;fat tail&#8217;, where the last 20% &#8211; polishing and getting things &#8216;just right&#8217; &#8211; takes at least 80% of the time. My 2010 post on <a href="http://www.voyce.com/index.php/2010/04/10/creating-an-ipad-flip-clock-with-core-animation/">Core Animation flip clocks</a> continues to get a lot of traffic, and I finally bit the bullet and posted a (free!) <a href="http://itunes.com/apps/flipclock">app</a> that uses it and it&#8217;s getting a lot of downloads, which is nice. I also had a look at iAd, which I&#8217;ll reserve judgement on for the time being, at the minute it&#8217;s not looking particularly lucrative&#8230;</p>
<p>As well as iOS stuff, I also took a look at OpenGL. I tend to do this every now and again, each time dipping in a little further and understanding a bit more. This time round it was looking at shaders (in OpenGL ES 2.0) and integrating with <a href="http://www.voyce.com/index.php/2011/11/18/creating-a-physics-based-opengl-ios-app/">Bullet physics</a>. My learning was certainly helped by this excellent <a href="http://arcsynthesis.org/gltut/">Learning Modern 3D Graphics Programming</a> tutorial.</p>
<h3>Kinect and F#</h3>
<p>Also while at home I finally got around to setting-up by my Kinect to do a bit of F# hacking. In the end I didn&#8217;t produce <a href="http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/">very much</a>, but it was pretty good fun anyway.</p>
<h2>Bring on 2012</h2>
<p>So, to sum it up: more of the same really, I guess. Although this year there&#8217;s definitely been a bit more of a focus on UI development, in both WPF and iOS, which I&#8217;ve been enjoying. It does tend to feel a bit schizophrenic, switching between technologies and platforms at the end of the working day. It can be interesting to identify the common themes and significant differences in the two approaches to GUI development. </p>
<p>This year I&#8217;m hoping to make my blogging a bit more regular, but who knows if I&#8217;ll be able to stick to it&#8230; If there&#8217;s anything you&#8217;d particularly like me to focus on, feel free to leave a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2012/01/04/looking-back-at-2011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Drawing animated shapes and text in Core Animation layers</title>
		<link>http://www.voyce.com/index.php/2011/12/03/drawing-animated-shapes-and-text-in-core-animation-layers/</link>
		<comments>http://www.voyce.com/index.php/2011/12/03/drawing-animated-shapes-and-text-in-core-animation-layers/#comments</comments>
		<pubDate>Sat, 03 Dec 2011 12:30:01 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Mac]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[CALayer]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[Core Graphics]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1370</guid>
		<description><![CDATA[Using paths and text to simple create composite animated graphics with Core Graphics, UIKit and Core Animation.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_1399" class="wp-caption alignleft" style="width: 148px"><a href="http://www.voyce.com/wp-content/uploads/2011/12/star_hello.png"><img src="http://www.voyce.com/wp-content/uploads/2011/12/star_hello.png" alt="Star and text" title="star_hello" width="138" height="149" class="size-full wp-image-1399" /></a><p class="wp-caption-text">Star and text</p></div>The other day I was overcome by the desire to create an animated start-burst, price-tag type graphic with iOS. Time to break out some Core Graphics and Core Animation code. On the way to getting it going, I came across some interesting gotchas, which I thought it&#8217;d be useful to talk about here.<br />
<span id="more-1370"></span></p>
<h3>Drawing the basic shape</h3>
<p>The first step is to draw the &#8217;star&#8217; shape. I decided to create a re-usable path, although at the minute I&#8217;m actually only drawing it once, so the benefits are limited. Doing this involves using the <code>CGPath...</code> versions of the Core Graphics functions, that add themselves to a mutable path objects, rather than being drawn directly on the currently active graphics context.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">    CGMutablePathRef r <span style="color: #002200;">=</span> CGPathCreateMutable<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #11740a; font-style: italic;">// Always have to move to a start point</span>
    CGPathMoveToPoint<span style="color: #002200;">&#40;</span>r, <span style="color: #a61390;">NULL</span>, x1, y1<span style="color: #002200;">&#41;</span>; 
    CGPathAddLineToPoint<span style="color: #002200;">&#40;</span>r, <span style="color: #a61390;">NULL</span>, x2, y2<span style="color: #002200;">&#41;</span>;
    CGPathCloseSubpath<span style="color: #002200;">&#40;</span>r<span style="color: #002200;">&#41;</span>;</pre></div></div>

<p>Once you&#8217;ve got created the path you can merrily set various stroke and fill colours and draw it over-and-over to your hearts content.</p>
<p><a href="http://www.voyce.com/wp-content/uploads/2011/12/star_algo.png"><img src="http://www.voyce.com/wp-content/uploads/2011/12/star_algo.png" alt="star_algo" title="star_algo" width="145" height="160" class="alignleft size-full wp-image-1383" /></a>The star drawing is parameterised in a few ways: we can set the inner radius (r2), outer radius (r1) and the number of points, which must be divisible by 3. We draw the points in groups of three, the first on the outer radius, then the inner, then the last on the outer. In that way the sections tesselate into a complete circle.</p>
<h3>Using it with CALayer</h3>
<p>So now we&#8217;ve got some code to draw the shape we want, we need a way to get it onto the screen, using <code>CALayer</code>s. There are 3 main ways of providing content for layers:</p>
<ul>
<li>Use a delegate that implements <code>drawInContext</code> (and don&#8217;t forget to call <code>setNeedsDisplay</code> at least once to cause it be drawn!)</li>
<li>Set the content to a <code>CGImageRef</code>. Meh&#8230; that&#8217;s going to mean it&#8217;s a bitmap, with all the associated aliasing/scaling issues.</li>
<li>Subclassing. Nah.</li>
</ul>
<p>We&#8217;ll use the first approach; we can create a simple <code>NSObject</code>-derived class that can manage the layer hierarchy (more of that later) and implement the required selector on it. In that function we can switch on the layer we&#8217;re being asked to draw, and do the appropriate handling:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>drawLayer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CALayer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>theLayer
        inContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGContextRef<span style="color: #002200;">&#41;</span>context 
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>theLayer <span style="color: #002200;">==</span> _textLayer<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// ...</span>
    <span style="color: #002200;">&#125;</span> <span style="color: #a61390;">else</span> <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>theLayer <span style="color: #002200;">==</span> _starLayer<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #11740a; font-style: italic;">// ...</span>
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></div></div>

<h3>Animating</h3>
<p>We&#8217;re only going to be doing fairly basic rotation animation here, so we can use <code>CABasicAnimation</code>. We use the key-value coding support to specify the <code>transform.rotation</code> property as the target. This is an alias for rotation around the Z axis, which is pointing &#8220;out&#8221; of the screen. We rotate from 0 to 2*pi radians, repeating essentially indefinitely by specifying a large repeatCount.</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">    CABasicAnimation <span style="color: #002200;">*</span>animation <span style="color: #002200;">=</span> 
        <span style="color: #002200;">&#91;</span>CABasicAnimation animationWithKeyPath<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;transform.rotation&quot;</span><span style="color: #002200;">&#93;</span>;
    animation.duration<span style="color: #002200;">=</span><span style="color: #2400d9;">8.0</span>;
    animation.repeatCount<span style="color: #002200;">=</span>HUGE_VALF;
    animation.autoreverses<span style="color: #002200;">=</span><span style="color: #a61390;">NO</span>;
    animation.fromValue<span style="color: #002200;">=</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#93;</span>;
    animation.toValue<span style="color: #002200;">=</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithFloat<span style="color: #002200;">:</span>TWOPI<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>_starLayer addAnimation<span style="color: #002200;">:</span>animation forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;rotation&quot;</span><span style="color: #002200;">&#93;</span>;</pre></div></div>

<h3>Drawing the text</h3>
<p>This was an interesting one. I originally started looking at a <code>CATextLayer</code>-based solution, but was surprised to find that it&#8217;s quite difficult to get vertical alignment within a rectangle. Instead, I decided to use the <code>NSString</code> UIKit additions that provide enough drawing and &#8211; importantly &#8211; measuring functions for us to work out exactly where we need to place the text.    </p>
<p>One important thing to note here is that we&#8217;re potentially mixing Core Graphics and UIKit functions here. They have different expectations about how to get hold of the required graphics context; with Core Graphics it&#8217;s always passed explicitly, whereas UIKit will grab the current context. This means that if you try and call <code>drawInRect</code> within your <code>drawLayer</code> function, you&#8217;ll see errors like &#8220;Invalid context: 0&#215;0&#8243; on the console, and no output.</p>
<p>The solution is simple when you know how: tell UIKit about your explicit context, like this:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>drawLayer<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CALayer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>theLayer
        inContext<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGContextRef<span style="color: #002200;">&#41;</span>context 
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">// ...</span>
    <span style="color: #11740a; font-style: italic;">// Let UIKit know about this context</span>
    UIGraphicsPushContext<span style="color: #002200;">&#40;</span>context<span style="color: #002200;">&#41;</span>;
    <span style="color: #11740a; font-style: italic;">// Because this function uses it internally...</span>
    <span style="color: #002200;">&#91;</span>myString drawInRect<span style="color: #002200;">:</span>r 
                     withFont<span style="color: #002200;">:</span>font
            lineBreakMode<span style="color: #002200;">:</span>UILineBreakModeClip 
                    alignment<span style="color: #002200;">:</span>UITextAlignmentCenter<span style="color: #002200;">&#93;</span>;
    UIGraphicsPopContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></div></div>

<p>By measuring the text before we draw, we can align it centrally vertically and fill the space horizontally, letting iOS worry about the horizontal alignment. <code>sizeWithFont</code> takes into account a bounding rectangle and our desired breaking/clipping options:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">        CGSize sz <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>s sizeWithFont<span style="color: #002200;">:</span>font 
                 constrainedToSize<span style="color: #002200;">:</span>theLayer.bounds.size 
                     lineBreakMode<span style="color: #002200;">:</span>UILineBreakModeClip<span style="color: #002200;">&#93;</span>;</pre></div></div>

<h3>Setting up a layer hierarchy</h3>
<p>Given that I wanted some parts of the thing to rotate, and others to be static, I needed to create multiple layers and put them together. This is very easily achieved by adding layers to the <code>subLayers</code> collection of our root layer, then we return the root layer and add that to the view.</p>
<p><div id="attachment_1391" class="wp-caption alignright" style="width: 170px"><a href="http://www.voyce.com/wp-content/uploads/2011/12/star_layers1.png"><img src="http://www.voyce.com/wp-content/uploads/2011/12/star_layers1.png" alt="Layer arrangement" title="star_layers" width="160" height="194" class="size-full wp-image-1391" /></a><p class="wp-caption-text">Layer arrangement</p></div>The layer set-up looks like this, with the root being empty, and having first the star layer, then the text layer added to the sublayers. This is just because <code>addSublayer</code> appends the sublayer, instead we could use the <code>insertSublayer</code> overloads to be explicit about the ordering we desire.<br />
<br clear="all"/><br />
The set-up function returns the root layer, and then we add that to our view:</p>

<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;">    _star <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>StarLayer alloc<span style="color: #002200;">&#93;</span> initWithRect<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">100</span>, <span style="color: #2400d9;">100</span>, <span style="color: #2400d9;">100</span>, <span style="color: #2400d9;">100</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self.view.layer<span style="color: #002200;">&#93;</span> addSublayer<span style="color: #002200;">:</span>_star.root<span style="color: #002200;">&#93;</span>;</pre></div></div>

<h3>Next Steps</h3>
<p>Here&#8217;s a red star and random text sitting a bit incongruously in a prototype of a spelling app I&#8217;m writing. </p>
<p><iframe width="200" height="165" src="http://www.youtube.com/embed/kAgYThdoy_c?rel=0" frameborder="0" allowfullscreen></iframe></p>
<p>It would be good to create a whole load of stars (probably not with text in) and shoot them across the screen in a star-burst by generating a random direction/speed vector and animating their speeds, opacity and scale to make them fade out.</p>
<p>You can check out the code <a href="https://github.com/voyce/StarLayer">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/12/03/drawing-animated-shapes-and-text-in-core-animation-layers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a physics-based OpenGL iOS app</title>
		<link>http://www.voyce.com/index.php/2011/11/18/creating-a-physics-based-opengl-ios-app/</link>
		<comments>http://www.voyce.com/index.php/2011/11/18/creating-a-physics-based-opengl-ios-app/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 22:40:50 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Bullet]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[physics]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1013</guid>
		<description><![CDATA[If you know a bit of OpenGL you can integrate the powerful Bullet physics API into your iPad or iPhone app.]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.voyce.com/wp-content/uploads/2010/09/puppet_grab.png" alt="puppet_grab" title="puppet_grab" width="128" height="128" class="alignleft size-full wp-image-1030" />With the success of iOS games like Angry Birds and its flocks of imitators, there are lots of people looking at creating physics-based games, so I decided to try and create a simple demo using OpenGL ES and the Bullet physics engine.<br />
<span id="more-1013"></span></p>
<h2>OpenGL</h2>
<p>The 3D work I&#8217;d done previously on iOS was using OpenGL ES 1.1, so as part of doing this, I also needed to get up to speed with the changes in version 2.0. The move involves replacing the fixed function pipeline approach with the use of shaders crafted in &#8220;shader language&#8221;, specifically <a href="http://www.opengl.org/documentation/glsl/">GLSL</a>. This approach is more flexible, but it means you take full responsibility for combining all the relevant matrices (model, projection etc), rather than letting OpenGL do it for you.</p>
<p>There are 2 distinct types of shader programs that operate on either vertices (vertex shaders) or pixels (fragment shaders). The steps required to create shader programs mirror the process of creating &#8220;normal&#8221; programs: they&#8217;re loaded, compiled and linked. Once you&#8217;ve got a program loaded, you can initialise it by setting variables of various kinds: attribute, uniform or varying. These are used for vertex and colour data, constants and passing data between vertex and fragment shaders respectively. If you&#8217;re interested in learning more, I suggest you check out some of the plethora of internet and dead-tree material on OpenGL. I&#8217;ll only be doing pretty basic stuff here.   </p>
<h2>Bullet</h2>
<p>I decided to try using <a href="http://bulletphysics.org/wordpress/">Bullet</a> as the physics engine. It looks very powerful and is widely used in various games and <a href="http://bulletphysics.org/wordpress/?p=241">movies</a>; the only bad thing I can say about it is that decent documentation is a bit lacking. I found the best way to get help was googling for API names on the Bullet forum; not a very efficient way of doing things. Maybe I&#8217;ve just been spoilt by the copious Apple and MS docs (yeah, yeah). </p>
<h3>Building it</h3>
<p>Luckily Bullet comes with an Xcode project &#8220;in the box&#8221;, so with a bit of <code>autoconf</code> magic, it was soon up and building the demo apps. Although there are loads of files in there, the core library itself isn&#8217;t too large or complex. As such, I decided to create a separate static library project targeting the iOS simulator (i386) and devices (armv6/7).</p>
<h3>API basics</h3>
<p>My intention is to use only a small subset of the Bullet API, encompassing rigid bodies and a couple of simple constraint types. For the purposes of the demo, I&#8217;m going to create the pretty standard set-up of a large static ground-box, along with a collection of more dynamic objects.  </p>
<p>The key part of joining up Bullet with your existing API is the <a href="http://www.bulletphysics.com/Bullet/BulletFull/classbtMotionState.html">btMotionState</a> class. It enables the API to callback into your code with updated positions at each &#8216;tick&#8217; of the physics engine, and you can then alter your geometry appropriately. I created a simple class that derives from <code>btMotionState</code>, implements the required pure virtual methods and contains a reference to my world object. Bullet calls the subclassed methods and we pass the transformations on to the object.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> QuadMotionState <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> btMotionState <span style="color: #008000;">&#123;</span>
    Quad <span style="color: #000040;">*</span>_object<span style="color: #008080;">;</span>
    btTransform _transform<span style="color: #008080;">;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
    QuadMotionState<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> btTransform <span style="color: #000040;">&amp;</span>initialpos, Quad <span style="color: #000040;">*</span>node<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        _object <span style="color: #000080;">=</span> node<span style="color: #008080;">;</span>
        _transform <span style="color: #000080;">=</span> initialpos<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">virtual</span> ~QuadMotionState<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">void</span> setNode<span style="color: #008000;">&#40;</span>Quad <span style="color: #000040;">*</span>node<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        _object <span style="color: #000080;">=</span> node<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> getWorldTransform<span style="color: #008000;">&#40;</span>btTransform <span style="color: #000040;">&amp;</span>worldTrans<span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span> <span style="color: #008000;">&#123;</span>
        worldTrans <span style="color: #000080;">=</span> _transform<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> setWorldTransform<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> btTransform <span style="color: #000040;">&amp;</span>worldTrans<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Pass the worldTrans to _object</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<h3>Debugging</h3>
<p>Now, obviously <em>you</em> will write the perfect code first time, and will have no need for any kind of diagnostics. But I am not that perfect; I need to see the difference between what I&#8217;ve told the API to do, and what it&#8217;s actually doing. You can do this by creating an object implementing <code>btIDebugDraw</code> and passing it to the (slightly oddly named) setDebugDrawer function on your world:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">btIDebugDraw <span style="color: #000040;">*</span>debug <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> DebugDrawHelper<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
m_dynamicsWorld<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>setDebugDrawer<span style="color: #008000;">&#40;</span>debug<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>The most important function on <code>btIDebugDraw</code> is <code>drawLine</code>. It will be called repeatedly to draw axes and bounding boxes in a variety of colours to indicate the object&#8217;s state. We can use the <code>Shader</code> we created earlier to give us an easy way of generating these debug visuals. All we need is a very simple shader, so can declare it inline:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">program.<span style="color: #007788;">loadShaders</span><span style="color: #008000;">&#40;</span>
		<span style="color: #FF0000;">&quot;attribute vec4 position;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #FF0000;">&quot;uniform mat4 projection;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #FF0000;">&quot;void main () {<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #FF0000;">&quot;gl_Position = position * projection;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #FF0000;">&quot;}<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, 
&nbsp;
		<span style="color: #FF0000;">&quot;uniform highp vec3 color;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #FF0000;">&quot;void main () {<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #FF0000;">&quot;gl_FragColor = vec4(color.r, color.g, color.b, 0.0);<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #FF0000;">&quot;}&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>Of course, anything more complex than this and you&#8217;ll want to put it into a separate file, but this program allows us to pass in the start and end vertex and its colour to draw the line in our implementation of <code>DrawLine</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> drawLine<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> btVector3<span style="color: #000040;">&amp;</span> from,<span style="color: #0000ff;">const</span> btVector3<span style="color: #000040;">&amp;</span> to,<span style="color: #0000ff;">const</span> btVector3<span style="color: #000040;">&amp;</span> color<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        glUseProgram<span style="color: #008000;">&#40;</span>program.<span style="color: #007788;">getProgram</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Set the projection matrix</span>
        GLint pu <span style="color: #000080;">=</span> glGetUniformLocation<span style="color: #008000;">&#40;</span>program.<span style="color: #007788;">getProgram</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">&quot;projection&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        glUniformMatrix4fv<span style="color: #008000;">&#40;</span>pu, <span style="color: #0000dd;">1</span>, <span style="color: #0000dd;">0</span>, _projection.<span style="color: #007788;">Pointer</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Set the colour of the line</span>
        GLint puc <span style="color: #000080;">=</span> glGetUniformLocation<span style="color: #008000;">&#40;</span>program.<span style="color: #007788;">getProgram</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">&quot;color&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        vec3 v <span style="color: #000080;">=</span> vec3<span style="color: #008000;">&#40;</span>color.<span style="color: #007788;">getX</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, color.<span style="color: #007788;">getY</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, color.<span style="color: #007788;">getZ</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        glUniform3fv<span style="color: #008000;">&#40;</span>puc, <span style="color: #0000dd;">1</span>, v.<span style="color: #007788;">Pointer</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Set the line vertices</span>
        <span style="color: #0000ff;">float</span> tmp<span style="color: #008000;">&#91;</span> <span style="color: #0000dd;">6</span> <span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #008000;">&#123;</span> from.<span style="color: #007788;">getX</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, from.<span style="color: #007788;">getY</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, from.<span style="color: #007788;">getZ</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>,
            to.<span style="color: #007788;">getX</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, to.<span style="color: #007788;">getY</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, to.<span style="color: #007788;">getZ</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
        glVertexAttribPointer<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">3</span>, GL_FLOAT, <span style="color: #0000ff;">false</span>, <span style="color: #0000dd;">0</span>, <span style="color: #000040;">&amp;</span>tmp<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        glEnableVertexAttribArray<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        glDrawArrays<span style="color: #008000;">&#40;</span> GL_LINES, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">2</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p><div id="attachment_1327" class="wp-caption alignright" style="width: 236px"><a href="http://www.voyce.com/wp-content/uploads/2010/09/physics_debug_screenshot.png"><img src="http://www.voyce.com/wp-content/uploads/2010/09/physics_debug_screenshot-226x300.png" alt="Bullet debug output" title="physics_debug_screenshot" width="226" height="300" class="size-medium wp-image-1327" /></a><p class="wp-caption-text">Bullet debug output</p></div> You&#8217;ll end up with a display showing your quads, along with their orientation and state (whether they&#8217;re &#8220;active&#8221; in the simulation). It looks something like this:<br />
<br clear="all"/></p>
<h3>Populating the world</h3>
<p>So in order to have something nice to look at, we&#8217;re gonna need to put some &#8216;things&#8217; into our world. And in order to make it act like the real world we&#8217;ll need to give those things some physical properties.</p>
<p>I created a simple class to render a textured box. This OpenGL object then needs to be represented in the physics worlds by a rigid body object, which in turn contains a collision detection object that closely matches the dimensions of the original object. In fact, in the case of a box, the collision detection object matches exactly, otherwise you&#8217;ll need to create an approximation using the more advanced classes. We use a <code>btBoxShape</code> to initialise our <code>btRigidBody</code> instance, along with setting its mass, inertia, and making a link to the state object that I mentioned above.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">btRigidBody <span style="color: #000040;">*</span>addShape<span style="color: #008000;">&#40;</span>Quad <span style="color: #000040;">*</span>shape, btScalar mass <span style="color: #000080;">=</span> <span style="color:#800080;">1.0f</span>, <span style="color: #0000ff;">float</span> restitution <span style="color: #000080;">=</span> <span style="color:#800080;">0.2f</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #666666;">// Set the initial transform based on the current location of the object</span>
        btTransform transform<span style="color: #008080;">;</span>
	transform.<span style="color: #007788;">setIdentity</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	transform.<span style="color: #007788;">setOrigin</span><span style="color: #008000;">&#40;</span>btVector3<span style="color: #008000;">&#40;</span>shape<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>getX<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, shape<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>getY<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, <span style="color:#800080;">0.</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	btCollisionShape<span style="color: #000040;">*</span> cshape <span style="color: #000080;">=</span> 
            <span style="color: #0000dd;">new</span> btBoxShape<span style="color: #008000;">&#40;</span>btVector3<span style="color: #008000;">&#40;</span>btScalar<span style="color: #008000;">&#40;</span>shape<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>getWidth<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #000040;">/</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span>,
                                     btScalar<span style="color: #008000;">&#40;</span>shape<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>getHeight<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #000040;">/</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span>,
                                     btScalar<span style="color: #008000;">&#40;</span>shape<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>getDepth<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #000040;">/</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        btVector3 localInertia<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span>,<span style="color: #0000dd;">0</span>,<span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>mass <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color:#800080;">0.0f</span><span style="color: #008000;">&#41;</span>
            cshape<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>calculateLocalInertia<span style="color: #008000;">&#40;</span>mass,localInertia<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        QuadMotionState <span style="color: #000040;">*</span>state <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> QuadMotionState<span style="color: #008000;">&#40;</span>transform, shape<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	btRigidBody<span style="color: #008080;">::</span><span style="color: #007788;">btRigidBodyConstructionInfo</span> rbInfo<span style="color: #008000;">&#40;</span>mass, state, cshape, localInertia<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	btRigidBody<span style="color: #000040;">*</span> body <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> btRigidBody<span style="color: #008000;">&#40;</span>rbInfo<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	body<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>setDamping<span style="color: #008000;">&#40;</span><span style="color:#800080;">0.85</span>, <span style="color:#800080;">0.85</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	body<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>setRestitution<span style="color: #008000;">&#40;</span>restitution<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Add the rigid body to the Bullet physics world</span>
	m_dynamicsWorld<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>addRigidBody<span style="color: #008000;">&#40;</span>body<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Establish the link between our object and the physics object</span>
	shape<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>setPhysicsObject<span style="color: #008000;">&#40;</span>body<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">return</span> body<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>To make things look a bit more polished I added some textures to the quads, along with very simple normal mapping to get some lighting effects. I also added the ability to rotate the view and zoom in and out by using <code>UIGestureRecognizer</code>s and changing the camera transform appropriately. The &#8220;finishing&#8221; touch (yeah, right), is the ability to tap to add a new quad.</p>
<h3>The results</h3>
<p>Here&#8217;s how the final thing looks. It&#8217;s very basic, I&#8217;ve hardly touched the surface of the Bullet API &#8211; there are no constraints in play, for instance &#8211; but it&#8217;s still kind of fun to play with. It&#8217;s running fairly slowly here, what with it being in the simulator, and being recorded. On a physical iPad it&#8217;s much snappier.<object width="420" height="315"><param name="movie" value="http://www.youtube.com/v/vbQ_EC_YlFY?version=3&amp;hl=en_US&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/vbQ_EC_YlFY?version=3&amp;hl=en_US&amp;rel=0" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />
Let me know if you&#8217;d be interested to see some more coverage of some of Bullet&#8217;s constraints and hinges features. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/11/18/creating-a-physics-based-opengl-ios-app/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++: The oldest new kid on the block</title>
		<link>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/</link>
		<comments>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/#comments</comments>
		<pubDate>Sat, 17 Sep 2011 23:06:09 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1294</guid>
		<description><![CDATA[Is C++ coming back to a warm welcome from Microsoft?  ]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.voyce.com/wp-content/uploads/2011/09/ballmer_cpp.png"><img src="http://www.voyce.com/wp-content/uploads/2011/09/ballmer_cpp.png" alt="Tasty" title="Tasty" width="200" height="200" class="alignright size-full wp-image-1296" /></a>Nobody could have failed to notice the recent resurgence of interest in the C++ programming language. In particular, the recent <a href="http://www.buildwindows.com/">Build</a> conference was the most we’ve seen Microsoft talking about C++ for several years. Why has a language that’s been languishing in the “prehistoric irrelevance” category for so long suddenly come back into vogue?<br />
<span id="more-1294"></span></p>
<h3>Dark Days</h3>
<p>We should bear in mind that in some camps, C++ never went away. The financial, scientific and games programming communities have bravely kept the fires burning.</p>
<p>Why? Primarily performance. In these industries performance is a feature, it’s a key differentiator, and it will help you make money. Can you say the same for an enterprise app (there I go, using that term disparagingly again) that just displays a form interface over a relational database?</p>
<p>However, even in the C++ bastions, the language was getting a bad press. I can only speak for the finance industry, where I’ve been working for the past 10 years, but even here the focus briefly switched away from raw performance to complex (overly-complex, dangerously-complex, as hindsight tells us) trades where getting to market first with something new was key: developer productivity was key. Flexibility and generality was key.</p>
<p>In that case, you don’t want to be dealing with the vagaries of subtle errors, crashes and memory leaks that can easily creep in when you’re using a language as low-level as C++. You just want to be able to release quickly. You probably want to be using a managed language.</p>
<p>In fact, C++ was getting a bad press all over. The functional power that was provided in languages like Haskell and F# &#8211; and being hastily added to C# &#8211; was missing or awkwardly implemented in C++. The provision of things like the .NET thread pool provided programmers on the CLR an easy way to schedule asynchronous tasks, and it was being touted as the only way to survive in the highly-parallel near-future. Of course, it was possible to do this stuff in C++, it was just more difficult.   </p>
<p>Despite this, the programming community widely understood the power that C++ brings, but also that it has to be wielded carefully. Witness the oft-repeated jokes about the fact that when you shoot yourself in the foot with C++, you tend to blow your leg off. There were even tensions within Microsoft, with the pro-managed DevDiv vs the hardcore, native-favouring Windows division.</p>
<h3>The New Order</h3>
<p>So what’s changed? Herb Sutter’s recent <a href="http://channel9.msdn.com/posts/C-and-Beyond-2011-Herb-Sutter-Why-C">talk</a> covered many of the reasons why C++ is relevant again, and the most obvious reason is the emergence and importance of mobile devices and data centres. </p>
<p>They have a completely different set of requirements than the desktop: they focus on squeezing the best experience out of every available cycle (and corresponding minute of battery life), and the most performance out of every watt of data centre power per degree of cooling. We’re seeing the impact of the smartphone in your pocket and the data-centric web and social media reflecting back onto the languages we use to write software.  </p>
<p>Managed languages fall down in some important areas here. They sacrifice memory efficiency to the god of garbage collection and they offer fewer opportunities for aggressive compiler optimisations, including, in the case of .NET, making use of chip-provided performance features like SIMD instructions.</p>
<p>Nowadays in more and more of the computing industry, it’s the hardware that’s driving the development choices, not the other way around.</p>
<p>With resource-constricted platforms, you want to be doing more of the heavy lifting offline, at compile time, not at run-time with a JIT compiler.</p>
<h3>How the iPhone showed devs don&#8217;t care</h3>
<p>While (parts of) Microsoft were busy pushing the managed languages hard, Apple was quietly producing game-changing pieces of hardware that the device-carrying public were buying in their hordes. And they weren’t just buying devices, they were buying apps to play on these devices &#8211; in their millions. Lots of developers wanted a piece of this action but &#8211; quelle horreur! &#8211; You had to use an obscure variant of C to create them.</p>
<p>But &#8211; surprise, surprise &#8211; developers did it anyway. Luckily, they weren’t on their own, but this time rather than a managed runtime, they had an API to use. And they had to use it; it was, and is, literally a condition of sale that your app uses only the APIs that Apple provide and in the way that they intended. Whatever your view on the fairness of this approach, having a restricted surface area and well defined set of libraries helps developers win back some of the productivity they might otherwise have sacrificed by using Objective-C.</p>
<p>Microsoft must’ve been looking askance at this, wondering how Apple had so effectively switched the model around. MS had been based on the idea of developer productivity being king and the hardware being utterly insignificant. Now developers were writing code in a language that was broadly derided by people in the programming community, yet they were in a virtuous circle where writing apps helped to ship hardware that increased the market for their apps. </p>
<h3>We need libraries</h3>
<p>Is it possible to find a good balance between the raw power of C++ and the productivity of managed languages? I think it is; and partly it comes down to having a good set of libraries. When I say good, I mean consistent, relevant, well-documented, easily available set of libraries. Can you see where C++ may have struggled here before?</p>
<p>For the low-level, programming task oriented basics, Boost is the answer. Seriously, Boost always seems to be the answer to questions of “how do I do X in C++?” where X is a modern programming technique. Smart pointers, lambdas, higher-order functions… they’re all there. </p>
<p>A few years ago if you were working in C++, you didn’t have many options apart from vanilla STL, Boost, and writing-it-yourself (again). Now, the STL and the language itself is richer and anecdotally, organisations are more receptive to the use of Boost. So hopefully, this combination gives us back access to most of the functionality that’s available to managed developers in their pre-packaged base class libraries.</p>
<h3>C++ and Apps</h3>
<p>But how is that going to help people use it to produce compelling apps and “experiences” (cough) and specifically, how is Microsoft going to use its developer productivity nous to keep Windows relevant in the new hardware markets? </p>
<p>They need something else; something like the Apple Core frameworks. It looks like this is what Microsoft is talking about with Windows 8 and the Windows Runtime. It’s suddenly not embarrassed to admit that, hey, Windows itself is written in C++, so maybe you shouldn’t have to go through a managed ‘interpretation’ of the existing APIs, one that’s exclusively available to managed languages.</p>
<p>Of course, Microsoft can’t do anything as radical as forcing all developers targeting a mobile or tablet platform to use C++. For them, programmers, rather than any particular hardware, are the bread-and-butter, so they tend to have a slightly less dictator-style relationship with devs than Apple does. </p>
<p>Judging from what I’ve seen from Build, Microsofts chosen approach is to provide language-specific “projections” (their term) from the Windows Runtime layer into a variety of languages, including C++. The native C++ types are mapped into corresponding concepts in the vernacular of the higher level languages; Javascript, C# etc. They’ve gone to some lengths, it seems, to ensure that transitions between levels are efficient. Using C++ at both levels should be the fast path, and of course you can mix it freely with code that, for example, uses Boost or other C++ libraries. </p>
<p>Additionally and importantly, as well as basic types, collections etc, the Windows Runtime also contains all of the rich APIs for accessing app-level functionality; things like image capture, sound and geolocation. So suddenly, all of this stuff is available in all its glory directly from C++ &#8211; and other languages too via cheap bridges. What they’ve essentially got is an identical copy of the architecture that exists in the iOS world, while still attempting to keep non C++ developers on-side. </p>
<h3>The Return&#8230;?</h3>
<p>So, have Microsoft managed to bring C++ in from the cold? They seem to have admitted, at least to themselves, that developers will need to use it in order to effectively target some platforms, and they’ve used their tooling experience to make it look and feel like a managed language in their IDEs, as well as leveraging their compiler technology to do some additional useful performance tricks. It feels like C++ was a fundamental concern in the redesign of the new alternative to the creaking Win32 API.</p>
<p>But will the transition be something to make current developers switch to C++, especially those who’ve been used to living in the cosseted managed world? Perhaps, if the Microsoft-based tablet market becomes as compelling &#8211; read, large &#8211; as Apple’s. Otherwise I don’t see any reason why developers who don’t have specific platform or other runtime requirements would move; for the majority of environments, developer time is still the dominant cost, so developer productivity will still be paramount. </p>
<p>The gap between managed and unmanaged languages has certainly narrowed in that area, but it still exists. C++ is still proving surprisingly relevant, despite its 30+ years, and hopefully its use in new and different areas of computing will feed back into improvements in the language and libraries for everyone’s benefit. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kinect SDK with F#</title>
		<link>http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/</link>
		<comments>http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 14:34:47 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[kinect]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1273</guid>
		<description><![CDATA[My first quick look at using the Kinect SDK with F#.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_1283" class="wp-caption alignleft" style="width: 210px"><a href="http://www.voyce.com/wp-content/uploads/2011/09/kinect.png"><img src="http://www.voyce.com/wp-content/uploads/2011/09/kinect.png" alt="Just what do you think you&#039;re doing, Dave?" title="kinect" width="200" height="200" class="size-full wp-image-1283" /></a><p class="wp-caption-text">Just what do you think you're doing, Dave?</p></div>I finally got around to taking a look at the <a href="http://research.microsoft.com/en-us/um/redmond/projects/kinectsdk/">Kinect SDK</a> the other day, partly because I was interested to see how the API looked from F#. Unfortunately getting it going turned out to be more of a pain than I was expecting.</p>
<p>The first bit was easy: I&#8217;m &#8220;lucky&#8221; enough to have one of the older Xboxes, which meant I&#8217;d had to get a Kinect with separate power, which is the one required by the SDK. Now all I needed was a Windows machine to develop on.<br />
<span id="more-1273"></span><br />
For all my Visual Studio stuff at home I use a virtual machine, and unfortunately I missed the point in the <a href="http://research.microsoft.com/en-us/um/redmond/projects/kinectsdk/docs/readme.htm">readme</a> about &#8220;Kinect for Windows applications cannot run in a virtual machine&#8221;. Doh. That would explain why, try as I might I couldn&#8217;t get <a href="http://www.virtualbox.org/">VirtualBox</a> to detect the device when I plugged it into the host. Whatever I did I ended up with a &#8216;resource is busy&#8217; error. </p>
<p>I even tried another VM, this time from VMWare. It got further, with the guest seeing the devices, but whenever I tried to run the sample apps the API initialisation call failed. Unfortunately the samples make a bit of a rookie mistake and don&#8217;t display the error code associated with the failure; the only way to get the underlying HRESULT is to debug the app. As it turned out the error was the catch-all <code>80080014</code>, which is attributed to various USB issues.</p>
<p>So, I finally relented and decided to once again set-up Bootcamp, which I&#8217;d stopped using a while back: why bother when VMs had done everything I needed? Again I was snookered, this time by the incompatibility of the <a href="http://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface">EFI</a> firmware in my ageing MacBook with the Win7 x64 install disc (which I&#8217;d had to actually burn onto optical media &#8211; can&#8217;t remember the last time I burnt a real physical disk)!</p>
<p>Eventually, I got Win7 x86, Visual Studio and the Kinect SDK installed on the metal, plugged in the sensor and &#8211; whoa &#8211; the devices were recognised and the drivers installed and&#8230; the samples ran!</p>
<p>From this point doing some hacking was pretty straightforward. I set about creating a project that used the skeletal tracking ability from the SDK. The project needs to reference the <code>Microsoft.Research.Kinect</code> assembly, then we can open some namespaces and initialise the API:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">open</span> System
<span style="color: #06c; font-weight: bold;">open</span> Microsoft<span style="color: #000080;">.</span><span style="color: #505090;">Research</span><span style="color: #000080;">.</span><span style="color: #505090;">Kinect</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">let</span> nui <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
nui<span style="color: #000080;">.</span><span style="color: #505090;">Initialize</span><span style="color: #000080;">&#40;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">RuntimeOptions</span><span style="color: #000080;">.</span><span style="color: #505090;">UseSkeletalTracking</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>The API uses .NET events to communicate back to the application that some form of data is available. Depending on the options that you specify at init time, any of the skeletal, depth frame or colour data will be returned in the event arguments. This seems like a good place to use F# Async&#8217;s event integration: Async.AwaitEvent. We can quite easily write some code that will create an Async task that will repeatedly listen for events:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> skeleton <span style="color: #000080;">&#40;</span>nui <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
            async <span style="color: #000080;">&#123;</span> 
                <span style="color: #06c; font-weight: bold;">let</span><span style="color: #000080;">!</span> args <span style="color: #000080;">=</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">AwaitEvent</span> nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrameReady</span>
                <span style="color: #060; font-style: italic;">// Do something with the args</span>
                <span style="color: #06c; font-weight: bold;">return</span><span style="color: #000080;">!</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #000080;">&#125;</span>
        loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #060; font-style: italic;">// Start the process of listening for events...</span>
    skeleton nui <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Start</span></pre></div></div>

<p>This seems to work nicely, although I&#8217;m not sure of the overhead involved, perhaps a solution involving Rx would be more appropriate. Anyway, let&#8217;s do something with the data we get in the event, like getting all the skeletons that are being tracked, and passing them to a <code>draw</code> function:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">                args<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrame</span><span style="color: #000080;">.</span><span style="color: #505090;">Skeletons</span> 
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">filter</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> s <span style="color: #000080;">-&gt;</span> s<span style="color: #000080;">.</span><span style="color: #505090;">TrackingState</span> <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonTrackingState</span><span style="color: #000080;">.</span><span style="color: #505090;">Tracked</span><span style="color: #000080;">&#41;</span>
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">iter</span> draw</pre></div></div>

<p>All that&#8217;s left is doing something cool in <code>draw</code>! Oh, and setting up all the GUI stuff necessary to actually get some pixels on the screen. I went for the WPF approach (as the managed samples do), which involves creating a simple object tree to display a rectangle in a canvas in a grid in a window, and doing a bit of marshalling back from the thread pool (where our Async code runs) to the main GUI thread.</p>
<p>Here&#8217;s all the code for possibly the most tedious thing you could do with a Kinect! But hey, it&#8217;s a starting point, right? I&#8217;m sure at some point I&#8217;ll get around to doing something cooler than a couple of small red rectangles with it&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">open</span> System
<span style="color: #06c; font-weight: bold;">open</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Windows</span>
<span style="color: #06c; font-weight: bold;">open</span> Microsoft<span style="color: #000080;">.</span><span style="color: #505090;">Research</span><span style="color: #000080;">.</span><span style="color: #505090;">Kinect</span>
&nbsp;
<span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>STAThread<span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
<span style="color: #06c; font-weight: bold;">do</span>
    <span style="color: #06c; font-weight: bold;">let</span> nui <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    nui<span style="color: #000080;">.</span><span style="color: #505090;">Initialize</span><span style="color: #000080;">&#40;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">RuntimeOptions</span><span style="color: #000080;">.</span><span style="color: #505090;">UseSkeletalTracking</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #060; font-style: italic;">// lifted straight from the sample code</span>
    <span style="color: #06c; font-weight: bold;">let</span> getDisplayPosition w h <span style="color: #000080;">&#40;</span>joint <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Joint</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> depthX <span style="color: #000080;">=</span> 0<span style="color: #000080;">.</span>0f
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> depthY <span style="color: #000080;">=</span> 0<span style="color: #000080;">.</span>0f
            nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonEngine</span><span style="color: #000080;">.</span><span style="color: #505090;">SkeletonToDepthImage</span><span style="color: #000080;">&#40;</span>joint<span style="color: #000080;">.</span><span style="color: #505090;">Position</span>, <span style="color: #000080;">&amp;</span>depthX, <span style="color: #000080;">&amp;</span>depthY<span style="color: #000080;">&#41;</span>
            <span style="color: #06c; font-weight: bold;">let</span> depthX <span style="color: #000080;">=</span> depthX <span style="color: #000080;">*</span> 320<span style="color: #000080;">.</span>0f<span style="color: #000080;">;</span> <span style="color: #060; font-style: italic;">//convert to 320, 240 space</span>
            <span style="color: #06c; font-weight: bold;">let</span> depthY <span style="color: #000080;">=</span> depthY <span style="color: #000080;">*</span> 240<span style="color: #000080;">.</span>0f<span style="color: #000080;">;</span> <span style="color: #060; font-style: italic;">//convert to 320, 240 space</span>
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> colorX <span style="color: #000080;">=</span> <span style="color: #c6c;">0</span>
            <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">mutable</span> colorY <span style="color: #000080;">=</span> <span style="color: #c6c;">0</span>
            <span style="color: #06c; font-weight: bold;">let</span> iv <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">ImageViewArea</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
            <span style="color: #060; font-style: italic;">// only ImageResolution.Resolution640x480 is supported at this point</span>
            nui<span style="color: #000080;">.</span><span style="color: #505090;">NuiCamera</span><span style="color: #000080;">.</span><span style="color: #505090;">GetColorPixelCoordinatesFromDepthPixel</span><span style="color: #000080;">&#40;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">ImageResolution</span><span style="color: #000080;">.</span><span style="color: #505090;">Resolution640x480</span>, iv, 
                <span style="color: #000080;">&#40;</span>int<span style="color: #000080;">&#41;</span>depthX, <span style="color: #000080;">&#40;</span>int<span style="color: #000080;">&#41;</span>depthY, 0s, <span style="color: #000080;">&amp;</span>colorX, <span style="color: #000080;">&amp;</span>colorY<span style="color: #000080;">&#41;</span>
&nbsp;
            <span style="color: #060; font-style: italic;">// map back to visible area</span>
            <span style="color: #06c; font-weight: bold;">new</span> Point<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>w <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>float<span style="color: #000080;">&#41;</span>colorX <span style="color: #000080;">/</span> 640<span style="color: #000080;">.</span><span style="color: #000080;">&#41;</span>, <span style="color: #000080;">&#40;</span>h <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>float<span style="color: #000080;">&#41;</span>colorY <span style="color: #000080;">/</span> 480<span style="color: #000080;">.</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #060; font-style: italic;">// Set-up the WPF window and its contents</span>
    <span style="color: #06c; font-weight: bold;">let</span> width <span style="color: #000080;">=</span> 1024<span style="color: #000080;">.</span>
    <span style="color: #06c; font-weight: bold;">let</span> height <span style="color: #000080;">=</span> 768<span style="color: #000080;">.</span>
    <span style="color: #06c; font-weight: bold;">let</span> w <span style="color: #000080;">=</span> Window<span style="color: #000080;">&#40;</span>Width<span style="color: #000080;">=</span>width, Height<span style="color: #000080;">=</span>height<span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> g <span style="color: #000080;">=</span> Controls<span style="color: #000080;">.</span><span style="color: #505090;">Grid</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> c <span style="color: #000080;">=</span> Controls<span style="color: #000080;">.</span><span style="color: #505090;">Canvas</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> hd <span style="color: #000080;">=</span> Shapes<span style="color: #000080;">.</span><span style="color: #505090;">Rectangle</span><span style="color: #000080;">&#40;</span>Fill<span style="color: #000080;">=</span>Media<span style="color: #000080;">.</span><span style="color: #505090;">Brushes</span><span style="color: #000080;">.</span><span style="color: #505090;">Red</span>, Width<span style="color: #000080;">=</span>10<span style="color: #000080;">.</span>, Height<span style="color: #000080;">=</span>10<span style="color: #000080;">.</span><span style="color: #000080;">&#41;</span>
    ignore <span style="color: #000080;">&lt;|</span> c<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> hd
    ignore <span style="color: #000080;">&lt;|</span> g<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> c
    w<span style="color: #000080;">.</span><span style="color: #505090;">Content</span> <span style="color: #000080;">&lt;-</span> g
&nbsp;
    <span style="color: #060; font-style: italic;">// We simple move the rectangle to where the head is</span>
    <span style="color: #06c; font-weight: bold;">let</span> draw <span style="color: #000080;">&#40;</span>s <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonData</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">let</span> point <span style="color: #000080;">=</span> getDisplayPosition width height s<span style="color: #000080;">.</span><span style="color: #505090;">Joints</span><span style="color: #000080;">.</span><span style="color: #000080;">&#91;</span>Nui<span style="color: #000080;">.</span><span style="color: #505090;">JointID</span><span style="color: #000080;">.</span><span style="color: #505090;">Head</span><span style="color: #000080;">&#93;</span>
        ignore <span style="color: #000080;">&lt;|</span> w<span style="color: #000080;">.</span><span style="color: #505090;">Dispatcher</span><span style="color: #000080;">.</span><span style="color: #505090;">BeginInvoke</span><span style="color: #000080;">&#40;</span>Threading<span style="color: #000080;">.</span><span style="color: #505090;">DispatcherPriority</span><span style="color: #000080;">.</span><span style="color: #505090;">Normal</span>, Action<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span>    
            hd<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>Controls<span style="color: #000080;">.</span><span style="color: #505090;">Canvas</span><span style="color: #000080;">.</span><span style="color: #505090;">TopProperty</span>, point<span style="color: #000080;">.</span><span style="color: #505090;">Y</span><span style="color: #000080;">&#41;</span>
            hd<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>Controls<span style="color: #000080;">.</span><span style="color: #505090;">Canvas</span><span style="color: #000080;">.</span><span style="color: #505090;">LeftProperty</span>, point<span style="color: #000080;">.</span><span style="color: #505090;">X</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">let</span> skeleton <span style="color: #000080;">&#40;</span>nui <span style="color: #000080;">:</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
            async <span style="color: #000080;">&#123;</span> 
                <span style="color: #06c; font-weight: bold;">let</span><span style="color: #000080;">!</span> args <span style="color: #000080;">=</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">AwaitEvent</span> nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrameReady</span>
                args<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonFrame</span><span style="color: #000080;">.</span><span style="color: #505090;">Skeletons</span> 
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">filter</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> s <span style="color: #000080;">-&gt;</span> s<span style="color: #000080;">.</span><span style="color: #505090;">TrackingState</span> <span style="color: #000080;">=</span> Nui<span style="color: #000080;">.</span><span style="color: #505090;">SkeletonTrackingState</span><span style="color: #000080;">.</span><span style="color: #505090;">Tracked</span><span style="color: #000080;">&#41;</span>
                <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">iter</span> draw
                <span style="color: #06c; font-weight: bold;">return</span><span style="color: #000080;">!</span> loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #000080;">&#125;</span>
        loop <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    skeleton nui <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Start</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">let</span> a <span style="color: #000080;">=</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Windows</span><span style="color: #000080;">.</span><span style="color: #505090;">Application</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    ignore <span style="color: #000080;">&lt;|</span> a<span style="color: #000080;">.</span><span style="color: #505090;">Run</span><span style="color: #000080;">&#40;</span>w<span style="color: #000080;">&#41;</span>
&nbsp;
    nui<span style="color: #000080;">.</span><span style="color: #505090;">Uninitialize</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>The moral of the story? Don&#8217;t be like me, and make sure you actually read the FAQing readme, then maybe you&#8217;ll spend more time doing a decent demo and less time plugging and unplugging your Kinect!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/09/05/kinect-sdk-with-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Am I being called from DllMain?</title>
		<link>http://www.voyce.com/index.php/2011/08/20/am-i-being-called-from-dllmain/</link>
		<comments>http://www.voyce.com/index.php/2011/08/20/am-i-being-called-from-dllmain/#comments</comments>
		<pubDate>Sat, 20 Aug 2011 12:52:37 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1258</guid>
		<description><![CDATA[How can you tell if your code is being called from within DllMain? You could use an undocumented function from ntdll.dll.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_1265" class="wp-caption alignright" style="width: 210px"><a href="http://www.voyce.com/wp-content/uploads/2011/08/lock_200.png"><img src="http://www.voyce.com/wp-content/uploads/2011/08/lock_200.png" alt="Lock; literal images &#039;r&#039; us" title="lock_200" width="200" height="200" class="size-full wp-image-1265" /></a><p class="wp-caption-text">Lock; literal images 'r' us</p></div>While Googling for an obscure Windows function the other day, I came across <a href="http://www.geoffchappell.com/viewer.htm?doc=index.htm">this</a> fantastically useful repository of undocumented WinAPI functions, put together by Geoff Chappell. I&#8217;m not sure how I hadn&#8217;t discovered it before.</p>
<p>One of the functions that immediately caught my eye was <a href="http://www.geoffchappell.com/viewer.htm?doc=studies/windows/win32/ntdll/api/ldrapi/lockloaderlock.htm">LdrLockLoaderLock</a>. I&#8217;d previously spent quite a few frustrating hours trying to figure out how to determine whether some code was being executed from DllMain, i.e. while in the loader lock, so I could avoid doing anything dodgy &#8211; or indeed, anything at all. </p>
<p>The case I was looking at was some logging library code that was used, amongst other things, to record the fact that DLLs were being unloaded. Unfortunately when this was called from DllMain, it sometimes caused a deadlock, for all the reasons we already know about. The library code was called from lots of DLLs, so it wasn&#8217;t feasible to fix all of the call sites, instead I had to make the logging a no-op when it&#8217;s not safe.<br />
<span id="more-1258"></span><br />
I&#8217;m embarrassed to say that my previous attempt to detect the lock involved some pretty heinous hackery. I worked out the memory address (the offset within ntdll.dll) where the loader lock critical section is located, cast that bit of memory to a CRITICAL_SECTION and tested it. I even had to provide the ability to change the offset based on the version of ntdll being used, in a vain attempt to reduce its fragility. Ouch. It was very nasty, and to be honest although it worked in the cases where I tested it, I was reluctant to release it.</p>
<p>Luckily, along comes LdrLockLoaderLock to save my blushes. It appears to give me exactly the functionality I need; you can pass a flag to tell it to return immediately if the lock&#8217;s already been taken, and there&#8217;s a status parameter that can be used to tell if you got the lock &#8211; whereupon you can call the corresponding <a href="http://www.geoffchappell.com/viewer.htm?doc=studies/windows/win32/ntdll/api/ldrapi/unlockloaderlock.htm">LdrUnlockLoaderLock</a>. Nice!  </p>
<p>I wonder if this is what&#8217;s used by the Visual Studio <a href="http://msdn.microsoft.com/en-us/library/ms172219.aspx">loader lock managed debugging assistant</a> to determine if your managed code is being run under the loader lock?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/08/20/am-i-being-called-from-dllmain/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# Async: Plays well with others?</title>
		<link>http://www.voyce.com/index.php/2011/05/27/fsharp-async-plays-well-with-others/</link>
		<comments>http://www.voyce.com/index.php/2011/05/27/fsharp-async-plays-well-with-others/#comments</comments>
		<pubDate>Fri, 27 May 2011 22:55:46 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1208</guid>
		<description><![CDATA[Async is a powerful way of getting parallelism in your F# code, just be careful what you call within your Async workflows.]]></description>
			<content:encoded><![CDATA[<p>OK, quick <a href="http://msdn.microsoft.com/en-us/library/dd233250.aspx">Async</a> pop quiz: How long does the <code>run</code> function below take to execute?</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">module</span> Test <span style="color: #000080;">=</span> 
    <span style="color: #06c; font-weight: bold;">let</span> work i <span style="color: #000080;">=</span> 
        async <span style="color: #000080;">&#123;</span> 
            System<span style="color: #000080;">.</span><span style="color: #505090;">Threading</span><span style="color: #000080;">.</span><span style="color: #505090;">Thread</span><span style="color: #000080;">.</span><span style="color: #505090;">Sleep</span><span style="color: #000080;">&#40;</span><span style="color: #c6c;">500</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #06c; font-weight: bold;">return</span> i<span style="color: #000080;">+</span><span style="color: #c6c;">1</span> 
        <span style="color: #000080;">&#125;</span>
    <span style="color: #06c; font-weight: bold;">let</span> run <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> 
        <span style="color: #000080;">&#91;</span>1<span style="color: #000080;">..</span>1000<span style="color: #000080;">&#93;</span> <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">map</span> work 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Parallel</span> 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">RunSynchronously</span></pre></div></div>

<p>(Waits for people to start FSI and paste in the code&#8230;)</p>
<p>My guess would&#8217;ve been something just over 500ms; each of the 1000 async tasks would surely sleep in parallel, and then the operation itself is trivial. The additional elapsed time would be dominated by the overhead of thread management, and depend on the number of threads that can physically run in parallel (I&#8217;m using an 8-core machine). But still, something close to 500ms&#8230;</p>
<p>The actual result? 28000ms. Yes, you read that right: 28 seconds. What on earth did we do wrong?<br />
<span id="more-1208"></span><br />
Surely it can&#8217;t be that <a href="http://msdn.microsoft.com/en-us/library/d00bd51t.aspx">Sleep</a>, right? I mean, each task is going to run on the thread pool anyway, so what difference would that make? Well, that *is* exactly the problem. It turns out that you can&#8217;t mix &#8220;vanilla&#8221; threading calls with <code>Async</code> API ones, because Async works in a completely different and incompatible way. If we use raw threading functions like <code>Sleep</code>, the async framework has no way of knowing if we&#8217;re doing anything useful. It eventually ends up causing .NET thread pool starvation, as we&#8217;re essentially grabbing and holding each thread in a way that doesn&#8217;t cooperate with anything else. New threads will spin-up to compensate and we&#8217;ll end up getting additional memory usage as well as worse performance. </p>
<p><div id="attachment_1232" class="wp-caption alignleft" style="width: 81px"><a href="http://www.voyce.com/wp-content/uploads/2011/05/threads_raw.png"><img src="http://www.voyce.com/wp-content/uploads/2011/05/threads_raw-71x300.png" alt="Nasty" title="threads_raw" width="71" height="300" class="size-medium wp-image-1232" /></a><p class="wp-caption-text">Nasty</p></div> This is a very rough impression of how things look if you use non-async aware blocking. Vertical lines represent threads in the thread pool, artificially restricted to 3 for diagrammatic purposes. Notice how each of the &#8216;blocks of work&#8217; are large, and the opportunities to spread the work amongst threads is small. As a result, total elapsed time is large.<br />
<br clear="all"/></p>
<p>Instead Async uses what&#8217;s called <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">continuation passing style</a>, a technique favoured by the functional programming community, that also happens to map quite nicely to features in the CLR, including the thread pool, tail calls and garbage collection. It has the rather nice feature that it never blocks an OS thread (unless it&#8217;s busy actually executing). Instead it queues a function (a continuation) to be called at some later point. </p>
<p><div id="attachment_1233" class="wp-caption alignright" style="width: 193px"><a href="http://www.voyce.com/wp-content/uploads/2011/05/threads_async.png"><img src="http://www.voyce.com/wp-content/uploads/2011/05/threads_async-183x300.png" alt="Nice" title="threads_async" width="183" height="300" class="size-medium wp-image-1233" /></a><p class="wp-caption-text">Nice</p></div>Here the blocks are broken into a small amount of initial work to create and schedule the event, and then a further small amount to execute the continuation. In the meantime other code can be run (in this case, other instances of the same task), and we get good usage of the thread pool.<br clear="all"/></p>
<p>For all the gory details and full Async semantics, I suggest you read the <a href="http://research.microsoft.com/pubs/147194/async-padl-revised-v2.pdf">paper</a> from Microsoft Research. Tucked away in there you&#8217;ll see that they do mention this restriction: </p>
<blockquote><p> The key facet of an asynchronous I/O primitive is that it does not block an OS thread while executing, but instead schedules the continuation of the asynchronous computation as a callback in response to an event.
</p></blockquote>
<p>So how do we &#8220;fix&#8221; our example? Simple: we replace the non-CPS-friendly explicit Sleep, with an Async-native Sleep.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">module</span> Test <span style="color: #000080;">=</span> 
    <span style="color: #06c; font-weight: bold;">let</span> work i <span style="color: #000080;">=</span> 
        async <span style="color: #000080;">&#123;</span> 
            <span style="color: #06c; font-weight: bold;">do</span><span style="color: #000080;">!</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Sleep</span><span style="color: #000080;">&#40;</span><span style="color: #c6c;">500</span><span style="color: #000080;">&#41;</span> 
            <span style="color: #06c; font-weight: bold;">return</span> i<span style="color: #000080;">+</span><span style="color: #c6c;">1</span> 
        <span style="color: #000080;">&#125;</span>
    <span style="color: #06c; font-weight: bold;">let</span> run <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> 
        <span style="color: #000080;">&#91;</span>1<span style="color: #000080;">..</span>1000<span style="color: #000080;">&#93;</span> <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">map</span> work 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">Parallel</span> 
        <span style="color: #000080;">|&gt;</span> Async<span style="color: #000080;">.</span><span style="color: #505090;">RunSynchronously</span></pre></div></div>

<p>The result now: 558ms. Much more like it! </p>
<p>What happens is that the <code>Async.Sleep</code> call is converted into an event that is fired after 500ms to continue the execution, i.e. actually perform the addition. In the meantime, each of the other instances of the workflow get a chance to run, and we get real parallelism.   </p>
<p>In this case it might look screamingly obvious, but be aware if you&#8217;re doing something such as calling into a third-party, legacy, or otherwise non-Async-aware code, it could cause your otherwise highly parallel code to choke. You&#8217;ll have to wrap it up in order to make it play nicely with Async and make sure you get the full benefit of this powerful F# feature.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/05/27/fsharp-async-plays-well-with-others/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mixing it up: when F# meets C#</title>
		<link>http://www.voyce.com/index.php/2011/05/09/mixing-it-up-when-f-meets-c/</link>
		<comments>http://www.voyce.com/index.php/2011/05/09/mixing-it-up-when-f-meets-c/#comments</comments>
		<pubDate>Mon, 09 May 2011 22:18:26 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[IL]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1146</guid>
		<description><![CDATA[How does it look when F# meets C#?]]></description>
			<content:encoded><![CDATA[<p><div class="wp-caption alignleft" style="width: 130px"><a href="http://www.flickr.com/photos/ianvoyce/5676819517/"><img alt="Simples?" src="http://farm6.static.flickr.com/5189/5676819517_e93bee2c41_m.jpg" title="meerkat" width="120" height="180" /></a><p class="wp-caption-text">Simples?</p></div>If it were a perfect world, we&#8217;d all exist in a happy little bubble of our favourite programming language and you&#8217;d never have to worry about the nasty details of interacting with something written by &#8211; gasp &#8211; someone else in a &#8211; double-gasp &#8211; different language. But unfortunately that&#8217;s precisely what we have to do all the time. And that means that one day all of your fancy-pants algorithmic, highly parallel, functionally pure F# code is going to meet the world of &#8220;enterprise&#8221; C# development head-on.</p>
<p>Of course the idiomatic way to avoid problems at the boundary between your F# code and the outside world is to ensure that you only expose a small set of compatible types. This works pretty well if your clients are also .NET languages. For instance you can do things like exposing your collections as <code>seq<T></code>, rather than say, a native F# <code>list</code>, and this will mean your collections can be consumed as <code>IEnumerable<T></code>. The only problem is it means you&#8217;ve got the added burden of maintaining this mapping layer, because you&#8217;ll no doubt want to use the F# &#8220;native&#8221; types internally.</p>
<p>So, what options do we have if some of our F# types happen to leak into our public API? Luckily, lots. Let&#8217;s take a look at how some of the common F# constructs can be called from C#.<br />
<span id="more-1146"></span></p>
<h3>Unions</h3>
<p>I talked about the power of discriminated unions a while back, so how do they map to C#? Interestingly the F# compiler generates a very simple OO type hierarchy, with an abstract base class that each of the cases derive from. This will mean that your calling code will need  to use some casting, but don&#8217;t worry, you&#8217;re not back in the hell of runtime typing; there are a set of methods on the type that you can use to identify the case before you do the cast, so at least you get some compile time sanity checking.</p>
<p>Here&#8217;s a simple discriminated union that we&#8217;ll be using as an example:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">type</span> TestDU <span style="color: #000080;">=</span>
        <span style="color: #000080;">|</span> One <span style="color: #06c; font-weight: bold;">of</span> int <span style="color: #000080;">*</span> int
        <span style="color: #000080;">|</span> Two <span style="color: #06c; font-weight: bold;">of</span> string
        <span style="color: #000080;">|</span> Three</pre></div></div>

<p>If we wanted to use this type in F#, we&#8217;d do so like this:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #060; font-style: italic;">// A function 'f' that takes an instance 't' of our union type</span>
    <span style="color: #06c; font-weight: bold;">let</span> f t <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">match</span> t <span style="color: #06c; font-weight: bold;">with</span> One <span style="color: #000080;">&#40;</span>a,b<span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span> printf <span style="color: #008080;">&quot;Got One&quot;</span> <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #060; font-style: italic;">// Apply our function with a particular TestDU union case</span>
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> f <span style="color: #000080;">&lt;|</span> Two <span style="color: #008080;">&quot;foo&quot;</span></pre></div></div>

<p>That&#8217;s pretty natural, as you&#8217;d expect. If we exposed the function <code>f</code> to C#, it looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">void</span> Module1.<span style="color: #0000FF;">f</span><span style="color: #000000;">&#40;</span>Module1.<span style="color: #0000FF;">TestDU</span> t<span style="color: #000000;">&#41;</span></pre></div></div>

<p>This means we have to create an instance of the <code>TestDU</code> type, but we&#8217;ll quickly discover it&#8217;s abstract. As I mentioned before, the F# compiler has generated a very simple class hierarchy, with the union cases being subtypes of <code>TestDU</code>, implemented as <a href="http://msdn.microsoft.com/en-us/library/ms173120.aspx">nested types</a> (which are used quite extensively by the F# compiler). But if we try and instantiate one of these subtypes&#8230;?<br />
<div id="attachment_1171" class="wp-caption alignleft" style="width: 427px"><a href="http://www.voyce.com/wp-content/uploads/2011/05/testdu_noctors.png"><img src="http://www.voyce.com/wp-content/uploads/2011/05/testdu_noctors.png" alt="The union case types have no constructors." title="testdu_noctors" width="417" height="106" class="size-full wp-image-1171" /></a><p class="wp-caption-text">The union case types have no constructors.</p></div><br />
Ouch: &#8216;No constructors defined&#8217;. Luckily, instead there are helper functions on the base class that will create instances for us, at least for those cases with arguments. The functions are prefixed with &#8216;New&#8217;, e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var one <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">NewOne</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    var two <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">NewTwo</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;foo&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And slightly oddly, the parameterless cases (<code>Three</code> in our example) use a property on the base class instead:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var three <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">Three</span><span style="color: #008000;">;</span></pre></div></div>

<p>So now we can create instances of the union type to pass to the F# function.</p>
<p>But what if we&#8217;re returned one instead? It will be of type <code>TestDU</code>, so how do we know what case it actually is? And how do we get to the parameters? Well, as we know it&#8217;s going to be one of the subtypes, we could use the C# &#8216;is&#8217; operator to determine its identity, but the base class also provides helper methods to do it for us, prefixed with <code>Is</code>, e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>two.<span style="color: #0000FF;">IsTwo</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var x <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>two <span style="color: #0600FF;">as</span> Module1.<span style="color: #0000FF;">TestDU</span>.<span style="color: #0000FF;">Two</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Item</span><span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">// Do something with x</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>As you can see, <code>Item</code> contains the case value. For tupled types this becomes <code>Item1</code>, <code>Item2</code> etc.</p>
<h3>Records</h3>
<p>Records are immutable types that contain fields, they tend to be used quite a lot in F# code, and luckily using them from C# is very straightforward. The only thing to remember is that they&#8217;re only constructor is the one taking all of the field values (because they&#8217;re immutable), e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">type</span> TestRecord <span style="color: #000080;">=</span>
        <span style="color: #000080;">&#123;</span>
        field1 <span style="color: #000080;">:</span> int
        field2 <span style="color: #000080;">:</span> string
        <span style="color: #000080;">&#125;</span></pre></div></div>

<p>Can be instantiated like this in C#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var r <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Module1.<span style="color: #0000FF;">TestRecord</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #666666;">&quot;foo&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3>Functions</h3>
<p>It&#8217;s usual in F# to use curried functions. That is, functions that can be applied one argument at a time, returning a partially applied function. It turns out that the compiler maps this type of function (when directly exposed, as a public function on a module, say) into its tupled equivalent, which makes them easily callable directly from C#. For instance:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">public</span> adder a b <span style="color: #000080;">=</span> a <span style="color: #000080;">+</span> b</pre></div></div>

<p>Has a native F# signature of <code>int -> int -> int</code>, but results in a generated CIL function taking a tuple of two ints, with signature more like <code>int * int -> int</code>.</p>
<p>But there are more complicated cases; F# functions can take functions and return them. When we&#8217;re dealing with functions in a first-class way like this, we can use the generic <code>Microsoft.FSharp.Core.FSharpFunc</code> type. For example:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">public</span> adder a b <span style="color: #000080;">=</span> a <span style="color: #000080;">+</span> b
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">public</span> addOne <span style="color: #000080;">=</span> adder <span style="color: #c6c;">1</span></pre></div></div>

<p>Where <code>addOne</code> is a function that returns a partially applied function. Calling it from F# is a breeze:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> x <span style="color: #000080;">=</span> addOne <span style="color: #c6c;">100</span></pre></div></div>

<p>But from C# it&#8217;s a bit trickier. The function returns an FSharpFunc, that we then need to apply with <code>Invoke</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    Microsoft.<span style="color: #0000FF;">FSharp</span>.<span style="color: #0000FF;">Core</span>.<span style="color: #0000FF;">FSharpFunc</span><span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>,<span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span> f <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">addOne</span><span style="color: #008000;">;</span>
    var x <span style="color: #008000;">=</span> f.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">100</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Although obviously you can combine this into a single line, and remove some of the type signatures (which I tend to do as much as possible using <code>var</code> when writing C# code):</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    var x <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">addOne</span>.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">100</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Things get even nastier if you happen to expose an F# function that takes a function. For example, a function that takes another function and applies it to two arguments:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> apply op a b <span style="color: #000080;">=</span> op a b</pre></div></div>

<p>In F# interactive we can see that this has the following, nicely generalised type signature:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">val</span> apply <span style="color: #000080;">:</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">'</span>a <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>b <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>c<span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>a <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>b <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">'</span>c</pre></div></div>

<p>i.e. it&#8217;s a function that takes as its first argument a function that takes an &#8216;a and a &#8216;b and returns a &#8216;c, it also accepts the &#8216;a and &#8216;b to pass to this function, and returns the &#8216;c result. Clear as. We may well want to create a version of this that uses the integer operator +, which is trivial from F#:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> add a b <span style="color: #000080;">=</span> apply <span style="color: #000080;">&#40;</span><span style="color: #000080;">+</span><span style="color: #000080;">&#41;</span> a b</pre></div></div>

<p>So how does it look if we try and do that from C#? In a word: messy. We have to use the <code>Microsoft.FSharp.Core.FuncConvert.ToFSharpFunc</code> helper functions, along with the .NET framework <code>Converter</code> as a way of specifying a generic, value-returning function.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.FSharp.Core</span><span style="color: #008000;">;</span>
...
    <span style="color: #0000FF;">var</span> op <span style="color: #008000;">=</span> FuncConvert.<span style="color: #0000FF;">ToFSharpFunc</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Converter<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>, FSharpFunc<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>, <span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>aa<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> FuncConvert.<span style="color: #0000FF;">ToFSharpFunc</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Converter<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span>, <span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>bb<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// The 'meat' of the function. Hmmm...</span>
                <span style="color: #0600FF;">return</span> aa <span style="color: #008000;">+</span> bb<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    var zz <span style="color: #008000;">=</span> Module1.<span style="color: #0000FF;">apply</span><span style="color: #000000;">&#40;</span>op, <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Whoa. That&#8217;s enough for now. As you can see, the various different ways of interoperating between F# and C# range from the neat to the nasty. The trick is definitely to pick your battles. Think carefully about what you need to expose and remember it&#8217;s probably best not to cross the beams if you can avoid it. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/05/09/mixing-it-up-when-f-meets-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

