<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Seshbot Programs]]></title>
  <link href="http://seshbot.com/atom.xml" rel="self"/>
  <link href="http://seshbot.com/"/>
  <updated>2015-09-24T03:35:57+00:00</updated>
  <id>http://seshbot.com/</id>
  <author>
    <name><![CDATA[Paul Cechner]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Practical Covariance and Contravariance]]></title>
    <link href="http://seshbot.com/blog/2015/09/21/co-and-contra-variance-made-easy/"/>
    <updated>2015-09-21T10:03:45+00:00</updated>
    <id>http://seshbot.com/blog/2015/09/21/co-and-contra-variance-made-easy</id>
    <content type="html"><![CDATA[<p><em>For a more in-depth rundown on covariance and contravariance explained in terms of category theory have a look at <a href="http://tomasp.net/blog/variance-explained.aspx/">Thomas Patricek&rsquo;s blog</a></em></p>

<p>Covariance and contravariance are things you&rsquo;ll probably ignore until you start using generics in ernest. Then one day you&rsquo;ll want to pass an enumerable to a function that takes a slightly different yet related type of enumerable and then <em>BAM</em> &ndash; you&rsquo;re hit with some crazy error messages and then all of a sudden you&rsquo;re up to your elbows in browser tabs of StackOverflow articles.</p>

<p>To cut straight to the chase, this is the problem:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="n">Base</span> <span class="n">rawBase</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Derived</span><span class="p">();</span> <span class="c1">// this works</span>
</span><span class='line'><span class="n">MyType</span><span class="p">&lt;</span><span class="n">Base</span><span class="p">&gt;</span> <span class="n">wrappedBase</span> <span class="p">=</span> <span class="k">new</span> <span class="n">MyType</span><span class="p">&lt;</span><span class="n">Derived</span><span class="p">&gt;();</span> <span class="c1">// ERROR!</span>
</span></code></pre></td></tr></table></div></figure>


<p>Sometimes we want the OO polymorphism substitution rules (AKA Liskov&rsquo;s substitution principle) to apply to generic types too. Covariance and contravariance provide us a mechanism to allow this substitution to take place.</p>

<p><span class='pullquote-right' data-pullquote='[co|contra]variance are necessitated due to the interaction of two different forms of polymorphism - object inheritance and generic typing'>
To be more specific, [co|contra]variance are necessitated due to the interaction of two different forms of polymorphism &ndash; object inheritance and generic typing. And yet sometimes you want to combine the two &ndash; while <code>MyType&lt;T&gt;</code> and <code>MyType&lt;U&gt;</code> share no inheritance relationship and therefore are not substitutable for each other, sometimes you want to treat them as if they are substitutable if <code>T</code> and <code>U</code> are themselves related.
</span></p>

<p>So a covariant or contravariant generic type (e.g., a <code>IEnumerable&lt;T&gt;</code>) might be bound to other references of that type (e.g., <code>IEnumerable&lt;U&gt;</code>) when there is an inheritance relationship between the two predicated types. This allows you to pass your <code>IEnumerable&lt;Employee&gt;</code> to a function that actually accepts an <code>IEnumerable&lt;Person&gt;</code> without the compiler complaining that they are different types.</p>

<p><span class='pullquote-left' data-pullquote='if Dog is-a-kind-of Animal, is it true that MyType&lt;Dog&gt; can-be-used-as-a MyType&lt;Animal&gt;?'>
The rule of thumb with inheritance is that if U inherits from T you could say that <em>U is-a-kind-of T</em>. With covariant and contravariant types, I like to think of them in terms of <em>can-be-used-as-a</em> relationship. To determine if <code>MyType</code> should be covariant or contravariant you could ask if Dog is-a-kind-of Animal, is it true that MyType&lt;Dog&gt; can-be-used-as-a MyType&lt;Animal&gt;?
</span></p>

<p><em>Covariance</em> and <em>contravariance</em> are two different ways that differently specialised generic types should themselves be substitutable for each other like derived types are:</p>

<p><strong>Covariance</strong>: <code>MyType&lt;T&gt;</code> is covariant if typing <code>MyType&lt;Base&gt; x = new MyType&lt;Derived&gt;()</code> makes sense (this looks very much like standard substitution rules.)</p>

<p>An example of this is an <code>IEnumerable</code>-derived type, and is classified as having methods that <em>return</em> the predicated type, or <em>getters</em> (hence C# uses the <code>out</code> keyword.)</p>

<p>The implication is that the relationship between the covariant generic types is the <strong>same</strong> as the relationship between their predicated types, e.g.:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">Base</span> <span class="n">b</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Derived</span><span class="p">();</span> <span class="c1">// OK because of Liskov substitution</span>
</span><span class='line'>
</span><span class='line'><span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">Derived</span><span class="p">&gt;</span> <span class="n">ds</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Derived</span><span class="p">&gt;();</span>
</span><span class='line'><span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">Base</span><span class="p">&gt;</span> <span class="n">bs</span> <span class="p">=</span> <span class="n">ds</span><span class="p">;</span> <span class="c1">// OK because IEnumerable is covariant</span>
</span><span class='line'><span class="n">Base</span> <span class="n">first</span> <span class="p">=</span> <span class="n">bs</span><span class="p">.</span><span class="n">First</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p><strong>Contravariance</strong>: <code>MyType&lt;T&gt;</code> is contravariant if typing <code>MyType&lt;Derived&gt; x = new MyType&lt;Base&gt;()</code> makes sense.</p>

<p>An example of this is the .Net generic <code>Action</code> type, and is classified as having methods that <em>accept</em> the predicated type as a parameter, or <em>setters</em> (hence C# uses the <code>in</code> keyword.)</p>

<p>Contravariant types are probably less common than covariant types, and imply that the relationship between the generic types is the <strong>inverse</strong> of the relationship between their predicated types. E.g.:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">Action</span><span class="p">&lt;</span><span class="n">Base</span><span class="p">&gt;</span> <span class="n">b</span> <span class="p">=</span> <span class="n">_</span> <span class="p">=&gt;</span> <span class="p">{};</span>
</span><span class='line'><span class="n">Action</span><span class="p">&lt;</span><span class="n">Derived</span><span class="p">&gt;</span> <span class="n">d</span> <span class="p">=</span> <span class="n">b</span><span class="p">;</span> <span class="c1">// OK because Action is contravariant</span>
</span><span class='line'><span class="n">d</span><span class="p">.</span><span class="n">Invoke</span><span class="p">(</span><span class="k">new</span> <span class="n">Derived</span><span class="p">());</span> <span class="c1">// invoke alias &#39;d&#39;, actually invokes &#39;b&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<!-- more -->


<h2>Why they&rsquo;re helpful</h2>

<p>Covariance and contravariance are useful in all the ways that Liskov&rsquo;s substitution principle is useful with regular polymorphic types &ndash; they are a mechanism that lets you inform the compiler when it&rsquo;s safe to bind an instance of one generic type to a reference of the same generic type with a different generic parameter.</p>

<p>If you&rsquo;re writing an application you&rsquo;ll often have one library or area of your code where you deal with heterogeneous types of one category, lets say <code>Animal</code>s, yet in another area of your code you&rsquo;ll deal exclusively with another related type, lets say <code>Dog</code>s. (Note that in math these are called <em>categories</em> and there is a whole set of theories in how to reason about them. See <a href="http://tomasp.net/blog/variance-explained.aspx/">Thomas Patricek&rsquo;s blog</a> for more details.)</p>

<p>To be very clear, covariance and contravariance only applies to:</p>

<ul>
<li>generic types</li>
<li>where the predicated types have an inheritence relationship</li>
<li>where a concrete object of that generic type is being bound to a reference (e.g., a passed as a parameter) of a different specialisation of that type</li>
</ul>


<h3>Liskov substitution without generics</h3>

<p>For example as a reminder of the standard substitution rules:</p>

<figure class='code'><figcaption><span>(C#) example of OO substitution rules in action</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">class</span> <span class="nc">Animal</span> <span class="p">{};</span>
</span><span class='line'><span class="k">class</span> <span class="nc">Dog</span> <span class="p">:</span> <span class="n">Animal</span> <span class="p">{};</span>
</span><span class='line'><span class="k">class</span> <span class="nc">Poodle</span> <span class="p">:</span> <span class="n">Dog</span> <span class="p">{};</span>
</span><span class='line'>
</span><span class='line'><span class="k">void</span> <span class="nf">SaveDog</span><span class="p">(</span><span class="n">Dog</span> <span class="n">dog</span><span class="p">)</span> <span class="p">{</span> <span class="p">...</span> <span class="p">}</span>
</span><span class='line'><span class="n">Dog</span> <span class="nf">LoadDog</span><span class="p">()</span> <span class="p">{</span> <span class="p">...</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">Animal</span> <span class="n">myAnimal</span> <span class="p">=</span> <span class="p">...</span> <span class="p">;</span>
</span><span class='line'><span class="n">SaveDog</span><span class="p">(</span><span class="n">myAnimal</span><span class="p">);</span> <span class="c1">// ERROR - myAnimal might be a cat!</span>
</span><span class='line'><span class="n">Animal</span> <span class="n">myAnimal2</span> <span class="p">=</span> <span class="n">LoadDog</span><span class="p">();</span> <span class="c1">// OK - dog is a kind of animal</span>
</span><span class='line'>
</span><span class='line'><span class="n">Poodle</span> <span class="n">myPoodle</span> <span class="p">=</span> <span class="p">...;</span>
</span><span class='line'><span class="n">SaveDog</span><span class="p">(</span><span class="n">myPoodle</span><span class="p">);</span> <span class="c1">// OK - poodle is a kind of dog</span>
</span><span class='line'><span class="n">Poodle</span> <span class="n">myPoodle2</span> <span class="p">=</span> <span class="n">LoadDog</span><span class="p">();</span> <span class="c1">// ERROR - LoadDog might return a non-poodle dog!</span>
</span></code></pre></td></tr></table></div></figure>


<p>OK cool, this is just how polymorphism works in OO languages. But here&rsquo;s where it gets confusing &ndash; what about generic types that are predicated on those types? E.g., a <code>IEnumerable&lt;Dog&gt;</code> or a <code>Action&lt;Dog&gt;</code>?</p>

<h3>Liskov&rsquo;s substitution of generic types</h3>

<p>Covariance and Contravariance hints tell the compiler to allow <em>references</em> to generic types to obey the same rules as polymorphic types! It doesn&rsquo;t affect how you can use a particular type directly, but it affects what other types of that generic object it can be bound to (when being passed to or returned from functions, for example).</p>

<p>To extend the previous example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// should be covariant but is not</span>
</span><span class='line'><span class="k">interface</span> <span class="n">IReader</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">T</span> <span class="nf">Read</span><span class="p">()</span> <span class="p">{...};</span> <span class="c1">// simplified interface</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// should be contravariant but is not</span>
</span><span class='line'><span class="k">interface</span> <span class="n">IWriter</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">void</span> <span class="nf">Write</span><span class="p">(</span><span class="n">T</span> <span class="n">entity</span><span class="p">);</span> <span class="c1">// simplified interface</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">void</span> <span class="nf">PrintDogFrom</span><span class="p">(</span><span class="n">IReader</span><span class="p">&lt;</span><span class="n">Dog</span><span class="p">&gt;</span> <span class="n">dogReader</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">Dog</span> <span class="n">dog</span> <span class="p">=</span> <span class="n">dogReader</span><span class="p">.</span><span class="n">Read</span><span class="p">();</span>
</span><span class='line'>  <span class="c1">// ... print dog info or something</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">void</span> <span class="nf">WriteDogTo</span><span class="p">(</span><span class="n">IWriter</span><span class="p">&lt;</span><span class="n">Dog</span><span class="p">&gt;</span> <span class="n">dogWriter</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">dogWriter</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="k">new</span> <span class="n">Poodle</span><span class="p">());</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// demonstrating a typical &#39;reading&#39; usage scenario</span>
</span><span class='line'><span class="c1">// that should work ideally</span>
</span><span class='line'>
</span><span class='line'><span class="n">IReader</span><span class="p">&lt;</span><span class="n">Poodle</span><span class="p">&gt;</span> <span class="n">poodleReader</span> <span class="p">=</span> <span class="p">...;</span> <span class="c1">// init somehow</span>
</span><span class='line'><span class="n">PrintDogFrom</span><span class="p">(</span><span class="n">poodleReader</span><span class="p">);</span> <span class="c1">// ERROR! (IReader&lt;Poodle&gt; != IReader&lt;Dog&gt;)</span>
</span><span class='line'><span class="c1">// BUT it should be OK (poodles are dogs)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// demonstrating a typical &#39;writing&#39; usage scenario</span>
</span><span class='line'><span class="c1">// that should work ideally</span>
</span><span class='line'>
</span><span class='line'><span class="n">IWriter</span><span class="p">&lt;</span><span class="n">Animal</span><span class="p">&gt;</span> <span class="n">animalWriter</span> <span class="p">=</span> <span class="p">...;</span> <span class="c1">// init somehow</span>
</span><span class='line'><span class="n">WriteDogTo</span><span class="p">(</span><span class="n">animalWriter</span><span class="p">);</span> <span class="c1">// ERROR! (IWriter&lt;Animal&gt; != IWriter&lt;Dog&gt;)</span>
</span><span class='line'><span class="c1">// BUT it should be OK (writer holds animals, can write dogs)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We recognise that a <code>IReader&lt;Poodle&gt;</code> instance should be able to be bound to a <code>IReader&lt;Dog&gt;</code> reference if <code>Poodle</code> is a <em>subclass</em> of <code>Dog</code>. This is known as <em>covariance</em> and is denoted in C# by labeling the generic type with the <code>out</code> keyword:</p>

<p>We can also see that <code>IWriter&lt;Dog&gt;</code> should be able to be bound to <code>IWriter&lt;Animal&gt;</code> if <code>Animal</code> is a <em>superclass</em> of <code>Dog</code>. This is known as <em>contravariance</em> and is denoted in C# by labeling the generic type with the <code>in</code> keyword.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// IReader is covariant on T</span>
</span><span class='line'><span class="k">interface</span> <span class="n">IReader</span><span class="p">&lt;</span><span class="k">out</span> <span class="n">T</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>  <span class="p">...</span> <span class="c1">// as before</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// IWriter is contravariant on T</span>
</span><span class='line'><span class="k">interface</span> <span class="n">IWriter</span><span class="p">&lt;</span><span class="k">in</span> <span class="n">T</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>  <span class="p">...</span> <span class="c1">// as before</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The difference in the two interfaces is simple &ndash; covariance is used when the dependent type is retrieved out of the generic type (an example would be how an <code>IEnumerable&lt;T&gt;</code> returns objects of type <code>T</code> and therefore is <em>covariant on T</em>). A generic type should be contravariant if it accepts the dependent type as input into its interface (an example would be how an <code>Action&lt;T&gt;</code> takes an instance of <code>T</code> as input when it is run, therefore it is <em>contravariant on T</em>).</p>

<p>Here&rsquo;s an attempt to visually represent valid type conversions for a cass hierarchy, a representative covariant type (<code>IReader</code>) and a representative contravariant type (<code>IWriter</code>):</p>

<center><img src='http://seshbot.com/images/plantuml/4a7b89795c37ad6d72cdb20c2e4412ec.png'></center>


<h2>When should my interfaces be covariant or contravariant?</h2>

<p>I only add this when its needed, but one thing you&rsquo;ll find is that you cannot have a covariant or contravariant type if you are both returning and accepting the dependent type in your interface. This is why in C# <code>IEnumerable</code> is covariant but <code>IList</code> is not &ndash; because <code>IList</code> allows you to add elements to the collection as well as retrieve the elements in the collection.</p>

<p>Sometimes you will be forced to make your type covariant if you want to use it in certain ways. In this case you may have to separate out the reading part of your interface into a separate interface and have the generic parameter be covariant there only.</p>

<h2>A few language-specific quirks you might run across</h2>

<p>Although the samples here might suggest otherwise, C# only allows <em>interfaces</em>, not concrete classes, to be specified as covariant or contravariant.</p>

<p>Java never used to support variance specifications much to its detriment. Java arrays behave in a covariant way, but because the interface supports both retrieving and setting elements, the following compiles (or at least used to, I havent tried it recently:)</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">Dog</span><span class="p">[]</span> <span class="n">dogs</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Dog</span><span class="p">[</span><span class="m">10</span><span class="p">];</span> <span class="c1">// ...</span>
</span><span class='line'><span class="n">Animal</span><span class="p">[]</span> <span class="n">dogsAsAnimals</span> <span class="p">=</span> <span class="n">dogs</span><span class="p">;</span>
</span><span class='line'><span class="n">dogsAsAnimals</span><span class="p">[</span><span class="m">0</span><span class="p">]</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Cat</span><span class="p">();</span> <span class="c1">// whaa?</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Note: in researching this I discovered that C# arrays suffer from the same problem! Arrays in both languages will throw runtime exceptions when used illegally like this</em></p>

<p>C# has supported variance for a long time, but unfortunately there are some corners where they have not yet added it. I recently found out that <code>Task&lt;T&gt;</code> is not covariant, and so if you were implementing your own covariant type, its interface cannot return generic <code>Task&lt;&gt;</code> types, which is frustrating because thats what Microsoft strongly recommend you to do.</p>

<p>Example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">interface</span> <span class="n">IReader</span><span class="p">&lt;</span><span class="k">out</span> <span class="n">T</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">T</span> <span class="nf">GetNext</span><span class="p">();</span>
</span><span class='line'>  <span class="n">Task</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">GetNextAsync</span><span class="p">();</span> <span class="c1">// compile error! although this should be idiomatic!</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The official answer to this (well, <a href="http://stackoverflow.com/questions/12204755/can-should-tasktresult-be-wrapped-in-a-c-sharp-5-0-awaitable-which-is-covarian">Jon Skeet&rsquo;s</a> word is very highly considered) was that adding variance to your interfaces quickly gets complicated in some way and so try to make your types invariant, and I cannot answer to that. My solution was to have the interface return a non-generic <code>Task</code> and dynamically downcast it to the generic type when I used it. This is not great, but its also quite safe as you know for certain the type of the task.</p>

<p>C++ generics (templates) do not directly support the notion of covariance or contravariance, but they don&rsquo;t need to &ndash; templates are specialised at compile time to generate separate instances for each required specialisation, so generic types are often not required to be coerced into other generic types.</p>

<p>For example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='cpp'><span class='line'><span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="n">T</span><span class="o">&gt;</span>
</span><span class='line'><span class="kt">void</span> <span class="n">printBases</span><span class="p">(</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">T</span><span class="o">*&gt;</span> <span class="o">&amp;</span> <span class="n">bases</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">foreach</span> <span class="p">(</span><span class="k">auto</span> <span class="o">*</span> <span class="n">b</span> <span class="o">:</span> <span class="n">bases</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="n">b</span><span class="o">-&gt;</span><span class="n">Name</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="n">endl</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">vector</span><span class="o">&lt;</span><span class="n">Derived</span><span class="o">*&gt;</span> <span class="n">ds</span> <span class="p">{};</span>
</span><span class='line'><span class="n">printBases</span><span class="p">(</span><span class="n">ds</span><span class="p">);</span> <span class="c1">// works as long as Derived has Name() method</span>
</span><span class='line'>
</span><span class='line'><span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="n">T</span><span class="o">&gt;</span>
</span><span class='line'><span class="kt">void</span> <span class="n">addDerived</span><span class="p">(</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="o">&amp;</span> <span class="n">deriveds</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">deriveds</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="k">new</span> <span class="n">Derived</span><span class="p">{});</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">vector</span><span class="o">&lt;</span><span class="n">Base</span><span class="o">*&gt;</span> <span class="n">bs</span> <span class="p">{};</span>
</span><span class='line'><span class="n">addDerived</span><span class="p">(</span><span class="n">bs</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>The above code shows that C++&rsquo;s templates are generally sufficient for performing generic operations on generically encapsulated types. The only constraings put on the type passed to the function is that it has a <code>Name()</code> method (this is known as &lsquo;duck-typing&rsquo;). Note that these are completely type-safe, as the compiler generates fully typed code at compile time. If I tried to add a <code>Base</code> type to a <code>Derived</code> vector, for example, you would get the expected error because the compiler would recognise the type mismatch.</p>

<p>On a related topic, it is also worth noting that C++ allows a derived class&#8217; overridden virtual methods to have <em>covariant return types</em> such that:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='cpp'><span class='line'><span class="k">struct</span> <span class="n">Base</span> <span class="p">{};</span>
</span><span class='line'><span class="k">struct</span> <span class="n">Derived</span> <span class="o">:</span> <span class="n">Base</span> <span class="p">{};</span>
</span><span class='line'>
</span><span class='line'><span class="k">struct</span> <span class="n">BaseFactory</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">virtual</span> <span class="n">Base</span> <span class="o">*</span> <span class="n">create</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="k">new</span> <span class="n">Base</span><span class="p">{};</span> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="k">struct</span> <span class="n">DerivedFactory</span> <span class="o">:</span> <span class="n">BaseFactory</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">override</span> <span class="n">Derived</span> <span class="o">*</span> <span class="n">create</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="k">new</span> <span class="n">Derived</span><span class="p">{};</span> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="n">DerivedFactory</span> <span class="o">*</span> <span class="n">ds</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DerivedFactory</span><span class="p">();</span>
</span><span class='line'><span class="n">Derived</span> <span class="o">*</span> <span class="n">d</span> <span class="o">=</span> <span class="n">ds</span><span class="o">-&gt;</span><span class="n">create</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="n">BaseFactory</span> <span class="o">*</span> <span class="n">bs</span> <span class="o">=</span> <span class="n">ds</span><span class="p">;</span>
</span><span class='line'><span class="n">Base</span> <span class="o">*</span> <span class="n">b</span> <span class="o">=</span> <span class="n">bs</span><span class="o">-&gt;</span><span class="n">create</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>Java also supports covariant return types, but C# does not.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An Introduction to OpenGL - Getting Started]]></title>
    <link href="http://seshbot.com/blog/2015/05/05/an-introduction-to-opengl-getting-started/"/>
    <updated>2015-05-05T07:40:37+00:00</updated>
    <id>http://seshbot.com/blog/2015/05/05/an-introduction-to-opengl-getting-started</id>
    <content type="html"><![CDATA[<p><em>This article is a culmination of all the little notes I took while learning OpenGL over the last several months. It&rsquo;s mostly stuff that I found difficult to research plus a little summary of the differences between OpenGL versions.</em></p>

<p><em>What a daunting task!</em></p>

<p><em>If you have any recommendations on how this could be more beginner-friendly please tell me.</em></p>

<p><em>Also thanks <a href="http://greggman.com/">Gregg Tavares</a> for pointing out my various errors!</em></p>

<h2>Things I wish I knew when learning OpenGL</h2>

<p>The most important thing a programmer should know before deciding whether to learn OpenGL is that OpenGL is very low level, poorly documented and extremely crufty. This is because it is an API specification and not a product library per-se. It is up to the many various vendors to implement the API spec as best they can.</p>

<p><span class='pullquote-right' data-pullquote='Anyone looking to learn to use OpenGL will face a constant battle with finding relevant documentation for their chosen version on their chosen platform with their chosen extensions.'>
In its various incarnations OpenGL spans almost 20 years and at least 7 major revisions, including the embedded versions. Anyone looking to learn to use OpenGL will face a constant battle with finding relevant documentation for their chosen version on their chosen platform with their chosen extensions.
</span></p>

<p>The next thing to know about modern OpenGL is that these days it does very little legwork for you other than allowing you to run a program on the GPU. You will have to write the GPU shader programs that do everything from transforming your own application data into screen-space coordinates, to calculating the exact colour of every pixel on the screen incorporating lighting and shading algorithms that you implement yourself (fortunately linear algebra makes this stuff a lot simpler than it sounds!) So OpenGL will not do any inherently 3D stuff for you &ndash; most OpenGL commands and types are capable of describing 3D positions, directions and transformations but you have to do the grunt work yourself.</p>

<p>The third immediate concern &ndash; <em>OpenGL does not work out of the box</em>! An annoying truth is that OpenGL realistically requires supporting libraries in order to function, most importantly to create a context within which the rendering operations can work. It is very common to incorporating at least three libraries &ndash; one to generate a GL context into which you render, a matrix and vector manipulation library, and an extension loader for when you need a little more functionality than your platform provides.</p>

<p><span class='pullquote-left' data-pullquote='OpenGL is the only low-level graphics API supported on pretty much all platforms you&#8217;d want to render graphics on.'>
So why would you even consider it?! Why would you write a series of articles on a technology that scares you so much? The reason it has kept its relevance is because OpenGL is the only low-level graphics API supported on pretty much all platforms you&rsquo;d want to render graphics on. Because it is so very widely adopted it is still the defacto standard for developers wanting a powerful low-level intrinsics that work on multiple platforms.
</span></p>

<p>If you are only targeting Windows you might consider DirectX. If you don&rsquo;t need to interact directly with your shaders, and are happy to work at a higher level of abstraction and not with the GPU directly, perhaps a higher level graphics library such as Unity or UDK would work better for you.</p>

<p>So assuming you still want to start using OpenGL, this article might be helpful to you. My intention is to mention a lot of stuff I had to hunt around for that seemed pretty important to me while I was trying to learn it myself. I will not be doing a step-by-step guide to performing specific OpenGL tasks however &ndash; for a good getting started guide check out <a href="https://open.gl/">open.gl</a> which is both modern and easy to follow.</p>

<p>To use OpenGL effectively I figure you&rsquo;d need to understand:</p>

<ul>
<li>opening an OpenGL window (i.e., creating a context)</li>
<li>the basics of rendering:

<ul>
<li>primitives, vertices and fragments</li>
<li>coordinate systems:

<ul>
<li>built-in normalised device coordinates (NDC) and clip coordinates</li>
<li>3D model, view and perspective coordinates</li>
</ul>
</li>
<li>shaders and the render pipeline (how data gets from your app to the screen):

<ul>
<li>vertex and fragment shaders</li>
<li>passing uniforms and attributes into the pipeline</li>
<li>vertex buffers (VBOs)</li>
<li>passing varying data from the vertex shader to the fragment shader</li>
</ul>
</li>
<li>the fixed-function pipeline (now deprecated)</li>
</ul>
</li>
<li>linear algebra (the magical language of graphics programming)</li>
<li>a rundown on all the different major OpenGL versions</li>
<li>major challenges that you certainly will face moving forward</li>
</ul>


<p>I&rsquo;ll leave more advanced core concepts such as framebuffers and textures for a later article.</p>

<!-- more -->


<h2>Starting a new project</h2>

<p>I suppose this is the most important thing to a lot of people, so I&rsquo;ll show how I bootstrap a new OpenGL project. I haven&rsquo;t been at it long so take it with a grain of salt, but I tried to focus on building a cross-platform solution.</p>

<p>I generally depend on four libraries. Although technically you could get away without any supporting libraries, these save a lot of time and effort. The libraries are:</p>

<ul>
<li>Google&rsquo;s <a href="https://code.google.com/p/angleproject/">ANGLE project</a> provides an OpenGL ES 2.0 (soon 3.0) driver library for Windows that wraps Direct3D. This is useful so you don&rsquo;t have to depend on the user downloading the OpenGL drivers for their graphics card on Windows.</li>
<li><a href="glfw.org">GLFW</a> to create a window and otherwise interact with the OS and other devices. Many people prefer <a href="https://www.libsdl.org/">SDL2</a> or <a href="https://www.opengl.org/resources/libraries/glut/">GLUT</a>. Alternatively you could use the standard low-level supporting libraries supported by your operating system &ndash; WGL, GLX or EGL.</li>
<li><a href="glm.g-truc.net">GLM</a> is a widely used vector and matrix library. It&rsquo;s particularly nice because it mirrors GLSL standard types and operations as much as possible, so hopefully there&rsquo;s some learning synergies there. I have tried using <a href="http://eigen.tuxfamily.org/">Eigen</a> which is more of a general linear algebra library focusing on performance, but it has a lot of limitations on how you can use (passing or storing types by value is complicated) it because it uses low-level processor vector operations under the covers. Of course you could always write your own matrix classes, but it&rsquo;s a pretty big task.</li>
<li><a href="http://glew.sourceforge.net/">GLEW</a> is a commonly used extension loader. Unfortunately extension loaders in general don&rsquo;t seem to work with ANGLE so I haven&rsquo;t used it much. <a href="https://github.com/hpicgs/glbinding">glbinding</a> and <a href="https://bitbucket.org/alfonse/glloadgen/wiki/Home">glLoadGen</a> are both code generators that create loaders for specific target versions of OpenGL. These don&rsquo;t seem to be able to target OpenGL ES versions however.</li>
</ul>


<p>I have created a <a href="https://github.com/seshbot/new-gl-app">simple GL application on GitHub</a> that I intended to be used as a starting point for OpenGL ES 2 experimentation. It should work on Windows, Linux and OSX, and the only external dependency should be CMake which is pretty easy to install. Then, hopefully, getting it running is a matter of (depending on your platform of choice):</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>git clone https://github.com/seshbot/new-gl-app
</span><span class='line'><span class="nb">cd </span>new-gl-app
</span><span class='line'>mkdir build <span class="o">&amp;&amp;</span> <span class="nb">cd </span>build
</span><span class='line'>cmake ..
</span><span class='line'>
</span><span class='line'>./glapp
</span></code></pre></td></tr></table></div></figure>


<p>Alternatively you could try copying <a href="http://seshbot.com/assets/2015-05-13-gl1.html">my sample GL HTML page</a> and copy the <a href="http://seshbot.com/assets/js/webgl-utils.js">webgl-utils.js</a> file into a subdirectory called &lsquo;js&rsquo; under that. Run the HTML file in your browser and you&rsquo;ll have a WebGL app!</p>

<h2>Understanding the OpenGL API</h2>

<p><em>Note:</em> I&rsquo;m using OpenGL ES 2 GLSL syntax in my examples because I believe that&rsquo;s probably got the broadest platform support, and is most similar to WebGL. The concepts are the same for later versions, aside from the syntactic differences. As I am focusing on explaining core concepts only OpenGL ES 2 should be fine for my purposes.</p>

<p>Take a moment to read some OpenGL specifications &ndash; they are probably easier to understand than you&rsquo;d think. Here&rsquo;s the <a href="https://www.khronos.org/registry/gles/specs/2.0/es_full_spec_2.0.25.pdf">OpenGL ES 2.0 Spec</a> if you want a definitive source for all this stuff.</p>

<p>I will probably mention the Khronos Group a lot throughout this article. The <a href="http://khronos.org">Khronos Group</a> is a consortium of companies such as Sun Microsystems, NVidia and Silicon Graphics who work on standardising graphics APIs, including OpenGL. Part of their OpenGL standardisation process is to provide reference interfaces (header files) for each version of the API that vendor implementations should conform to.</p>

<p>Here&rsquo;s a bit of a glossary of terms and concepts that are necessary to become familiar with in order to be an effective OpenGL programmer.</p>

<h3>The OpenGL API &ndash; commands, enums and objects</h3>

<p>The OpenGL API consists entirely of commands (e.g., <code>glDrawElements()</code>), enums (e.g., <code>GL_COLOR_BUFFER_BIT</code>) and, conceptually, objects.</p>

<p>The <strong>commands</strong> and <strong>enums</strong> are described in the specification but can also be browsed on the Khronos API header files &ndash; have a look at <a href="https://www.khronos.org/registry/gles/api/GLES2/gl2.h">GLES2/gl2.h</a> for the standard GLES2 header. Most vendor implementations use these exact files as the entry point for their libraries.</p>

<p>OpenGL <strong>objects</strong> are the conceptual entities you create using the API, such as vertex buffers (VBOs), vertex arrays (VAOs), shaders, programs, textures and framebuffers. OpenGL has commands to create, bind and delete each of the different types of objects. Note that the objects you create are only valid with the context that was active when you created them!</p>

<p>OpenGL commands that operate on OpenGL objects require those objects to be <em>bound</em>. For example when you call <code>glDrawElements()</code> you don&rsquo;t pass the program, the target framebuffer or the vertex or index buffer IDs to the function, it just operates on whichever program, framebuffer and vertex buffers are currently bound (through the <code>glUseProgram()</code>, <code>glBindFramebuffer()</code> and <code>glBindBuffer()</code> commands.) Many people feel this is a confusing and error-prone way to do things; it means that if you call some library or function that uses OpenGL there is no way to determine whether it has modified the current context in any way, so you have to re-bind all your stuff. It&rsquo;s unfortunate but that&rsquo;s the API we are stuck with :(</p>

<p><em>Note:</em> it is interesting to note that the <code>glCreate</code>-type functions don&rsquo;t actually create or allocate anything! They give you back a free handle, but that handle isn&rsquo;t actually allocated until it is bound. This means that technically you&rsquo;re free to keep track of these IDs yourself and allocate them according to whatever scheme you most desire, though I&rsquo;m not sure why you&rsquo;d do that.</p>

<h3>OpenGL context</h3>

<p><em>Here I&rsquo;ll describe the concepts involved in creating and using OpenGL contexts. For a more tutorial-type approach have a look at <a href="https://open.gl/context">this guide</a> that shows how to use several different popular context management libraries.</em></p>

<p>The <strong>context</strong> encapsulates the rendering view, its rendering settings and which OpenGL <em>objects</em> are currently active (such as which shader will be invoked during rendering). When starting your application you will need to create a context and set the capabilities you want the driver will use while rendering, such as whether the renderer will perform scissor, stencil, depth or alpha testing, how the renderer will blend fragments into final pixel colours and what part of the window to render into (the viewport). Contexts are not thread-safe (unfortunately!) and are essentially global in scope (even more unfortunately!) and are the cause of most of the grief people have with OpenGL.</p>

<p>You should avoid querying the state of the context too much if possible (i.e., querying information about bound objects, or even constantly querying error state) &ndash; it is apparently quite slow. You should also avoid accessing context from multiple different threads. I believe you are supposed to create separate contexts in each thread you wish to render from, or more preferably not render from multiple threads at all.</p>

<p>It is also possible to create a <em>shared context</em> where objects created on one context are available in another. This can be tricky so proceed with caution &ndash; for example, according to the spec shared contexts may not share framebuffer objects for some reason. I found that out <a href="https://code.google.com/p/angleproject/issues/detail?id=979">the hard way</a>.</p>

<p>Unfortunately the creation of an OpenGL context is not defined by the OpenGL spec. If you want to create one you&rsquo;ll either have to look up how to do this on your platform of choice (for example Windows provides WGL, while <a href="http://www.geeks3d.com/20121109/overview-of-opengl-support-on-os-x/">OSX</a> and Linux systems use GLX) or use another third-party library that does this for you (I like GLFW, but SDL2 is very popular, and some people still use the older GLUT.) These libraries often give you access to keyboard and mouse input as well as various other utilities you might need when making your app (such as buffer swapping, text, audio and the like.)</p>

<p>Below is a simple example of creating a context using GLFW in C or C++. For a line-by-line explanation of this see <a href="http://www.glfw.org/docs/latest/quick.html">the official GLFW docs</a>.</p>

<figure class='code'><figcaption><span>Creating a context with GLFW</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="cp">#include &lt;GLFW/glfw3.h&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="k">static</span> <span class="kt">void</span> <span class="n">key_callback</span><span class="p">(</span><span class="n">GLFWwindow</span><span class="o">*</span> <span class="n">window</span><span class="p">,</span> <span class="kt">int</span> <span class="n">key</span><span class="p">,</span> <span class="kt">int</span> <span class="n">scancode</span><span class="p">,</span> <span class="kt">int</span> <span class="n">action</span><span class="p">,</span> <span class="kt">int</span> <span class="n">mods</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="n">key</span> <span class="o">==</span> <span class="n">GLFW_KEY_ESCAPE</span> <span class="o">&amp;&amp;</span> <span class="n">action</span> <span class="o">==</span> <span class="n">GLFW_PRESS</span><span class="p">)</span>
</span><span class='line'>        <span class="n">glfwSetWindowShouldClose</span><span class="p">(</span><span class="n">window</span><span class="p">,</span> <span class="n">GL_TRUE</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">int</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">glfwInit</span><span class="p">())</span>
</span><span class='line'>      <span class="n">exit</span><span class="p">(</span><span class="n">EXIT_FAILURE</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// create context (unfortunately GLFW bundles this in with window creation)</span>
</span><span class='line'>  <span class="n">GLFWwindow</span><span class="o">*</span> <span class="n">window</span> <span class="o">=</span> <span class="n">glfwCreateWindow</span><span class="p">(</span><span class="mi">640</span><span class="p">,</span> <span class="mi">480</span><span class="p">,</span> <span class="s">&quot;Simple example&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">window</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="n">glfwTerminate</span><span class="p">();</span>
</span><span class='line'>    <span class="n">exit</span><span class="p">(</span><span class="n">EXIT_FAILURE</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="n">glfwMakeContextCurrent</span><span class="p">(</span><span class="n">window</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glfwSwapInterval</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="c1">// wait for a vsync before swapping to avoid &#39;tearing&#39;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// tell GLFW to notify us when keys are pressed (esc will exit)</span>
</span><span class='line'>  <span class="n">glfwSetKeyCallback</span><span class="p">(</span><span class="n">window</span><span class="p">,</span> <span class="n">key_callback</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">/////</span>
</span><span class='line'>  <span class="c1">// OpenGL configure context capabilities</span>
</span><span class='line'>  <span class="n">glClearColor</span><span class="p">(</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glEnable</span><span class="p">(</span><span class="n">GL_DEPTH_TEST</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glEnable</span><span class="p">(</span><span class="n">GL_BLEND</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glBlendFunc</span><span class="p">(</span><span class="n">GL_SRC_ALPHA</span><span class="p">,</span> <span class="n">GL_ONE_MINUS_SRC_ALPHA</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// TODO: create OpenGL objects (shader programs, vertex buffers, etc) here</span>
</span><span class='line'>  <span class="c1">///</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// main loop</span>
</span><span class='line'>  <span class="k">while</span> <span class="p">(</span><span class="o">!</span><span class="n">glfwWindowShouldClose</span><span class="p">(</span><span class="n">window</span><span class="p">))</span> <span class="p">{</span>
</span><span class='line'>    <span class="kt">int</span> <span class="n">width</span><span class="p">,</span> <span class="n">height</span><span class="p">;</span>
</span><span class='line'>    <span class="n">glfwGetFramebufferSize</span><span class="p">(</span><span class="n">window</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">width</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">height</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">/////</span>
</span><span class='line'>    <span class="c1">// OpenGL render</span>
</span><span class='line'>    <span class="n">glViewport</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">height</span><span class="p">);</span>
</span><span class='line'>    <span class="n">glClear</span><span class="p">(</span><span class="n">GL_COLOR_BUFFER_BIT</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// TODO: draw your primitives here!</span>
</span><span class='line'>    <span class="c1">///</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">glfwSwapBuffers</span><span class="p">(</span><span class="n">window</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// TODO: destroy OpenGL objects here</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">glfwDestroyWindow</span><span class="p">(</span><span class="n">window</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glfwTerminate</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">exit</span><span class="p">(</span><span class="n">EXIT_SUCCESS</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Most OpenGL context management libraries are very similar in usage to this.</p>

<h3>Primitives, Vertices and Fragments</h3>

<p>Each time you call an OpenGL drawing function you are drawing a <strong>primitive</strong>. You can think of a primitive as a shape of some kind that can be either 2D or 3D and rendered as a collection of points, lines or triangles.</p>

<p>You specify the primitive type you want to draw when invoking <code>glDrawElements()</code> or <code>glDrawArrays()</code>. Among the valid types are:</p>

<ul>
<li><code>GL_TRIANGLES</code>, which uses each 3 vectors to create a triangle. If you provide 9 vertices you will draw 3 triangles.</li>
<li><code>GL_TRIANGLE_STRIP</code> is more complicated in that it will use each set of 3 consecutive vertices to draw a triangle. In other words if you supply 4 vertices it will draw 2 triangles &ndash; one from v0, v1 and v2, another from v2, v1, v3. Notice that the first two vertices of every second triangle are re-ordered &ndash; this is to ensure that the triangles all face the same direction, as triangle direction is derived from which direction the triangle&rsquo;s vertices appear to be counter-clockwise in order (relevant if face culling is enabled.)</li>
<li><code>GL_POINTS</code>, which renders unconnected dots. You can control the size of the points by calling the <code>glPointSize()</code> command in desktop GL or by setting the <code>gl_PointSize</code> GLSL variable in OpenGL ES. You can also apply a texture to the point to render more complex particles (the GPU passes your fragment a <code>gl_PointCoord</code> variable to indicate which texture UV coordinates you should render.)</li>
<li><code>GL_LINES</code> is useful for quickly drawing a wireframe of your model.</li>
<li>there are also <code>GL_LINE_STRIP</code>, <code>GL_LINE_LOOP</code>, <code>GL_TRIANGLE_FAN</code>, <code>GL_QUADS</code>, <code>GL_QUAD_STRIP</code> and <code>GL_POLYGON</code>.</li>
</ul>


<p>You will describe your primitives as collections of <strong>vertices</strong>. These vertices are passed to the GPU and it then transforms them to triangles then <em>rasterises</em> those triangles into <strong>fragments</strong>. These fragments may be filtered, blended and anti-aliased and ultimately may be drawn as pixels on your screen. So technically <em>fragments are not pixels</em>.</p>

<h3>Coordinate systems</h3>

<p>The OpenGL <strong>coordinate system</strong> is simple but requires some explanation &ndash; put simply, the range of visible coordinates within the viewport goes from -1.0 to 1.0 in the X, Y and Z directions. This coordinate space is known as <strong>normalized device coordinates</strong> or NDC, and anything falling outside of this range will not be rendered. The X and Y coordinates describe the horizontal and vertical component of the pixel (-1, -1 corresponds with the bottom left corner of the viewport) and the Z axis is the <em>depth</em> component that is used for depth testing (if enabled.) By default the NDC Z coordinates move <em>away from</em> the viewer, so +Z is into the screen.</p>

<p><img class="center" src="http://seshbot.com/images/upload/2015-05-09-gl_1_ndc.png" title="&#34;Normalised device coordinates (NDC). By convention XYZ shown as RGB&#34;" alt="&#34;Normalised device coordinates (NDC). By convention XYZ shown as RGB&#34;"></p>

<p>But <strong>you won&rsquo;t be using NDC directly</strong> &ndash; you will be rendering your primitives in what is known as <em>clip coordinates</em>, which are <em>very</em> similar to NDC except with a 4th dimension (x, y, z and w). You might be somewhat confused when you write your vertex shader, when setting the mandatory <code>gl_Position</code> variable with the vertex coordinates (described later) you&rsquo;ll notice it is a <code>vec4</code>. What&rsquo;s the 4th dimension for? It turns out the 4th dimension <em>w</em> is used for <em>perspective division</em>, which is super useful for 3D graphics but useless for 2D. For now you just have to know that when the GPU transforms from <em>clip coordinates</em> to <em>NDC</em> it calculates something like this: <code>ndc_coords = clip_coords.xyz / clip_coords.w</code>. So if rendering 2D stuff to the screen just set <code>gl_Position.w</code> to 1.0.</p>

<p>When programming in 2D you may choose to draw all your primitives using these NDC coordinates to avoid having to convert between coordinate spaces at all. The samples in this article draw primitives using normalised device coordinates directly.</p>

<p>3D coordinate systems are more complicated and I will discuss them in depth in a later article. For now it is interesting to note two things: first, by convention OpenGL coordinate systems other than NDC generally have the Z axis moving <em>towards</em> the viewer, so the <em>negative</em> Z axis goes into the screen.</p>

<p>Secondly, when rendering 3D primitives the verticies that describe the primitive are usually transformed in between a well defined sequence of coordinate spaces. The coordinates in the model&rsquo;s local <strong>model space</strong> are first moved to <strong>world space</strong> where their position and orientation is given relative to all other objects in a scene (the same model may be used many times in the one scene, but each will look different if they have different model space transformations.) Then the coordinates are transformed to <strong>view space</strong> where their position and orientation are relative to the viewer&rsquo;s eye. Then they are transformed into clip coordinates and finally NDC as before. I hope to go into more detail on this process in a later article &ndash; I just wanted to list the terms here for completeness.</p>

<p>One final thing I will mention about 3D coordinates is that it is common to specify 3D positions, directions and transformations using 4 dimensional vectors and matricies. I won&rsquo;t go into it now but it is very useful to remember that <em>positional</em> coordinates generally have a 4th dimension <em>w</em> set to 1.0 and <em>directions</em> generally have <em>w</em> set to 0. This makes the linear algebra work out nicely when multiplying against transformation matricies as the 4th dimension in the vector usually controls the translation factor of the transformation, which is not relevant for directions (i.e., a &lsquo;north&rsquo; pointing vector is stil pointing north no matter where the vector is located in space.)</p>

<h3>Shaders and the render pipeline</h3>

<p>Every time you call an OpenGL draw operation (the <code>glDrawArrays()</code> or <code>glDrawElements()</code> commands) you invoke the entire render pipeline. This is when the GPU passes the verticies in your primitives to your vertex shader, clips the resulting coordinates, generates triangles from the vertices, rasterises them into fragments, passes those fragments to your fragment shader then tests visibility, blends and dithers those fragments into pixels on your screen (or some other framebuffer.)</p>

<p>The difference between <code>glDrawArrays()</code> and <code>glDrawElements()</code> is in how the GPU knows which vertices to use when transforming your vertices into triangles. <code>glDrawArrays()</code> is simpler in that it builds triangles using the vertices in their given order &ndash; in a GL_TRIANGLES primitive, triangle T0 will be built from vertices V0, V1 and V2, triangle T1 built from V3, V4, V5 and so on.</p>

<p><code>glDrawElements()</code> is more complex but often more performant. Instead of using the vertex data strictly in the order you declared them, it uses a separate buffer called the <em>index buffer</em> (also known as the <em>element buffer</em>) to determine which vertices to use in which triangles. This is great because it allows you to reuse vertices to create multiple triangles &ndash; an index buffer of <code>[0, 1, 2, 2, 1, 3, 1, 0, 4]</code> will construct 3 triangles from only 5 vertices! The first triangle will be using v0, v1 and v2, the second using v2, v1, v3 and the third using v1, v0 and v4.</p>

<p><em>Note:</em> Vertex buffers are bound by invoking <code>glBindBuffer(GL_ARRAY_BUFFER, my_buff_loc)</code> and index buffers are bound with <code>glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, my_buff_loc)</code>. Don&rsquo;t ask me about the names.</p>

<h4>Pipeline summary</h4>

<p>To draw a primitive, the GPU first needs your <em>vertex data</em>. The GPU will decode your vertex data to extract <em>vertex attributes</em> and pass those into your <em>vertex shader</em> once for each vertex. Your vertex shader is expected to output clip coordinates for that vertex so the GPU knows where on the screen to show it (if at all,) and information that the GPU should pass on to your fragment shader for fragments derived from this vertex.</p>

<p>Once the GPU has processed all vertices the GPU can clip the vertices to within the NDC area only, it transforms those vertices into triangles and then <em>rasterises</em> the triangles into fragments which sort-of represent the pixels of the primitive being drawn. The GPU will then call your <em>fragment shader</em> for each fragment, passing it the relevant output data of your <em>vertex shader</em>. Your fragment shader is expected to output a colour and optionally a new depth-value for the fragment.</p>

<p>The GPU then processes, blends and dithers the fragments to the output framebuffer, as described under <em>how the GPU writes fragments to the framebuffer</em> a few pages down.</p>

<p>You invoke the rendering pipeline by calling either the <code>glDrawArrays()</code> or <code>glDrawElements()</code> commands (or one of their variations.) Unless you&rsquo;re using the fixed function pipeline you&rsquo;ll have to have a shader program bound so the GPU knows which vertex shader and fragment shader to invoke. You will also have to specify the vertex data (the vertex positions and perhaps other information such as the vertex normals and colours) of the primitive you are rendering. The &lsquo;basic shader program&rsquo; a few pages down shows one way to do both of these things.</p>

<center><img src='http://seshbot.com/images/plantuml/40c1ceacc43d3519b9e919430a1278c9.png'></center>


<p>Once again, if you want more details on how this works have a look at the specs, like the <a href="https://www.khronos.org/registry/gles/specs/2.0/es_full_spec_2.0.25.pdf">OpenGL ES 2.0 Spec</a>.</p>

<h4>Passing data to the GPU &ndash; uniforms, attributes and varyings</h4>

<p>There are two ways your application can pass data to your shaders &ndash; <em>uniforms</em> that are set only once per <code>glDraw*</code> call and and <em>attributes</em> that may be different per-vertex. In addition, fragment shaders receive per-fragment input derived from the output of the vertex shader in <em>varyings</em> (see the <em>rendering pipeline</em> diagram above.)</p>

<h5>Sending uniform data to the GPU</h5>

<p>A <em>uniform</em> represents a variable that remains the same for the rendering of an entire primitive. This might be something like the object material or the position of the sun. The pattern for setting a uniform is to first get a handle to the uniform with <code>glGetUniformLocation(my_program, "my_uniform")</code>. Pass this handle to the <code>glUniform*</code> functions to set the uniform (for example <code>glUniform3f()</code> will set a uniform of type <code>vec3</code> in your shader.) Setting a uniform will make it available in any of the shaders in the bound program that are want to use it.</p>

<p>In the code example a few pages down you can see how the unifrom data is bound and updated:</p>

<figure class='code'><figcaption><span>uniform updating snippet</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'>  <span class="k">auto</span> <span class="n">time_loc</span> <span class="o">=</span> <span class="n">glGetUniformLocation</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">,</span> <span class="s">&quot;time&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glUniform1f</span><span class="p">(</span><span class="n">time_loc</span><span class="p">,</span> <span class="n">glfwGetTime</span><span class="p">());</span>
</span></code></pre></td></tr></table></div></figure>


<p>Uniforms may also be structures and arrays &ndash; the syntax to declare and use structs and arrays in GLSL (the shader code) is very similar to C, but setting them from the client application is a little tricky.</p>

<p><em>To set uniform values in a structure</em>: you essentially treat the variable as if it is in the namespace of the structure name. E.g., if the shader contains the code <code>struct Point { float x; float y; }; uniform Point p1;</code> you can access <code>p1.x</code> with exactly that syntax: <code>auto u_p1x = glGetUniformLocation(my_program, "p1.x")</code>.</p>

<p><em>To set uniform values in an array</em>: you access the specific array element using standard C syntax. If the shader contains the code <code>float xs[10];</code> you can get the location of a particluar element of <code>xs</code> with <code>auto u_xs = glGetUniformLocation(my_program, "xs[0]")</code>. You can use this uniform location to either set a single element using <code>glUniform*()</code> or set a number of the elements using <code>glUniform*v()</code>.</p>

<p><em>Note:</em> that you cannot apply offsets to the returned uniform location to access specific array elements &ndash; in the above example, I cannot call <code>glUniform1f(u_xs + 2, 1.)</code> as that could be the location of a totally different uniform. In this case you would either have to find the location of the element you want to access directly (in this case <code>glGetUniformLocation(my_program, "xs[2]")</code>) or set multiple elements (using <code>glUniform*v()</code>) in the array starting from the index we retrieved.</p>

<h5>Sending vertex attribute data to the GPU</h5>

<p>An <em>attribute</em> represents data related to the current vertex being processed. You specify where the GPU can find vertex data by calling the <code>glVertexAttribPointer*</code> functions for each vertex attribute in your vertex shader. This process is <em>very</em> different to specifying uniforms!</p>

<p>The standard form for using a vertex attribute is something like:</p>

<figure class='code'><figcaption><span>setting vertex attribute data</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// ... first bind the appropriate shader</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// during initialisation</span>
</span><span class='line'><span class="n">GLint</span> <span class="n">position_loc</span> <span class="o">=</span> <span class="n">glGetAttribLocation</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">,</span> <span class="s">&quot;position&quot;</span><span class="p">);</span>
</span><span class='line'><span class="n">glEnableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'><span class="k">const</span> <span class="kt">float</span> <span class="n">vertex_buffer</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="p">...</span> <span class="p">};</span> <span class="c1">// x, y, z positions</span>
</span><span class='line'><span class="n">glVertexAttribPointer</span><span class="p">(</span><span class="n">position_loc</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">GL_FLOAT</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">vertex_buffer</span><span class="p">);</span>
</span><span class='line'><span class="n">glDisableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// at render time</span>
</span><span class='line'><span class="n">glEnableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'><span class="n">glDrawArrays</span><span class="p">(</span><span class="n">GL_TRIANGLES</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">4</span><span class="p">);</span> <span class="c1">// draw verts 0..4 as triangles</span>
</span><span class='line'><span class="n">glDisableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>The above code snippet illustrates how to passing a raw pointer to your vertex data to the GPU. This is not the usual case, because quite often your buffered data will interleave more than one attribute&rsquo;s worth of information (such as normals, vertex colours etc.) Usually you will create a <strong>vertex buffer object</strong> (VBO) and use <code>glVertexAttribPointer()</code> to dictate how the GPU should extract the vertex info from that.</p>

<p><em>vertex buffer objects</em> are created, bound and destroyed like any other OpenGL object. You specify the data to buffer by calling the <code>glBindBuffer()</code> command with a pointer to the buffer. While this buffer is bound, any calls to <code>glVertexAttribPointer()</code> with a non-pointer in the final parameter will implicitly be referring to the bound buffer, using the final parameter instead as an offset into the buffer where the data may be found. This is necessary for interleaving vertex data in the same buffer.</p>

<p>Having a single buffer with different types of vertex information interleaved is very common. Your two tools for describing how this buffer data is formatted are the above-mentioned <em>offset</em> parameter and the <em>stride</em> parameter. While the <em>offset</em> describes the starting byte of an attribute in the buffer, the <em>stride</em> describes the total distance (in bytes!) between the start of that attribute and the start of the next instance of that attribute. A stride of <code>0</code> is considered special &ndash; it is used if the attribute is &lsquo;tightly packed&rsquo;, meaning the buffer contains only that attribute with no space between them.</p>

<p>This is best illustrated with an example:</p>

<figure class='code'><figcaption><span>specifying attributes in an interleaved buffer</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="kt">float</span> <span class="n">positions_and_colours_buffer</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="o">-</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span>   <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span>   <span class="c1">// x, y,   r, g, b</span>
</span><span class='line'>  <span class="o">-</span><span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span>   <span class="c1">// x, y,   r, g, b</span>
</span><span class='line'>  <span class="c1">// ...</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'><span class="n">glBindBuffer</span><span class="p">(</span><span class="n">GL_ARRAY_BUFFER</span><span class="p">,</span> <span class="n">positions_and_colours_buffer</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="k">auto</span> <span class="n">position_offset</span> <span class="o">=</span> <span class="mi">0U</span><span class="p">;</span>  <span class="c1">// positions start 0 bytes in</span>
</span><span class='line'><span class="k">auto</span> <span class="n">colour_offset</span> <span class="o">=</span> <span class="mi">2</span> <span class="o">*</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">GLfloat</span><span class="p">);</span> <span class="c1">// normals start 8 bytes in</span>
</span><span class='line'><span class="kt">int</span> <span class="n">stride</span> <span class="o">=</span> <span class="mi">5</span> <span class="o">*</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">GLfloat</span><span class="p">);</span>  <span class="c1">// each vertex is total 10 bytes</span>
</span><span class='line'>
</span><span class='line'><span class="n">glVertexAttribPointer</span><span class="p">(</span><span class="n">position_loc</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">GL_FLOAT</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="n">stride</span><span class="p">,</span> <span class="p">(</span><span class="kt">void</span><span class="o">*</span><span class="p">)</span><span class="n">position_offset</span><span class="p">);</span>
</span><span class='line'><span class="n">glVertexAtrirbPointer</span><span class="p">(</span><span class="n">colour_loc</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">GL_FLOAT</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="n">stride</span><span class="p">,</span> <span class="p">(</span><span class="kt">void</span><span class="o">*</span><span class="p">)</span><span class="n">colour_offset</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Note</em>: in OpenGL 3.0 and above you will want to use <strong>vertex array objects</strong> (VAOs) to speed up your rendering process. A <em>VAO</em> offers you shorthand for binding vertex bufffers and the related vertex attributes for those buffers. This means that <code>glBindVertexArray()</code> can replace a number of <code>glBindBuffer()</code> and <code>glEnableVertexAttribArray()</code> commands.</p>

<p>The pattern for using this is:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// at init time when creating buffers</span>
</span><span class='line'><span class="n">glBindVertexArray</span><span class="p">(</span><span class="n">my_vao</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glBindBuffer</span><span class="p">(</span><span class="n">my_vbo</span><span class="p">);</span>
</span><span class='line'>  <span class="n">GLfloat</span> <span class="n">verts</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span>  <span class="mf">.5</span><span class="p">,</span> <span class="mf">.5</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">,</span> <span class="mf">.5</span> <span class="p">};</span>
</span><span class='line'>  <span class="n">glBufferData</span><span class="p">(</span><span class="n">GL_ARRAY_BUFFER</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">verts</span><span class="p">),</span> <span class="n">verts</span><span class="p">,</span> <span class="n">GL_STATIC_DRAW</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glEnableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glVertexAttribPointer</span><span class="p">(</span><span class="n">position_loc</span><span class="p">,</span> <span class="p">...);</span>
</span><span class='line'><span class="n">glBindVertexArray</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// at render time</span>
</span><span class='line'><span class="n">glBindVertexArray</span><span class="p">(</span><span class="n">my_vao</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glDrawElements</span><span class="p">(...);</span>
</span><span class='line'><span class="n">glBindVertexArray</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>I won&rsquo;t be illustrating those here because I am focusing on OpenGL ES 2.0 for this article.</p>

<h5>Sending per-fragment varyings to the fragment shader</h5>

<p><em>Varyings</em> are per-fragment data the fragment shader uses to calculate the output colour of a fragment. Examples of this might be the normal of the surface at that point, or the material colour interpolated from the material colours of the surrounding vertices. A 3D program will often use this information along with the location of the sun (passed through a uniform) in its lighting calculations &ndash; a fragment on a surface directly facing a light source will have a brighter colour than one not.</p>

<p>The calculation of what value is passed into a varying is a little bit tricky. Fragment shaders get their per-fragment input indirectly from the vertex shaders through variables called <em>varyings</em>. Of course for any three vertices forming a triangle you could have hundreds of fragments, so the GPU takes the varyings coming out of the vertex shader for each vertex influencing a fragment and interpolates them before passing them into the fragment shader.</p>

<h4>The Vertex Shader</h4>

<p>Below is a simple vertex shader that expects two input variables from the application: the uniform <code>time</code> and the vertex attribute <code>vert_position</code>.</p>

<figure class='code'><figcaption><span>a simple vertex shader</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// per-primitive variables passed in from your application</span>
</span><span class='line'><span class="n">uniform</span> <span class="kt">float</span> <span class="n">time</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// per-vertex variables passed in from your application</span>
</span><span class='line'><span class="n">attribute</span> <span class="n">vec4</span> <span class="n">vert_position</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// output data to send to the fragment shader for each fragment derived from this vertex</span>
</span><span class='line'><span class="n">varying</span> <span class="n">vec4</span> <span class="n">frag_colour</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// mandatory! calculate the NDC coordinates of this vertex</span>
</span><span class='line'>  <span class="n">gl_Position</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="mf">0.01</span> <span class="o">*</span> <span class="n">sin</span><span class="p">(</span><span class="n">time</span><span class="p">),</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">)</span> <span class="o">+</span> <span class="n">vert_position</span><span class="p">;</span>
</span><span class='line'>  <span class="c1">// frags go from black on the left side to red on the right side of the viewport</span>
</span><span class='line'>  <span class="n">frag_colour</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">((</span><span class="n">vert_position</span><span class="p">.</span><span class="n">x</span> <span class="o">+</span> <span class="mf">1.</span><span class="p">)</span> <span class="o">/</span> <span class="mf">2.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Note:</em> GLSL (the shader language) allows the specification of <em>precision</em> for floating-point values, including all <code>vec</code> and <code>mat</code> types. Some versions of GLSL (at least GLSL ES) <em>require</em> variable precisions to be specified in all declarations and parameter lists (I have omitted these for brevity in my examples.) Valid precision values are <code>lowp</code>, <code>mediump</code> and <code>highp</code>. In general <code>mediump</code> is what you want, although for colours you can use <code>lowp</code> without any problems.</p>

<h4>The Fragment Shader</h4>

<p>The fragment shader captures all the logic required to determine the colour of a fragment. This might be as simple as just returning a uniform RGBA value or might involve complex 3D shading calculations incorporating a number of light sources and shadow maps. I will explore the 3D stuff in a later article.</p>

<p>A simple fragment shader that works with the above vertex shader might look like this:</p>

<figure class='code'><figcaption><span>a simple fragment shader</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// per-primitive variables passed in from your application</span>
</span><span class='line'><span class="n">uniform</span> <span class="kt">float</span> <span class="n">time</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// interpolated from output data of vertex shader</span>
</span><span class='line'><span class="n">varying</span> <span class="n">vec4</span> <span class="n">frag_colour</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="n">frag_colour</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that the <code>varying</code> variables are not passed directly from the vertex shader but is actually interpolated from the results of all vertex shader invocations for the vertices surrounding this fragment. This means that, for example, colour gradients look smooth between vertices.</p>

<h4>How the GPU writes fragments to the FrameBuffer</h4>

<p>In this context the <em>framebuffer</em> is the rendering target, which is usually either the viewport or a texture. (Framebuffers are also used for other purposes such as combining multiple rendering passes that I will go into in a later article.) When the GPU has collected all the fragments it is going to render, it goes through a series of per-fragment operations to determine what gets written to the framebuffer.</p>

<p>First the GPU checks to ensure this bit of the viewport is actually owned by this framebuffer, because is possible to have one viewport obscuring another. Next the fragment is tested against the scissor test region, the stencil buffer, then the depth buffer, if those capabilities are enabled in current context. If a fragment fails one of these tests it is discarded. Then the GPU performs a blending operation if enabled on the context, blending the fragment against what is read from the framebuffer before the render operation began. The resultant fragment is finally written to the framebuffer. Furthermore, if the framebuffer has <em>multisampling</em> enabled (for anti-aliasing) it may merge multiple fragment colours (or <em>samples</em> as they are called now) into a single pixel.</p>

<h4>Basic shader program example</h4>

<p>The partial application code below shows a basic vertex shader, fragment shader being invoked to render a square in the middle of the window.</p>

<figure class='code'><figcaption><span>rendering a &#8216;triangle strip&#8217; primitive using a buffer of vertex positions</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
<span class='line-number'>62</span>
<span class='line-number'>63</span>
<span class='line-number'>64</span>
<span class='line-number'>65</span>
<span class='line-number'>66</span>
<span class='line-number'>67</span>
<span class='line-number'>68</span>
<span class='line-number'>69</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'>  <span class="c1">// just define our shader in-line</span>
</span><span class='line'>  <span class="k">const</span> <span class="kt">char</span> <span class="n">vertex_src</span><span class="p">[]</span> <span class="o">=</span> <span class="s">&quot;\</span>
</span><span class='line'><span class="s">    uniform float time;       // passed in for whole primitive </span><span class="se">\n</span>
</span><span class='line'>    <span class="n">attribute</span> <span class="n">vec2</span> <span class="n">position</span><span class="p">;</span>  <span class="c1">// passed in with vertex data \n</span>
</span><span class='line'>    <span class="n">attribute</span> <span class="n">vec3</span> <span class="n">colour</span><span class="p">;</span>    <span class="c1">// passed in with vertex data \n</span>
</span><span class='line'>    <span class="n">varying</span> <span class="n">vec4</span> <span class="n">frag_colour</span><span class="p">;</span> <span class="c1">// passed out to frag shader  \n</span>
</span><span class='line'>    <span class="kt">void</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>                                           <span class="err">\</span><span class="n">n</span>
</span><span class='line'>      <span class="c1">// this is where we would transform to NDC, but  our coordinates are already NDC</span>
</span><span class='line'>      <span class="c1">// so just pass the position through as-is with a little animation \n</span>
</span><span class='line'>      <span class="n">gl_Position</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">position</span> <span class="o">*</span> <span class="n">sin</span><span class="p">(</span><span class="n">time</span><span class="p">),</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">);</span>     <span class="err">\</span><span class="n">n</span>
</span><span class='line'>      <span class="n">frag_colour</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">colour</span><span class="p">,</span> <span class="mf">1.</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span><span class="s">&quot;;</span>
</span><span class='line'>  <span class="k">const</span> <span class="kt">char</span> <span class="n">fragment_src</span><span class="p">[]</span> <span class="o">=</span> <span class="s">&quot;\</span>
</span><span class='line'><span class="s">    varying vec4 frag_colour; // passed in from vert shader (and interpolated) </span><span class="se">\n</span>
</span><span class='line'>    <span class="kt">void</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>                              <span class="err">\</span><span class="n">n</span>
</span><span class='line'>      <span class="c1">// fragment colour is dark gray          \n</span>
</span><span class='line'>      <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="n">frag_colour</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span><span class="s">&quot;;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// create shaders</span>
</span><span class='line'>  <span class="k">auto</span> <span class="n">vertexShader</span> <span class="o">=</span> <span class="n">glCreateShader</span><span class="p">(</span><span class="n">GL_VERTEX_SHADER</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glShaderSource</span><span class="p">(</span><span class="n">vertexShader</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">vertex_src</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glCompileShader</span><span class="p">(</span><span class="n">vertexShader</span><span class="p">);</span>
</span><span class='line'>  <span class="k">auto</span> <span class="n">fragmentShader</span> <span class="o">=</span> <span class="n">glCreateShader</span><span class="p">(</span><span class="n">GL_FRAGMENT_SHADER</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glShaderSource</span><span class="p">(</span><span class="n">fragmentShader</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">fragment_src</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glCompileShader</span><span class="p">(</span><span class="n">fragmentShader</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// create shader program using the shaders</span>
</span><span class='line'>  <span class="n">GLuint</span> <span class="n">shaderProgram</span> <span class="o">=</span> <span class="n">glCreateProgram</span><span class="p">();</span>
</span><span class='line'>  <span class="n">glAttachShader</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">,</span> <span class="n">vertexShader</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glAttachShader</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">,</span> <span class="n">fragmentShader</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glLinkProgram</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">);</span>    <span class="c1">// link the program</span>
</span><span class='line'>  <span class="n">glUseProgram</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">);</span>    <span class="c1">// and select it for usage</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// these are the NDC coordinates of a square on the viewport</span>
</span><span class='line'>  <span class="k">static</span> <span class="k">const</span> <span class="kt">float</span> <span class="n">vertexArray</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>     <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">,</span>   <span class="mf">1.</span><span class="p">,</span> <span class="mf">.5</span><span class="p">,</span> <span class="mf">.5</span><span class="p">,</span>    <span class="c1">// x, y,  r, g, b,</span>
</span><span class='line'>     <span class="o">-</span><span class="mf">0.5</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span>  <span class="mf">.5</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">.5</span><span class="p">,</span>    <span class="c1">// x, y,  r, g, b,</span>
</span><span class='line'>     <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">,</span>   <span class="mf">1.</span><span class="p">,</span> <span class="mf">.5</span><span class="p">,</span> <span class="mf">.5</span><span class="p">,</span>    <span class="c1">// x, y,  r, g, b,</span>
</span><span class='line'>     <span class="mf">0.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.5</span><span class="p">,</span>  <span class="mf">.9</span><span class="p">,</span> <span class="mf">.9</span><span class="p">,</span> <span class="mf">.9</span><span class="p">,</span>    <span class="c1">// x, y,  r, g, b,</span>
</span><span class='line'>     <span class="mf">0.5</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span>   <span class="mf">.5</span><span class="p">,</span> <span class="mf">.5</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span>    <span class="c1">// x, y,  r, g, b,</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// we need this to pass the &#39;time&#39; uniform to the shaders</span>
</span><span class='line'>  <span class="k">auto</span> <span class="n">time_loc</span> <span class="o">=</span> <span class="n">glGetUniformLocation</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">,</span> <span class="s">&quot;time&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="c1">// we need this to pass the &#39;position&#39; and &#39;colour&#39; attributes in to the vertex shader</span>
</span><span class='line'>  <span class="k">auto</span> <span class="n">position_loc</span> <span class="o">=</span> <span class="n">glGetAttribLocation</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">,</span> <span class="s">&quot;position&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="k">auto</span> <span class="n">colour_loc</span> <span class="o">=</span> <span class="n">glGetAttribLocation</span><span class="p">(</span><span class="n">shaderProgram</span><span class="p">,</span> <span class="s">&quot;colour&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glEnableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glEnableVertexAttribArray</span><span class="p">(</span><span class="n">colour_loc</span><span class="p">);</span>
</span><span class='line'>  <span class="c1">// glVertexAttribPointer allows you to specify vertices in many ways, so its pretty complicated</span>
</span><span class='line'>  <span class="n">glVertexAttribPointer</span><span class="p">(</span><span class="n">position_loc</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">GL_FLOAT</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">GLfloat</span><span class="p">)</span> <span class="o">*</span> <span class="mi">5</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">GLfloat</span><span class="p">)</span> <span class="o">*</span> <span class="n">vertexArray</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glVertexAttribPointer</span><span class="p">(</span><span class="n">position_loc</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">GL_FLOAT</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">GLfloat</span><span class="p">)</span> <span class="o">*</span> <span class="mi">5</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">GLfloat</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">vertexArray</span> <span class="o">+</span> <span class="mi">2</span><span class="p">));</span>
</span><span class='line'>  <span class="n">glDisableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'>  <span class="n">glDisableVertexAttribArray</span><span class="p">(</span><span class="n">colour_loc</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">while</span> <span class="p">(</span><span class="o">!</span><span class="n">quit</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// ... clear viewport etc </span>
</span><span class='line'>
</span><span class='line'>    <span class="n">glUniform1f</span><span class="p">(</span><span class="n">time_loc</span><span class="p">,</span> <span class="n">glfwGetTime</span><span class="p">());</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">glEnableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'>    <span class="n">glEnableVertexAttribArray</span><span class="p">(</span><span class="n">colour_loc</span><span class="p">);</span>
</span><span class='line'>    <span class="n">glDrawArrays</span><span class="p">(</span><span class="n">GL_TRIANGLE_STRIP</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">);</span>
</span><span class='line'>    <span class="n">glDisableVertexAttribArray</span><span class="p">(</span><span class="n">position_loc</span><span class="p">);</span>
</span><span class='line'>    <span class="n">glDisableVertexAttribArray</span><span class="p">(</span><span class="n">colour_loc</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// ... swap buffers etc</span>
</span><span class='line'>  <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This should look something like this:</p>

<center>
  <iframe src="http://seshbot.com/assets/2015-05-13-gl1.html" width="320" height="200" scrolling="no" style="border: 2px solid black; -moz-box-shadow: black 2px 2px 2px;"></iframe>
  <br/>
  <a style="clear:both;" href="http://seshbot.com/assets/2015-05-13-gl1.html" target="_blank">click here to open in a separate window</a>
</center>


<h3>Immediate mode and the fixed function pipeline</h3>

<p>I discuss this more when discussing the different OpenGL versions below, but OpenGL 1 was much simpler to use than later versions, though much less powerful. OpenGL 1 operated using a <em>fixed-function pipeline</em> using an <em>immediate mode</em> API, where the programmer not only describes high-level primitives&#8217; individual vertices but also describe the lighting model to use, define several lights and set up materials to use during rendering. Retained mode allows all of this functionality to be executed on a shader program, which is written by the developer but run on the GPU directly. This is much more performant but requires a lot of extra work on the part of the developer.</p>

<p>The term immediate mode means that the drawing operations are explicitly executed in your client application each frame, which is considered slower because it ties the client application logic too closely with the GPU rendering operations, so the GPU is not able to make as many optimisations as it would if the instructions were on the GPU itself (retained mode.)</p>

<h2>Linear algebra (magic!)</h2>

<p>Linear algebra is the language of graphics programming. You <em>need</em> to learn some basics if you&rsquo;re going to tackle this stuff. I won&rsquo;t go into what a vector or matrix is here but you will have to learn the basics of their form and function if you don&rsquo;t already know them.</p>

<p>The most basic understanding you should have is that vectors are usually used to describe coordinates in space and directions, and matricies are used to describe transformations (translation, scale, rotation, shear etc) to those vectors. Another thing to note is that a single matrix may represent an accumulation of many different transformations performed in sequence, so if I said (in pseudo-code) <code>auto m = translate * scale * rotate</code>, then any time I multiply <code>m</code> by a vector it will have the same effect as performing all of those transformations at once &ndash; amazing!</p>

<p>Once again, the OpenGL API does not help you in dealing with matricies or vectors, but there is a great supporting library that does &ndash; <a href="http://glm.g-truc.net/">GLM</a>.</p>

<p>There are two ways the elements in a matrix may be stored &ndash; OpenGL programmers often use <em>column-major</em> matrix layouts. This is a convention only, but is generally used in the official documentation and in OpenGL support libraries such as GLM. The reason this is important is that unlike scalar multiplication, matrix multiplication is not <em>commutative</em>, meaning <code>A * B</code> does not equal <code>B * A</code>. The main impact of using column-major vs row-major matricies is the order of multiplications must be reversed to have the same effect. In column-major (the most usual) you would accumulate your transformations to the left, so if you want to first rotate (<em>R</em>) then scale (<em>S</em>) then translate (<em>T</em>) last, you would execute <code>T * S * R</code>. A more common example would be when calculating the <em>model view projection</em> matrix it would be accumulated as <code>mat4 mvp = P * V * M</code>. When calculating this with a <em>row-major</em> library you would be expected to accumulate it as <code>mat4 mvp = M * V * P</code>. Converting a matrix to or from column-major to row-major is known as <em>transposing</em> the matrix.</p>

<p>A common term in linear algebra is the <em>identity matrix</em>. This is a matrix <em>I</em> where multiplying it with another matrix <em>A</em> gives that matrix (<code>I * A = A</code>.) It is easily recognisable as it is entirely made of 0s with 1s on the diagonal.</p>

<p>Another generally useful matrix operation is the <em>inverse</em> of a matrix. The inverse of a matrix A is the matrix required to multiply with A so that the result is the identity matrix. In other words, <code>Ai * A = I</code>. This is useful when rolling back a matrix multiplication. If you have the <em>model view projection</em> matrix <code>mat4 mvp = proj * view * model</code>, you can find the <em>model view</em> matrix by calculating the inverse projection <em>inv_proj</em> and calculating: <code>mat4 mv = inv_proj * mvp</code>.</p>

<p>Vector operations are even more interesting. A few things I want to point out here are <em>dot product</em>, <em>cross product</em> and the difference between <em>positional coordinates</em> and <em>directional coordinates</em>.</p>

<p>The <strong>dot product</strong> operation (sometimes known as the <em>inner product</em>) is used for many purposes; the dot product of two vectors A and B is a scalar (not a vector) number that is the sum of the products of their components (e.g., <code>auto a_dot_b = A.x * B.x + A.y * B.y + A.z * B.z</code>). It turns out that this simple formula gives you the cosine of the angle between those vectors multiplied by their magnitudes (<code>|A||B|cos(Ɵ)</code>), which is really useful because:</p>

<ul>
<li>if the vectors are unit vectors (they each have magnitude of 1) the dot product will just give you <code>cos(Ɵ)</code> which is a number between 0 and 1, where 0 implies that they are perpendicular to each other (at 90 degrees) and 1 implies they are parallel. This is great for calculating how much light should bounce off a surface if the light direction is one vector and the surface normal is the other.</li>
<li>if the vectors are both unit vectors you can inverse cos the dot product to find the angle between the vectors (<code>auto angle = acos(dot(A, B))</code>)</li>
<li>you can find the projection of vector A onto vector B by finding the dot product of A and B then dividing the result by the length of A.</li>
<li>calculating the dot product of a vector with itself will give you the distance squared. If you are checking to see which vector is longer, you can just compare their squared distances (saving you a square root operation)</li>
</ul>


<p>The <strong>cross product</strong> is another simple formula that gives you a vector that is perpendicular to two given vectors. In other words, if you have vectors A and B that both lie along the same surface, calculating <code>cross(A, B)</code> will give a vector that represents the normal to that surface. This normal vector will also follow the <em>right-hand rule</em> as pictured below (Note: you will usually want to normalise your normal before using it, so lighting calculations can dot product them straight out of the box!)</p>

<p><img class="center" src="http://upload.wikimedia.org/wikipedia/commons/d/d2/Right_hand_rule_cross_product.svg" width="200" height="200" title="&#34;Cross product follows the right-hand rule&#34;" alt="&#34;Cross product follows the right-hand rule&#34;"></p>

<h2>OpenGL versions and extensions</h2>

<p>A constant frustration when reading documentation and code examples is that OpenGL 1.0 is <em>worlds apart</em> from OpenGL 2.0. Many of us would have been well served if they had given it a totally different name, so different are the products!</p>

<p><strong>OpenGL 1</strong> functions in what is now called <em>immediate mode</em> and is considered deprecated. In this version the programmer describes the scene lights, materials and fog, then notifies the driver of each polygon explicitly. The driver would then render the scene using its own internal lighting model using the described lights and materials. This is called the <em>fixed function pipeline</em>.</p>

<figure class='code'><figcaption><span>OpenGL 1 example code snippet</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// configure light</span>
</span><span class='line'><span class="n">glEnable</span><span class="p">(</span><span class="n">GL_LIGHTING</span><span class="p">);</span>     <span class="c1">// deprecated</span>
</span><span class='line'><span class="n">glEnable</span><span class="p">(</span><span class="n">GL_LIGHT0</span><span class="p">);</span>       <span class="c1">// deprecated</span>
</span><span class='line'><span class="n">glLightfv</span><span class="p">(</span><span class="n">GL_LIGHT0</span><span class="p">,</span> <span class="n">GL_AMBIENT</span><span class="p">,</span> <span class="p">{</span><span class="mf">.4f</span><span class="p">,</span> <span class="mf">.1f</span><span class="p">,</span> <span class="mf">.1f</span><span class="p">});</span> <span class="c1">// deprecated</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// draw a primitive</span>
</span><span class='line'><span class="n">glPushMatrix</span><span class="p">();</span>            <span class="c1">// deprecated</span>
</span><span class='line'><span class="c1">// matrix operations will apply to all vertices until glPopMatrix()</span>
</span><span class='line'><span class="n">glLoadIdentity</span><span class="p">();</span>          <span class="c1">// deprecated</span>
</span><span class='line'><span class="n">glRotatef</span><span class="p">(</span><span class="mf">3.14f</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">);</span> <span class="c1">// deprecated</span>
</span><span class='line'><span class="n">glBegin</span><span class="p">(</span><span class="n">GL_TRIANGLE</span><span class="p">);</span>      <span class="c1">// deprecated</span>
</span><span class='line'>  <span class="n">glVertex3f</span><span class="p">(</span><span class="mf">.0</span><span class="p">,</span> <span class="mf">.0</span><span class="p">.,</span> <span class="mf">.0</span><span class="p">);</span> <span class="c1">// deprecated</span>
</span><span class='line'>  <span class="n">glVertex3f</span><span class="p">(</span><span class="mf">.1</span><span class="p">,</span> <span class="mf">.0</span><span class="p">.,</span> <span class="mf">.0</span><span class="p">);</span> <span class="c1">// deprecated</span>
</span><span class='line'>  <span class="n">glVertex3f</span><span class="p">(</span><span class="mf">.1</span><span class="p">,</span> <span class="mf">.1</span><span class="p">.,</span> <span class="mf">.0</span><span class="p">);</span> <span class="c1">// deprecated</span>
</span><span class='line'><span class="n">glEnd</span><span class="p">();</span>                   <span class="c1">// deprecated</span>
</span><span class='line'><span class="n">glPopMatrix</span><span class="p">();</span>             <span class="c1">// deprecated</span>
</span><span class='line'><span class="n">glFlush</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p><strong>OpenGL 2</strong> introduced shaders, yet still provided compatability with the above described model. Shaders had access to the state declared in the fixed function pipeline through standard global variables (such as the <code>gl_LightSource[]</code> array and the <code>gl_FrontMaterial</code> variable sent from the client and the <code>gl_ModelViewProjection</code> matrix which was generated by the driver.) The vertex shader can invoke the standard fixed-function pipeline functionality by callling <code>gl_Position = ftransform();</code>.</p>

<p><strong>OpenGL 3</strong> completely deprecated the immediate mode fixed-function pipeline. Of course this introduced backwards-compatability issues so they also introduced several <em>profiles</em> to allow backward compatability to be optionally compiled in. The <em>compatability profile</em> can be requested to enable deprecated features, while the <em>core profile</em> disallows the use of these features.</p>

<p>Since OpenGL 2 however there have been no truly large architectural changes (unfortunately.) Changes have focused around adding features (new types of shaders, for example) to provide better performance and more generally useful aspects of existing functionality. This is a shame because there are still a lot of problems with OpenGL that many developers want addressed &ndash; the original goal of OpenGL 3 was to include massive refactorings to remove all the global state (more on this later) but vendors objected so strenuously that this work was put off until <em>GLNext</em> which is now known as <a href="https://www.khronos.org/vulkan">Vulkan</a>.</p>

<p>OpenGL shaders are written in their own language &ndash; <strong>GLSL</strong>. GLSL has its own varied syntax between versions, and to make things even more complicated they support the notion of extensions. The best bet is to decide on which version of OpenGL you will be learning and learn the GLSL appropriate to that version. They are all quite similar in form but are syntactically incompatible with each other.</p>

<p>Some mention should be made regarding extensions.  Extensions are often touted as a great feature in OpenGL not available in other graphics libraries such as DirectX. New commands and enumerations are often added to the OpenGL API by vendors as extensions, and then if this functionality proves popular it becomes formalised as part of the API in a later version.</p>

<p>Each OpenGL version has a known set of extensions. These can be browsed in the Khronos reference implementations &ndash; for example the OpenGL ES 2 extensions are in the <a href="https://www.khronos.org/registry/gles/api/GLES2/gl2ext.h">GLES2/gl2ext.h</a> header file. There are idiomatic ways to detect support for and load these extensions using system calls but most people use an <strong>extension loader</strong> of some type. A very popular extension loader is the <a href="http://glew.sourceforge.net/">OpenGL Extension Wrangler Library</a> (also known as GLEW.)</p>

<p>If you want some functionality not natively available in your chosen version of the OpenGL API you will often find an extension that provides that functionality. The problem is, extensions are not supported uniformly on all platforms with all drivers, so quite often you&rsquo;ll have to work around the missing functionality in some platform anyway. This severely limits the usefulness of extensions, and in general you should try to do without them if possible.</p>

<p>I personally do use a few extensions in a few circumstances: either to get around eccentricities of a particular platform (e.g., some Windows platforms use BGRA instead of RGBA framebuffer formats, which are only available through the GL_EXT_texture_format_BGRA8888 extension) or if I have through experimentation determined that an extension is very broadly supported.</p>

<p>Here&rsquo;s a quick summary of what I understand of the different OpenGL versions:</p>

<h3>OpenGL 1 &ndash; high level and slow but simple</h3>

<ul>
<li>Immediate mode only (fixed function pipeline)</li>
<li>no shaders</li>
<li>a lot of people still use this when demonstrating functionality</li>
<li>only version natively supported by Windows</li>
</ul>


<h3>OpenGL 2 &ndash; shaders run on the GPU</h3>

<ul>
<li>first shader-based version</li>
<li>vertex and fragment shaders</li>
<li>still have access to the fixed function pipeline &ndash; even within shaders</li>
</ul>


<h3>OpenGL 3 &ndash; a controversial release</h3>

<ul>
<li>framebuffers for rendering to non-screen targets (e.g., render to a texture)</li>
<li>vertex array objects (VAOs) allow great performance boosts by quickly binding and unbinding whole groups of buffers and attribute bindings</li>
<li>geometry shaders (modify/extend geometry of primitives)</li>
<li>significant (breaking!) changes to GLSL shader language</li>
<li>deprecated most 1.0 functionality (immediate mode stuff) introducing compatability and core modes

<ul>
<li>compatability mode gives access to the old fixed function pipeline</li>
<li>core mode does not</li>
</ul>
</li>
</ul>


<h3>OpenGL 4 &ndash; modernisation, performance and professional enhancements</h3>

<ul>
<li>OpenGL 4.0 goal was to achieve parity with Direct3D 11</li>
<li><a href="http://arstechnica.com/information-technology/2014/08/opengl-4-5-released-with-one-of-direct3ds-best-features/">OpenGL 4.5</a> goal was to achieve parity with Direct3D 12</li>
<li>tesselation shaders introduce extra polygons for &lsquo;denser&rsquo; meshes with smoother curves</li>
<li>compute shaders for using the GPU for non-graphics computations (GPGPU stuff)</li>
<li>GPGPU compute shader uses SPIR &ndash; an intermediate language based on LLVM</li>
<li>Direct State Access &ndash; mitigate long-standing architectural problems with immediate mode</li>
<li>modern OSX supports up to OpenGL 4.1</li>
</ul>


<h3>OpenGL ES &ndash; simplified for embedded systems</h3>

<ul>
<li>OpenGL ES 1.0 based on OpenGL 1.3</li>
<li>OpenGL ES 1.1 based on OpenGL 1.5</li>
<li>OpenGL ES 2.0 based on OpenGL 2.0

<ul>
<li>WebGL is based on OpenGL ES 2.0</li>
<li><a href="https://code.google.com/p/angleproject/">Google ANGLE project</a> provides OpenGL ES 2.0 support on Windows (wraps DirectX API)</li>
</ul>
</li>
<li>OpenGL ES 3.0 full subset of OpenGL 4.3

<ul>
<li>GLSL ES 3.0 based on GLSL 3.3</li>
<li>similar to OpenGL 3 but without geometry shaders</li>
<li>supported by modern iOS and Android devices</li>
<li><a href="https://code.google.com/p/angleproject/wiki/Update20150105">experimental support</a> in Google ANGLE project</li>
</ul>
</li>
</ul>


<h3>WebGL</h3>

<ul>
<li>based on OpenGL ES 2.0</li>
<li>I don&rsquo;t know much about this yet, but <a href="http://webglfundamentals.com">WebGL Fundamentals</a> is a great resource</li>
</ul>


<h3>Vulkan &ndash; GLNext, lots of hype but not much information yet</h3>

<ul>
<li>get away from immediate mode single-threaded global state context heritage</li>
<li>allow shaders to be written in a variety of languages</li>
<li><a href="http://arstechnica.com/gadgets/2015/03/khronos-unveils-vulkan-opengl-built-for-modern-systems/">http://arstechnica.com/gadgets/2015/03/khronos-unveils-vulkan-opengl-built-for-modern-systems/</a></li>
</ul>


<p>I have chosen to do most of my experimentation in OpenGL ES 2. This should give me the broadest platform availability as well as being compatible with WebGL for web demonstrations. I have resorted to using a few extensions that are supported on the platforms I use where necessary (e.g., to get anti aliasing), though I try to avoid this where possible.</p>

<h2>Challenges you will face</h2>

<ul>
<li>Having to learn support libraries in addition to the OpenGL API</li>
<li>Cross platform support is difficult as many features are not uniformly supported</li>
<li>Debugging GL state in different platforms &ndash; OpenGL debugging tools are not great, and there are none that work cross-platform</li>
<li>Multithreading correctly is extremely difficult &ndash; if possible just do all your rendering on one thread!</li>
<li>Managing extensions can be a pain in the ass</li>
<li>State management &ndash; OpenGL uses global state, so it is impossible to write optimal abstractions because cannot encapsulate state, and state querying is prohibitively expensive. So you end up redundantly setting state that has often already been set.</li>
<li>lots of problems: <a href="http://richg42.blogspot.jp/2014/05/things-that-drive-me-nuts-about-opengl.html">http://richg42.blogspot.jp/2014/05/things-that-drive-me-nuts-about-opengl.html</a></li>
</ul>


<h3>Documentation and tutorials</h3>

<p>As I mentioned there&rsquo;s not a lot of great documentation out there. I started to create <a href="http://cechner.github.io/">my own responsive OpenGL documentation</a> and then discovered that there&rsquo;s already a pretty sweet one out there called <a href="http://docs.gl/">docs.gl</a>. Docs.gl is great because it makes it clear which commands are supported in which versions of OpenGL &ndash; something that&rsquo;s hard to figure out from the more official sources.</p>

<p>A great beginner tutorial is <a href="http://open.gl/">open.gl</a> &ndash; it&rsquo;s modern, minimalistic and well written. A very similar-seeming tutorial series that goes into more advanced techniques is <a href="http://learnopengl.com/">Learn OpenGL</a>. There used to be a fantastic series called the ArcSynthesis tutorials but they seem to have died. There is a <a href="http://www.pdfiles.com/pdf/files/English/Designing_&amp;_Graphics/Learning_Modern_3D_Graphics_Programming.pdf">PDF version of their content</a> that seems pretty good though.</p>

<p><a href="http://ogldev.atspace.co.uk/index.html">OGLdev</a> is a series of tutorials that go into more depth than the open.gl site above, and is in bite-sized chunks for easier consumption.</p>

<p>If you want to step through some sample code, download the <a href="https://github.com/progschj/OpenGL-Examples">OpenGL-Examples</a> github repository. It seems pretty easy to use and goes into fairly advanced topics.</p>

<p>If you want <em>really really detailed</em> runthrough of the graphics pipeline, have a look at <a href="https://fgiesen.wordpress.com/category/graphics-pipeline/">the ryg blog</a>. I haven&rsquo;t made my way through it yet but I really want to. Fabien Gleson seems to be pretty knowledgable about not only low level rendering details but also general low level computing concepts in general.</p>

<p>Finally, if you&rsquo;re into WebGL you should check out Gregg Tavares&#8217; <a href="http://webglfundamentals.org/">WebGL Fundamentals</a>. Gregg has a lot of experience working on WebGL in Chrome and game programming in general and has made some fantastic javascript support libraries that make every-day WebGL much simpler.</p>

<p>As I mentioned before though, you can easily try reading the specs yourself. Google is your friend here &ndash; search for the specific version + &lsquo;spec&rsquo; and it will <a href="https://www.google.com.au/search?q=opengl+3+spec">usually be the first hit</a>.</p>

<h2>Debugging</h2>

<p>There are <a href="https://www.opengl.org/wiki/Debugging_Tools">many different OpenGL debugging tools</a> on different platforms and they are all generally pretty bad. I haven&rsquo;t spent a lot of time with any of them so please tell me if you find a good one!</p>

<p>If you&rsquo;re on OSX you can give the <a href="https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/OpenGLProfilerUserGuide/Introduction/Introduction.html">OpenGL Profiler</a> a go &ndash; it allows you to set breakpoints on certain GL calls, look at frame buffers (though I found this difficult to do) and much more.</p>

<p>Windows users should check out <a href="https://github.com/baldurk/renderdoc">RenderDoc</a>, which allows you to track API calls, view render buffers and a lot of other stuff, for both OpenGL and DirectX. You can also invoke the DLL directly to dump various information from within your application. I haven&rsquo;t used it myself though so I won&rsquo;t go on further.</p>

<p>It&rsquo;s also a great idea to have some macros that optionally call <code>glGetError()</code> after every OpenGL call you make so you can easily track down where things begin to go awry. Unfortunately though querying the context can be fairly expensive so you should make it easy to disable this macro when things are not going awry.</p>

<p>Feel free to copy-paste this into your codebase:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// #define DEBUG_OPENGL_COMMANDS // uncomment this to enable error checking</span>
</span><span class='line'>
</span><span class='line'><span class="cp">#ifdef DEBUG_OPENGL_COMMANDS</span>
</span><span class='line'>  <span class="kt">void</span> <span class="n">checkOpenGLError</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span><span class="o">*</span> <span class="n">function</span><span class="p">,</span> <span class="k">const</span> <span class="kt">char</span><span class="o">*</span> <span class="n">file</span><span class="p">,</span> <span class="kt">int</span> <span class="n">line</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">auto</span> <span class="n">err</span> <span class="o">=</span> <span class="n">glGetError</span><span class="p">();</span> <span class="k">if</span> <span class="p">(</span><span class="n">err</span> <span class="o">==</span> <span class="n">GL_NO_ERROR</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>
</span><span class='line'>    <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;unrecognised&quot;</span><span class="p">;</span>
</span><span class='line'>    <span class="k">switch</span> <span class="p">(</span><span class="n">err</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="k">case</span> <span class="nl">GL_INVALID_ENUM:</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;GL_INVALID_ENUM&quot;</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="nl">GL_INVALID_VALUE:</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;GL_INVALID_VALUE&quot;</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="nl">GL_INVALID_OPERATION:</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;GL_INVALID_OPERATION&quot;</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="nl">GL_STACK_OVERFLOW:</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;GL_STACK_OVERFLOW&quot;</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="nl">GL_STACK_UNDERFLOW:</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;GL_STACK_UNDERFLOW&quot;</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="nl">GL_OUT_OF_MEMORY:</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;GL_OUT_OF_MEMORY&quot;</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">case</span> <span class="nl">GL_INVALID_FRAMEBUFFER_OPERATION:</span> <span class="n">err_msg</span> <span class="o">=</span> <span class="s">&quot;GL_INVALID_FRAMEBUFFER_OPERATION&quot;</span><span class="p">;</span> <span class="k">break</span><span class="p">;</span>
</span><span class='line'>      <span class="k">default</span><span class="o">:</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>    <span class="c1">// on Windows call ::OutputDebugString </span>
</span><span class='line'>    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;OpenGL error &#39;%s&#39; (0x%04x) called from %s in file %s line %d</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span>
</span><span class='line'>      <span class="n">err_msg</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">function</span><span class="p">,</span> <span class="n">file</span><span class="p">,</span> <span class="n">line</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="cp">#  define GL_VERIFY(stmt) do { stmt; checkOpenGLError(#stmt, __FUNCTION__, __FILE__, __LINE__); } while (0)</span>
</span><span class='line'><span class="cp">#  define GL_CHECK() do { checkOpenGLError(__FUNCTION__, __FILE__, __LINE__); } while (0)</span>
</span><span class='line'><span class="cp">#  define GL_IGNORE(stmt) do { GL_CHECK(); stmt; glGetError(); } while (0)</span>
</span><span class='line'><span class="cp">#else</span>
</span><span class='line'><span class="cp">#  define GL_VERIFY(stmt) stmt</span>
</span><span class='line'><span class="cp">#  define GL_CHECK()</span>
</span><span class='line'><span class="cp">#  define GL_IGNORE(stmt) stmt</span>
</span><span class='line'><span class="cp">#endif</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then you just wrap all your function calls like so: <code>GL_VERIFY(glDrawElements(...))</code>. If you want to just check for errors at a particular point in your code, just call <code>GL_CHECK()</code>.</p>

<p>One final interesting note about debugging OpenGL: If you are using a Google&rsquo;s ANGLE OpenGL driver that you compiled yourself you can step into it, so if you start getting vague sounding errors like <code>GL_INVALID_FRAMEBUFFER_OPERATION</code> but want to know specifically what the problem is, you can step into the ANGLE DLLs yourself to see which part of their validation fails. It&rsquo;s like running a own fully-compliant validation layer in your own client code.</p>

<h2>Upcoming</h2>

<p>Now that I&rsquo;ve gotten all the basic stuff out of the way I&rsquo;d like to go into a bunch of other more advanced things that I thought wasn&rsquo;t particularly easy to get help with. In no particular order:</p>

<ul>
<li>Pros and cons of writing an OpenGL wrapper library (<a href="https://github.com/seshbot/glpp">my glpp library</a>)</li>
<li>Building and using Google&rsquo;s ANGLE library</li>
<li>Using OpenGL for 2D:

<ul>
<li>setting up the GL context (depth buffer)</li>
<li>basic 2D coords</li>
<li>drawing primitives</li>
<li>simple texture</li>
<li>using orthographic projection with 2D</li>
</ul>
</li>
<li>Using OpenGL for 3D:

<ul>
<li>setting up the GL context (blending, face culling)</li>
<li>3d coordinate system (plus MVP, normal matrix)</li>
<li>drawing primitives</li>
<li>perspective projection and the frustum</li>
</ul>
</li>
<li>3D lighting</li>
<li>3D shadows</li>
<li>Particle systems</li>
<li>Texturing (textures, texture unit and samplers), sampling, blending, alpha discard, stencil testing, <a href="http://stackoverflow.com/questions/9224300/what-does-gltexstorage-do">glTexStorage</a></li>
<li>Multi pass rendering (using FrameBuffers):

<ul>
<li>Render scene &ndash;> FBO &ndash;> texture colour buffer &ndash;> screen rectangle &ndash;> post effect frag shader &ndash;> screen</li>
<li>Post processing (HSV and gamma correction)</li>
</ul>
</li>
<li>Loading models and animations (using assimp)</li>
<li>Rendering text (using stb)</li>
<li>Using Qt/QML with OpenGL</li>
<li>Object Picking in a 3D scene</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Week in Review: back from my hiatus (from my hiatus)]]></title>
    <link href="http://seshbot.com/blog/2015/01/24/week-in-review-back-from-my-hiatus-from-my-hiatus/"/>
    <updated>2015-01-24T04:49:15+00:00</updated>
    <id>http://seshbot.com/blog/2015/01/24/week-in-review-back-from-my-hiatus-from-my-hiatus</id>
    <content type="html"><![CDATA[<p>In September I went to Spain for 6 weeks to chill out with my family and check out what the countryside had to offer. Then I moved from Japan to Australia and got caught up in the Christams spirit. So although I have done some stuff (below) I have not made much progress on any big projects in the last few months&hellip;</p>

<p>BUT I have done a lot. Below the fold I talk about starting a C++ OpenGL library, creating some nicer OpenGL documentation, learning Blender 3D, setting up a new computer and moving country.</p>

<p>On the side I&rsquo;ve been helping a mate out set up an e-commerce site for his new Japanese brewery &ndash; more information to come when it is released in a few months!</p>

<!-- more -->


<h2>Australian lifestyle</h2>

<p>Things are <strong>really</strong> breezy here &ndash; it is a great relief to be in a country where I can just pick up a medicare card, or drivers licence, or bank card, or ANYTHING that involves beurocracy and signing documents without worrying about not understanding or sitting through hours of pawing through contracts and legalese, or running up against brick walls because I&rsquo;m a foreigner. Although the service is generally not as nice as that in Japan, people are more willing to take the initiative when helping you out.</p>

<p>Everything is a long drive away. The computer store <a href="https://www.ple.com.au/">PLE</a> is easily a 30 minute drive away, out in one of Perth&rsquo;s industrial areas. Oh and speaking of that, there are very very few good computer stores around here. PLE is fantastic however, all staff members I&rsquo;ve spoken with are really knowledgable about hardware and have been super helpful.</p>

<p>Pretty soon I&rsquo;ll set up an ABN (business entity) because its easy to do and I would like to make some business cards&hellip;</p>

<h2>My new office</h2>

<p>I&rsquo;m currently living in Kalamunda &ndash; a beautiful area in the hills east of Perth, although it&rsquo;s a bit far from anywhere (as is everything else in WA!) As predicted the internet in Australia has been nothing but trouble, but we are close to the exchange so once I get some technical stuff sorted out we should have OK speeds (although with a download cap which feels very 90s).</p>

<p>The big lesson I&rsquo;ve learned is that no company that provides a utility (e.g., telephony) should ever be privatised. They live in a privileged state of natural monopoly and will always screw their customers by providing the cheapest possible service, if any service at all.</p>

<h2>My new computer</h2>

<p>To celebrate moving to Australia, and because my old office computer is in a box on the ocean somewhere, I decided to get a new well-spec&rsquo;d machine. Having last built a machine about 15 years ago I decided to trust in the most recent <a href="http://arstechnica.com/gadgets/2014/08/ars-technica-system-guide-august-2014/">ArsTechnica system guide</a> by largely basing my decisions on the <a href="http://arstechnica.com/gadgets/2014/08/ars-technica-system-guide-august-2014/4/">Hot-Rod specifications</a> contained therein.</p>

<p>It features:</p>

<ul>
<li>CPU: <a href="http://ark.intel.com/products/80815/Intel-Core-i5-4590-Processor-6M-Cache-up-to-3_70-GHz">Intel Core i5-4590</a></li>
<li>Motherboard: <a href="http://www.asus.com/au/Motherboards/H97ME/">Asus H97M-E</a></li>
<li>RAM: 16GB (2x 8GB) DDR3-1600 (can&rsquo;t recall brand)</li>
<li>SSD: <a href="http://www.samsung.com/au/consumer/pc-peripherals/solid-state-drive/ssd-840-evo/MZ-7TE250BW">Samsung 840 EVO 250GB</a></li>
<li>Case: <a href="http://www.corsair.com/de-de/obsidian-series-350d-micro-atx-pc-case">Corsair Obsidian 350D</a></li>
<li>GPU: I reused my NVidia 550 GTX from my previous machine</li>
<li>PSU: I also brought my old 750W power unit from Japan</li>
</ul>


<p>Windows 8 boots up <em>really</em> quickly and the machine in general is just super speedy and a pleasure to use. I am especially happy with the case, it pops open and closed easily without tools and has fantastic airflow and filtering.</p>

<h2>New OpenGL work</h2>

<p>I have put aside the game stuff I was doing to focus on my core OpenGL knowledge a bit. OpenGL is crufty and problematic to use, and often if you make a mistake it can take hours or days to figure out what the problem is.</p>

<p>As such I begun work on <a href="https://github.com/seshbot/glpp">glpp</a> &ndash; a C++ library that provides a strongly-typed interface to OpenGL that also features utilities to easly create rendering pipelines, typed buffers, and under the covers utilises third-party libraries to provide context creation, image loading and 3d model loading. It also builds on OSX and Windows (using ANGLE so you dont have to install your own OpenGL drivers!) and targets OpenGL ES 2.0 to ensure maximum support across platforms.</p>

<p>I want to try automatically generating my type-safe versions of the OpenGL API (enums, bit fields and functions), and would like to somehow transform the <a href="https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/api/gl.xml">Khronos OpenGL API Registry</a> to reduce the amount of manual work required. In considering this I came up with another idea &ndash; how about making some nice interactive documentation that doesn&rsquo;t suck as much as all the other docs!?</p>

<p>So with this in mind I have started experimenting with creating a static single-page-app with Ember.js that will source a set of auto-generated JSON docs of my own fashioning, using the &lsquo;fixture adapter&rsquo; instead of loading data from some REST-ful service. I created a github repo called <a href="https://github.com/seshbot/gldoc">gldoc</a> which I&rsquo;ll be pushing my efforts into. For now it&rsquo;s just a small skeleton Ember app though, as I struggle to recall how Ember works.</p>

<p>Of course instead of writing an ember app and generating the JSON data I could just generate a bunch of static pages (or maybe make it single page with creative uses of divs, jQuery and handlebars), but I would like to mess with ember a bit more so I&rsquo;ll go down that route.</p>

<p>In other news however, Microsoft has release Visual Studio 13 &lsquo;community edition&rsquo; which is totally free to use! This is fantastic news as the &lsquo;express edition&rsquo; was missing a bunch of features I really like using such as performance profiling and the interactive command window, among other things.</p>

<h2>3D modelling with Blender</h2>

<p>To cut a long story short, Blender is a very nice 3D modelling application. If you want to learn it I would highly recommend starting with the <a href="http://cgcookie.com/blender/cgc-courses/blender-basics-introduction-for-beginners/">Blender Cookie introduction for beginners</a> series of videos. Also, install the &lsquo;pie menus&rsquo; (look it up) &ndash; they make switching between states super simple.</p>

<p><img src="http://seshbot.com/images/upload/2015-01-25-dude.png" title="&#34;I made a dude&#34;" alt="&#34;I made a dude&#34;"></p>

<h2>Games</h2>

<p>I went a bit crazy and decided to start playing Dark Souls and the new Elite: Dangerous.</p>

<p>Dark Souls is so awesome I am considering making a lets play video as I&rsquo;ve seen others do. I downloaded <a href="https://obsproject.com/">OBS</a> and am excited to give it a try.</p>

<p>Elite: Dangerous is a fantastic successor to the Elite games of the 80s, made by the same guy via KickStarter. The feel of the game is fantastic, but the multiplayer aspect is quite lackluster at the moment &ndash; it is very difficult to locate your friends or help them out in battles etc. But at least it HAS a multiplayer aspect!</p>

<p>In fact I enjoy the game so much I purchased a <a href="http://www.thrustmaster.com/products/tflight-hotas-x">ThrustMaster T-Flight HOTAS X</a> which makes the experience much better. I am seriously considering an Oculus Rift as well, as in addition to the natural synergies with this game, I&rsquo;d love to try making some software for it.</p>

<p>Finally, I headed into Tactics in Perth and purchased Ticket to Ride, Munchkin and an Adventure Time card game as well.</p>

<h2>Blogging</h2>

<p>I have learned so much about OpenGL over the last few months that I can envisage a 4 or 5 part series of articles on the subject. Specifically exploring what OpenGL is and how to get started, how to set up a simple 2D scene, how to set up a typical 3D scene (including shading), shadows and stencils, frame buffers and render pipelines, and texturing.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[C++11/14 idioms I use every day]]></title>
    <link href="http://seshbot.com/blog/2014/08/16/modern-c-plus-plus-idioms-i-use-every-day/"/>
    <updated>2014-08-16T04:49:33+00:00</updated>
    <id>http://seshbot.com/blog/2014/08/16/modern-c-plus-plus-idioms-i-use-every-day</id>
    <content type="html"><![CDATA[<p><em>if you want to see a bunch of people complaining about my rules regarding </em>auto<em>, have a look at <a href="https://news.ycombinator.com/item?id=8193157">HackerNews</a> and <a href="http://www.reddit.com/r/cpp/comments/2dvirt/new_c_idioms_i_use_every_day/">Reddit</a></em></p>

<p>Most attention on the new C++ has focused on the changes that provide functionality and performance that was previously not possible, both library enhancements (chrono, regex, smart pointers, and stuff to help with lambdas for example) and core language enhancements (perfect forwarding, variadic templates, the new memory model and threading capabilities, initialiser lists and the like). This functionality will impact us all in helping to write more correct code and efficient libraries, but often will only be relevant in certain parts of our code.</p>

<p><span class='pullquote-right' data-pullquote='the first thing that struck me when I started using C++11 was the smaller features that I could take advantage of every time I put my fingers to the keyboard.'>
But the first thing that struck me when I started using C++11 was the smaller features that I could take advantage of every time I put my fingers to the keyboard. These are the things that make code more concise and simple and allow me to present my intentions more clearly.
</span></p>

<p>Stuff I take advantage of every day:</p>

<ul>
<li>more concise general coding:

<ul>
<li>lambdas for scoped initialisation or inline &lsquo;builder&rsquo; functions</li>
<li>new standard library functionality for string manipulation, particularly std::to_string() and std::stoi() etc</li>
<li>range-based for loop</li>
</ul>
</li>
<li>clearer declarations:

<ul>
<li>inline member initialisation,</li>
<li>the <code>override</code>, <code>default</code> and <code>delete</code> keywords</li>
<li>delegating constructors,</li>
<li>uniform initialisation, especially when invoking or returning from functions</li>
<li>auto type deduction everywhere!</li>
</ul>
</li>
<li>far fewer dependencies on boost</li>
</ul>


<p>These are the things I think all C++ programmers should learn first, because they benefit you <em>straight away</em> and confer very little risk of being learned wrong.</p>

<p>At the very end I also mention a few upcoming features that I&rsquo;m really excited about as they will be game-changers.</p>

<!-- more -->


<h2>More concise coding</h2>

<p>These are the most obvious every-day enhancements, mostly focusing on making code easier to write and to read. Some of the most pleasing languages to use (like F#) are so because the ratio between language constructs and code relating to logic is very low.</p>

<h3>use the auto keyword where possible</h3>

<p>The <code>auto</code> keyword should be used wherever possible. Functions should be short and readable, so don&rsquo;t pollute your code with unneccessary type declarations! Curmudgeons often claim they prefer to see the type written with the declaration, but I think readability and maintainability trumps this. Yes, maintainability &ndash; you want to be able to change return values, template signatures, class names and such, and auto adapts without complaint.</p>

<p>Scott Meyers dedicates a chapter to this in his new &lsquo;Effective Modern C++&rsquo; book (the item is <em>Item 4: Prefer auto to explicit type declarations</em>) &ndash; also have a look at his presentation also entitled <a href="http://vimeo.com/channels/ndc2014/97318797">Effective Modern C++</a> where he covers the matter.</p>

<p>If you&rsquo;re still unconvinced, <a href="http://www.reddit.com/r/cpp/comments/2dvirt/new_c_idioms_i_use_every_day/cju6c4w">academican helpfully pointed out</a> on the <a href="http://www.reddit.com/r/cpp/comments/2dvirt/new_c_idioms_i_use_every_day/">reddit discussion</a> of this article that <em>Herb Sutter wrote a <a href="http://herbsutter.com/2013/06/07/gotw-92-solution-auto-variables-part-1/">series</a> of <a href="http://herbsutter.com/2013/06/13/gotw-93-solution-auto-variables-part-2/">GOTW</a> <a href="http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/">articles</a> on this topic last year which defend the principle of &ldquo;Almost Always Auto&rdquo;. He does a much better job than I could</em> . The <a href="http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/">third article</a> explores this topic <em>particularly</em> thoroughly.</p>

<p>These articles are a real treasure-trove, where Herb concludes that:</p>

<ul>
<li>Guideline: Prefer to declare local variables using auto x = expr; when you don’t need to explicitly commit to a type. It is efficient by default and guarantees that no implicit conversions or temporary objects will occur</li>
<li>Guideline: Prefer to declare local variables using auto. It guarantees that you get the exact type and so is the simplest way to portably spell the implementation-specific type of arithmetic operations on built-in types, which vary by platform, and ensure that you cannot accidentally get narrowing conversions when storing the result</li>
<li>Guideline: Remember that preferring auto variables is motivated primarily by correctness, performance, maintainability, and robustness—and only lastly about typing convenience</li>
</ul>


<p>If you still don&rsquo;t agree with Scott and Herb, two of the most influential C++ gurus out there, then perhaps it would be well worth exploring why &ndash; if you know something they don&rsquo;t you&rsquo;re probably able to make a lucrative living lecturing!</p>

<h3>other uses for lambdas</h3>

<p>Lambdas are of course a fantastic feature that helps us all out in so many ways. But I tend to use it in general day-to-day stuff for what I call <strong>inline builder functions</strong>. This is when you want to perform some complicated ritual to create some resource but don&rsquo;t like setting your resources to some default &lsquo;uninitialised&rsquo; state.</p>

<p>For example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// create an immutable type or one that has no &#39;uninitialised&#39; state</span>
</span><span class='line'><span class="k">const</span> <span class="kt">int</span> <span class="n">calculated</span> <span class="o">=</span> <span class="p">[</span><span class="o">&amp;</span><span class="p">]</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">auto</span> <span class="n">l</span> <span class="o">=</span> <span class="n">lock</span><span class="p">();</span>
</span><span class='line'>   <span class="k">auto</span> <span class="n">first</span> <span class="o">=</span> <span class="n">stage1</span><span class="p">();</span>
</span><span class='line'>   <span class="k">auto</span> <span class="n">second</span> <span class="o">=</span> <span class="n">stage2</span><span class="p">();</span>
</span><span class='line'>   <span class="k">return</span> <span class="n">combine</span><span class="p">(</span><span class="n">first</span><span class="p">,</span> <span class="n">second</span><span class="p">);</span>
</span><span class='line'><span class="p">}();</span> <span class="c1">// notice I invoke the lambda here!</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// ... use the calculated value</span>
</span></code></pre></td></tr></table></div></figure>


<p>Of course you could put this functionality in a function somewhere but this means you don&rsquo;t pollute your class namespace, and the functionality is localised to the place you use it.</p>

<h3>range-based for loops</h3>

<p>The range-based for loop is also a no-brainer. It is not as useful as it could be &ndash; for example you often want to maintain some index as you iterate over something, and the standard library (and even boost range) don&rsquo;t provide a nice wrapper around iterators to help with this.</p>

<p>As a side note (I don&rsquo;t actually do this very often,) you can extend any type to be range-based for loop-compatible by providing specialisations of <code>std::begin()</code> and <code>std::end()</code> for that type. For example, I suppose one could do:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="k">struct</span> <span class="n">irange</span> <span class="p">{</span> <span class="kt">int</span> <span class="n">First</span><span class="p">;</span> <span class="kt">int</span> <span class="n">Last</span><span class="p">;</span> <span class="p">};</span>
</span><span class='line'><span class="k">struct</span> <span class="n">irange_iterator</span> <span class="p">{</span>
</span><span class='line'>   <span class="kt">int</span> <span class="n">Val</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>   <span class="c1">// minimalistic forward-iterator implementation</span>
</span><span class='line'>   <span class="kt">int</span> <span class="k">operator</span><span class="o">*</span><span class="p">()</span>                            <span class="p">{</span> <span class="k">return</span> <span class="n">Val</span><span class="p">;</span>          <span class="p">}</span>
</span><span class='line'>   <span class="kt">bool</span> <span class="k">operator</span><span class="o">!=</span><span class="p">(</span><span class="n">irange_iterator</span> <span class="k">const</span> <span class="o">&amp;</span> <span class="n">r</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">Val</span> <span class="o">!=</span> <span class="n">r</span><span class="p">.</span><span class="n">Val</span><span class="p">;</span> <span class="p">}</span>
</span><span class='line'>   <span class="n">irange_iterator</span> <span class="k">operator</span><span class="o">++</span><span class="p">()</span>               <span class="p">{</span> <span class="k">return</span> <span class="p">{</span><span class="o">++</span><span class="n">Val</span><span class="p">};</span>      <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// begin() and end() are invoked by range-based for</span>
</span><span class='line'><span class="n">irange_iterator</span> <span class="n">begin</span><span class="p">(</span><span class="n">irange</span> <span class="k">const</span> <span class="o">&amp;</span> <span class="n">r</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="p">{</span> <span class="n">r</span><span class="p">.</span><span class="n">First</span> <span class="p">};</span> <span class="p">}</span>
</span><span class='line'><span class="n">irange_iterator</span> <span class="n">end</span><span class="p">(</span><span class="n">irange</span> <span class="k">const</span> <span class="o">&amp;</span> <span class="n">r</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="p">{</span> <span class="n">r</span><span class="p">.</span><span class="n">Last</span> <span class="o">+</span> <span class="mi">1</span> <span class="p">};</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">int</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">for</span> <span class="p">(</span><span class="k">auto</span> <span class="n">v</span> <span class="o">:</span> <span class="n">irange</span><span class="p">{</span><span class="mi">10</span><span class="p">,</span><span class="mi">20</span><span class="p">})</span>
</span><span class='line'>      <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="n">v</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;, &quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// prints &#39;10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>&hellip;but don&rsquo;t do it &ndash; the iterator is incomplete (and non-const-correct, and probably buggy) and it doesn&rsquo;t cover reverse ranges for starters. Plus there are some cool libraries out there, like <a href="https://github.com/ryanhaining/cppitertools/blob/master/README.md">CPPItertools</a> perhaps?</p>

<h3>Many new basic STL utilities</h3>

<p>But one thing people dont mention much is that the standard library now includes a bunch of small helper functions for basic string conversions! Previously one might use boost <code>lexical_cast&lt;&gt;()</code> for this sort of thing, but now you can generally rely on <code>std::to_string()</code> overloads and <code>std::stoi()</code> and its variants to do the simple stuff for you.</p>

<p>The standard library also has new container types and algorithms. If you haven&rsquo;t familiarised yourself with the new <code>std::unordered_map</code> and <code>std::array</code> containers you really should. And new algorithms that you&rsquo;d kick yourself for reimplementing include <code>all_of()</code>/<code>any_of()</code>/<code>none_of()</code>, <code>iota()</code>, <code>minmax()</code>, <code>is_permutation()</code> (as well as all the other is_ functions) and <code>shuffle</code>. See this well-known <a href="http://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoning">Sean Parent&rsquo;s talk on C++ Seasoning</a> for some great discussion on using C++ algorithms to their fullest.</p>

<h2>Clearer declarations</h2>

<p>Initialisation is the backbone of C++ &ndash; typically all resources should be allocated and initialised in constructors and released deterministically in destructors according to very specific rules, ensuring exception safety and preventing resource leaks.</p>

<h3>Initialisation is much simpler</h3>

<p>C++11 allows us to focus on our intents more than focusing on our types. For example, the <code>auto</code> keyword and uniform initialisation both make code far clearer:</p>

<p>For example, we can expect to use a nice 3D mesh API like so:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="k">auto</span> <span class="n">square</span> <span class="o">=</span> <span class="n">create_triangle_mesh</span><span class="p">({</span>
</span><span class='line'>   <span class="p">{</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">},</span> <span class="p">{</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">},</span> <span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">},</span>
</span><span class='line'>   <span class="p">{</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">},</span> <span class="p">{</span> <span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">},</span> <span class="p">{</span><span class="mi">1</span><span class="p">,</span>  <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">},</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>This smacks of &lsquo;struct initialisation&rsquo; which I really liked:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="k">struct</span> <span class="n">TcpHeader</span> <span class="p">{</span>
</span><span class='line'>   <span class="n">uint16_t</span> <span class="n">src_port</span><span class="p">;</span> <span class="n">uint16_t</span> <span class="n">dst_port</span><span class="p">;</span>
</span><span class='line'>   <span class="n">uint32_t</span> <span class="n">seq</span><span class="p">;</span>
</span><span class='line'>   <span class="n">uint32_t</span> <span class="n">ack</span><span class="p">;</span>
</span><span class='line'>   <span class="c1">// ... plus other stuff</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// this works in C++03 as well</span>
</span><span class='line'><span class="n">TcpHeader</span> <span class="n">hdr</span> <span class="o">=</span> <span class="p">{</span><span class="mi">10012</span><span class="p">,</span> <span class="mi">8088</span><span class="p">,</span> <span class="mh">0x01</span><span class="p">,</span> <span class="mh">0x01</span><span class="p">,</span> <span class="cm">/* ... */</span> <span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Construction is much more flexible</h3>

<p>Now for trivial types you sometimes don&rsquo;t need a constructor:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="c1">// no constructor needed!</span>
</span><span class='line'><span class="k">struct</span> <span class="n">counter</span> <span class="p">{</span>
</span><span class='line'>   <span class="kt">int</span> <span class="n">last_</span> <span class="p">{</span> <span class="mi">0</span> <span class="p">};</span>
</span><span class='line'>   <span class="kt">int</span> <span class="n">step_</span> <span class="p">{</span> <span class="mi">1</span> <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>   <span class="kt">int</span> <span class="n">next</span><span class="p">()</span> <span class="p">{</span> <span class="n">last_</span> <span class="o">+=</span> <span class="n">step_</span><span class="p">;</span> <span class="k">return</span> <span class="n">last_</span><span class="p">;</span> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now there&rsquo;s a way to share construction code without resorting to a private init() function:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="k">struct</span> <span class="n">counter</span> <span class="p">{</span>
</span><span class='line'>   <span class="kt">int</span> <span class="n">last_</span><span class="p">;</span>
</span><span class='line'>   <span class="kt">int</span> <span class="n">step_</span><span class="p">;</span>
</span><span class='line'>   <span class="n">counter</span><span class="p">()</span>
</span><span class='line'>   <span class="o">:</span> <span class="n">counter</span> <span class="p">{</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span> <span class="p">}</span> <span class="p">{</span> <span class="p">}</span> <span class="c1">// delegating constructor!</span>
</span><span class='line'>   <span class="n">counter</span><span class="p">(</span><span class="kt">int</span> <span class="n">last</span><span class="p">,</span> <span class="kt">int</span> <span class="n">step</span><span class="p">)</span>
</span><span class='line'>   <span class="o">:</span> <span class="n">last_</span><span class="p">(</span><span class="n">last</span><span class="p">),</span> <span class="n">step_</span><span class="p">(</span><span class="n">step</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>   <span class="kt">int</span> <span class="n">next</span><span class="p">()</span> <span class="p">{</span> <span class="n">last_</span> <span class="o">+=</span> <span class="n">step_</span><span class="p">;</span> <span class="k">return</span> <span class="n">last_</span><span class="p">;</span> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<h3>More explicit inheritance</h3>

<p>I have always been jealous of languages that have the <code>override</code> keyword, because a common trap when refactoring is to rename a virtual base method &ndash; the compiler cannot warn you that you forgot to replace the overridden methods in specialised classes (unless it is pure virtual, which it really should be, but anyway&hellip;)</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="k">struct</span> <span class="n">base</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">virtual</span> <span class="n">string</span> <span class="n">name</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="s">&quot;default&quot;</span><span class="p">;</span> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="k">struct</span> <span class="n">derived</span> <span class="o">:</span> <span class="k">public</span> <span class="n">base</span> <span class="p">{</span>
</span><span class='line'>   <span class="c1">// compile error - xname() is not an inherited member! </span>
</span><span class='line'>   <span class="k">virtual</span> <span class="n">string</span> <span class="n">xname</span><span class="p">()</span> <span class="n">override</span> <span class="p">{</span> <span class="k">return</span> <span class="s">&quot;derived!&quot;</span> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>default</code> keyword can be a godsend to the concientious coder who likes to always obey the &lsquo;rule of three&rsquo; (or now the rule of five, or <a href="https://isocpp.org/blog/2012/11/rule-of-zero">rule of zero</a> as of lately.) Again the benefit is in reducing code that you need to write and maintain &ndash; the best code is no code at all.</p>

<p>To illustrate, imagine you have a class that encapsulates some resource handle. The resource will of course be destroyed in the destructor, and we choose to disallow copying to ensure that resource isn&rsquo;t double-destroyed. We want to allow moving however, because we don&rsquo;t want to force clients to wrap the resource in pointer types to pass it around&hellip;</p>

<p>The problem is that when one disables the copy constructor, one also disables the move constructor. The <code>default</code> keyword allows us to re-enable it without actually maintaining it as we update the class in future:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='c++'><span class='line'><span class="k">struct</span> <span class="n">Handle</span> <span class="p">{</span>
</span><span class='line'>   <span class="n">Handle</span><span class="p">(</span><span class="kt">int</span> <span class="n">h</span><span class="p">)</span> <span class="o">:</span> <span class="n">impl_</span><span class="p">(</span><span class="mi">100000000</span><span class="p">,</span> <span class="n">h</span><span class="p">)</span> <span class="p">{</span> <span class="p">}</span>
</span><span class='line'>   <span class="o">~</span><span class="n">Handle</span><span class="p">()</span> <span class="o">=</span> <span class="k">default</span><span class="p">;</span> <span class="c1">// just for &#39;rule of five&#39; completeness</span>
</span><span class='line'>
</span><span class='line'>   <span class="c1">// disallow copying, it would be super inefficient </span>
</span><span class='line'>   <span class="n">Handle</span><span class="p">(</span><span class="n">Handle</span> <span class="k">const</span> <span class="o">&amp;</span><span class="p">)</span> <span class="o">=</span> <span class="k">delete</span><span class="p">;</span>
</span><span class='line'>   <span class="n">Handle</span> <span class="o">&amp;</span> <span class="k">operator</span><span class="o">=</span><span class="p">(</span><span class="n">Handle</span> <span class="k">const</span> <span class="o">&amp;</span><span class="p">)</span> <span class="o">=</span> <span class="k">delete</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>   <span class="c1">// ...but allow moving, it is super fast!</span>
</span><span class='line'>   <span class="n">Handle</span><span class="p">(</span><span class="n">Handle</span> <span class="o">&amp;&amp;</span><span class="p">)</span> <span class="o">=</span> <span class="k">default</span><span class="p">;</span>
</span><span class='line'>   <span class="n">Handle</span> <span class="o">&amp;</span> <span class="k">operator</span><span class="o">=</span><span class="p">(</span><span class="n">Handle</span> <span class="o">&amp;&amp;</span><span class="p">)</span> <span class="o">=</span> <span class="k">default</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span> <span class="n">impl_</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>I also use this to ensure my base class destructors are virtual, a simple <code>virtual ~MyType() = default;</code> makes my intentions clear.</p>

<h2>Far fewer Boost dependencies</h2>

<p>Boost is fantastic, but it&rsquo;s a beast and can really slow down compile times. C++11 and onward have made it so I no longer feel it necessary to include boost when starting out with a new project &ndash; I will often add it at a much later stage.</p>

<p>Essential functionality that has been taken from boost that I use all the time:</p>

<ul>
<li>chrono for time measurement: e.g., <code>using clock = std::chrono::steady_clock; auto now = clock::now(); auto later = now + std::chrono::seconds(10);</code></li>
<li>smart pointer libraries</li>
<li>lambda helpers <code>std::bind</code> and <code>std::function</code></li>
<li>new thread library, although <code>std::future</code> still needs a lot of work (to get a <code>then()</code> function equivalent)</li>
<li><code>std::optional</code> to make our interfaces more explicit when invalid data may be returned</li>
<li>the <code>&lt;cstdint&gt;</code> header for precise platform-independent types (for example <code>uint32_t</code> instead of <code>unsigned int</code>)</li>
</ul>


<p>Of note as well are the new regex, random and type index libraries, though they didn&rsquo;t make the list because I don&rsquo;t use them as often.</p>

<p><strong>Functionality that I wish they had taken from boost, or that I would still use boost for</strong> :</p>

<ul>
<li>program options: it&rsquo;s a bit complicated to use, but it gives very high quality functionality and catches all the corner cases I&rsquo;ve ever needed</li>
<li>the new log library (there are probably better ones out there, but as long as I&rsquo;m using boost I might as well use this one)</li>
<li>similarly, the boost unit test library is simple but effective, and you might as well use it if you&rsquo;re already using boost</li>
<li>filesystem, although that is coming in C++17</li>
<li>asio, which has also been proposed for C++17</li>
<li>the range library is a hot topic, people are still trying to figure out how to get this right but boost has had a pretty good stab at it (though sadly <code>range::indexed</code> doesnt play well with range-based for yet)</li>
<li>I often expose basic event attributes on my classes using the signals2 library</li>
<li>the string manipulation and string formatting libraries can be pretty sweet as well</li>
</ul>


<p>I will generally end up including boost in my apps because I really like these libraries.</p>

<h2>Hope for the future</h2>

<p>The C++ language committee is known for being <em>very</em> conservative, with the explicit objective of only adding to the language features they think will still be relevant in the distant future. Created in 1983, the first standard was released in 1998, and with a relatively minor update in 2003 you could be forgiven for saying it was a relatively stagnant language.</p>

<p><span class='pullquote-left' data-pullquote='Today even the most knowledgable C++ consultants are feeling their way around the language'>
But in the last 5 years the landscape has changed dramatically. C++11, although released years later than intended, brings massive changes to both the core language and standard libraries, and the language committee has resolved to release new standards every few years, with C++14 almost released and C++17 well underway. Today even the most knowledgable C++ consultants are feeling their way around the language ; how to most effectively use the new range-based for loops (prefer <code>for (auto &amp;&amp; x: xs)</code>!) and whether perhaps movable types should be <a href="http://scottmeyers.blogspot.jp/2014/07/should-move-only-types-ever-be-passed.html?utm_source=twitterfeed&amp;utm_medium=twitter&amp;m=1">passed by value or by rvalue reference</a>.
</span></p>

<p>C++17 is probably even more exciting for me than C++11 was, because it solves a couple of C++&rsquo;s greatest problems: complicated error messages and crazy compile times. Concepts will allow programmers to write template code <em>without even knowing it is template code</em> !. And we will all be able to create template overloads without resorting to those crazy SFINAE techniques that are so ugly I generally don&rsquo;t use them at all.</p>

<p>But the real truly beautiful feature will be modules. Apple have been heading up a team that will allow us to import modules without causing the pre-processor to continually parse massive compilation units, which is the vast majority of what it does these days. Apple have already implemented the beginnings of this in ObjectiveC, so they have a good grip on the problems. Check out <a href="http://llvm.org/devmtg/2012-11/Gregor-Modules.pdf">this fantastic presentation on modules</a> for more details.</p>

<p>A great summary of the current state of C++17 is the <a href="http://botondballo.wordpress.com/2014/07/17/trip-report-c-standards-committee-meeting-in-rapperswil-june-2014/">notes of the last standards committee meeting</a> . Within you will find such goodies as:</p>

<ul>
<li>Herb Sutter&rsquo;s <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4029.pdf">proposal to make return values explicit</a> . This will make returning <code>unique_ptr</code> types as simple as <code>return {new Thing}</code>.</li>
<li>a proposal for <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4026.html">better nested namespace syntax</a> (e.g., <code>namespace pcx::gl { /* my declarations */ }</code> )</li>
<li>the proposal for enhanced ranged-based for syntax to prevent accidental misuse (currently the recommended syntax is actuall <code>for (auto &amp;&amp; x : xs)</code>, but this will allow us to use <code>for (x : xs)</code>)</li>
</ul>


<p>My wishlist for future enhancements include:</p>

<ul>
<li>better functional constructs (I found a youtube clip of some guy fantasising about <a href="https://www.youtube.com/watch?v=YJIaGRDIyEE">piping data ranges around</a> ).</li>
<li>declarative computation expressions: python, C# and every functional language ever have great consise declarative formats for generating series of data that I would love in C++.</li>
<li>new primitives to make async programming easier &ndash; (<code>async</code> and <code>await</code> are apparently on the way, boost already has a coroutines library!)</li>
<li>stable C++ ABI allowing portable libraries (compilation units from different compilers or even platforms), would mean header-only types can be used in library interfaces/boundaries (e.g., currently cant have boost::any&lt;> in an exported header because it would turn into different code on client and library.) This is already proposed by Herb Sutter <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4028.pdf">here</a></li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[C++ trick: Use Make without Makefiles]]></title>
    <link href="http://seshbot.com/blog/2014/06/16/make-with-no-makefile-for-c-plus-plus-playgrounds/"/>
    <updated>2014-06-16T01:23:57+00:00</updated>
    <id>http://seshbot.com/blog/2014/06/16/make-with-no-makefile-for-c-plus-plus-playgrounds</id>
    <content type="html"><![CDATA[<p>I use CMake personally because managing Makefiles is a hassle. However, I still use <code>make</code> regularly for one purpose: to easily create quick apps without setting up any projects or infrastructure at all. I have no idea where I first heard about this trick, and I can find very little referring to it on the internet. I recently found out that most people didn&rsquo;t know about it though, so I thought I&rsquo;d put a bit of info up here so others can benefit from it.</p>

<p>Generally when using C++ in an IDE it can be a hassle to create a small test application for, say, verifying a new language feature works the way you think it does, or creating a test bed to create a self-contained but complicated algorithm. In such cases, when I am using an OS that supports <code>make</code>, I generally do this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>vim blah.cpp
</span><span class='line'><span class="c"># write your small app</span>
</span><span class='line'>make blah
</span><span class='line'><span class="c"># make magically runs &#39;c++ tmp.cpp -o tmp&#39;</span>
</span><span class='line'>./blah
</span></code></pre></td></tr></table></div></figure>


<p>&hellip; and that&rsquo;s it. It turns out <code>make</code>, when no makefile is present, will try a bunch of stuff that includes searching for <code>.c</code> and <code>.cpp</code> candidate files for generating your target. If the target (in this case &lsquo;blah&rsquo;) ended instead in <code>.o</code> it would sensibly generate an object file without linking it into an executable!</p>

<p>There is no easy way to make it automatically detect dependencies and include them, so all your source has to be within that one file. But there are some further tricks you can do&hellip;</p>

<h2>Compilation options</h2>

<p>By default on my OSX at the moment, make will call my CLang compiler:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nb">echo</span> <span class="s2">&quot;int main() {}&quot;</span> &gt; tmp.cpp
</span><span class='line'>make tmp
</span><span class='line'><span class="c"># c++ tmp.cpp -o tmp</span>
</span></code></pre></td></tr></table></div></figure>


<p>But without any special flags, CLang will compile without C++14 support, which I really want!</p>

<p>An easy workaround to this is to set your <code>CXXFLAGS</code> environment variable that contains the flags you always want to be passed to your C++ compiler by default. In my machine I have added to my <code>~/.bash_profile</code> file: <code>CXXFLAGS='-std=c++1y -stdlib=libc++'</code>. Now when I run this command I get:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>make tmp
</span><span class='line'><span class="c"># c++ -std=c++1y -stdlib=libc++    tmp.cpp   -o tmp</span>
</span></code></pre></td></tr></table></div></figure>


<p>Thats pretty cool. Of course you can set any of make&rsquo;s <a href="http://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html">implicit variables</a> to ensure your app is built with these flags by default. For example, the compiler can be changed to GCC by setting <code>CXX=gcc</code>.</p>

<p>You can also include default include paths and libraries to link against, so that your small apps are able to incorporate boost or even your own library that you are developing.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Swift: a solid modern imperative language]]></title>
    <link href="http://seshbot.com/blog/2014/06/03/swift-a-good-example-of-a-modern-imperative-language/"/>
    <updated>2014-06-03T23:25:06+00:00</updated>
    <id>http://seshbot.com/blog/2014/06/03/swift-a-good-example-of-a-modern-imperative-language</id>
    <content type="html"><![CDATA[<p><em>Note 1: these are first impressions only &ndash; I&rsquo;ve only spent a day really looking at the docs and playing with the XCode beta so I am probably mistaken about some stuff</em></p>

<p><em>Note 2: I am using a beta of XCode, and it has caused me some trouble (a mysterious service it starts keeps crashing, filling my HDD up with core files.) I would recommend waiting for the non-beta if I were you.</em></p>

<p>Apple recently announced the support of a new language targeted at the same application programming space as Objective C. It&rsquo;s called Swift and it seems to me a very good summary of the features all modern imperative languages are striving for.</p>

<p>The last decade or so has seen a strong resurgence in functional programing evangelism. Languages like F#, Scala, Clojure and even Erlang for a while re-introduced to mainstream programmers high-level concepts that imperative programmers were largely unfamiliar with. A short experiment with a language supporting algebraic data types, type inference, higher order functions, closures, or the standard foundational map, reduce and fold functions will convince any programmer that their language
would be far better off being more declarative.</p>

<p>For a comprehensive guide to the Swift language see the <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html">Swift tour</a>.</p>

<p><img src="http://seshbot.com/images/upload/2014-06-04-swift-xcode6.png" title="&#34;Some Swift code in Xcode 6 beta&#34;" alt="&#34;Some Swift code in Xcode 6 beta&#34;"></p>

<p>I have wanted two write another iOS app for a while now, and so I&rsquo;m thinking Swift may be the way forward for me there. To that end I&rsquo;ve spent all this morning going through docs and messing with XCode to get a feel for the various idioms and coding styles it encourages&hellip;</p>

<!-- more -->


<h2>Syntactic niceties</h2>

<p>Swift is a very much streamlined language, and for low friction it seems to take a lot from F#. Like F#, a programmer can seemingly almost approach swift as a scripting language &ndash; the first line in your source file can be functioning application code, no boilerplate required! And the &lsquo;playground&rsquo; concept is very familiar to anyone who has used Scala Workspaces or F# interactive mode.</p>

<p>The clarity of syntax is quite impressive &ndash; type inference introduces <code>var</code> and <code>let</code> common to many modern languages, and bracket-less control flow operations and optional semicolons make your code look a lot cleaner (and a bit like golang).</p>

<p>Structure types may be initialised in-line at the point of instantiation: <code>val vga = VideoMode(width: 800, height: 600)</code>. Once you see this you think <em>of course, why would it be otherwise?</em></p>

<p>Syntactically there is a lot of shorthand available for interacting with fundamental data types:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// create an Array[Int]</span>
</span><span class='line'><span class="kt">var</span> <span class="n">xs</span> <span class="p">=</span> <span class="p">[</span><span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">,</span> <span class="m">3</span><span class="p">]</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// create a Dictionary&lt;String,Double&gt;</span>
</span><span class='line'><span class="kt">var</span> <span class="n">menu</span> <span class="p">=</span> <span class="p">[</span><span class="s">&quot;Coffee&quot;</span><span class="p">:</span> <span class="m">3.5</span><span class="p">,</span> <span class="s">&quot;Bacon&quot;</span><span class="p">:</span> <span class="m">5.1</span><span class="p">]</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// create a tuple of two strings</span>
</span><span class='line'><span class="kt">var</span> <span class="n">location</span> <span class="p">=</span> <span class="p">(</span><span class="s">&quot;Tokyo&quot;</span><span class="p">,</span> <span class="s">&quot;TYO&quot;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// shorthand for iterating over Sequences</span>
</span><span class='line'><span class="k">for</span> <span class="n">x</span> <span class="k">in</span> <span class="n">xs</span> <span class="p">{</span> <span class="n">println</span><span class="p">(</span><span class="s">&quot;x is \(x)&quot;</span><span class="p">)</span> <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And anyone who loves Scala&rsquo;s string interpolation operators will appreciate the ability to write <code>println("hi, my age is \(me.age - 5)")</code>.</p>

<p>As a special treat, Swift also supports Objective-C style named parameters. This can make some functions arguments more clear when they have the same type:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">func</span> <span class="nf">replace</span><span class="p">(</span><span class="n">inString</span> <span class="n">str</span><span class="p">:</span> <span class="n">String</span><span class="p">,</span> <span class="err">#</span><span class="k">value</span><span class="p">:</span> <span class="n">String</span><span class="p">,</span> <span class="err">#</span><span class="n">withValue</span><span class="p">:</span> <span class="n">String</span><span class="p">)</span> <span class="p">-&gt;</span> <span class="n">String</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// ... </span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// then later call it:</span>
</span><span class='line'><span class="n">val</span> <span class="n">simplified</span> <span class="p">=</span> <span class="n">replace</span><span class="p">(</span><span class="n">inString</span><span class="p">:</span> <span class="n">url</span><span class="p">,</span> <span class="k">value</span><span class="p">:</span> <span class="s">&quot;http://&quot;</span><span class="p">,</span> <span class="n">withValue</span><span class="p">:</span> <span class="s">&quot;&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>OK perhaps that is not a great example, but I think the concept has a lot of merit.</p>

<h2>Functional concepts</h2>

<p>In addition to type inference and closures, Swift has obviously been checking out the Scala and F# and the like for ideas, much to its credit.</p>

<p>First, fret not because higher-order operations are all available to you, and included in the standard library are standard set of foundational functions you&rsquo;d expect in a functional language such that it is possible to write <code>var ys = map([1,2,3], {i in i * 2})</code>.</p>

<p>But one thing that seems quite interesting to me is the extended syntax available to enumerations (known as &lsquo;associated types&rsquo;) that make them almost seem like <em>algebraic data types</em>&hellip;</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">enum</span> <span class="n">Shape</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">case</span> <span class="nf">Circle</span><span class="p">(</span><span class="n">Double</span><span class="p">)</span>
</span><span class='line'>    <span class="k">case</span> <span class="nf">Ellipse</span><span class="p">(</span><span class="n">Double</span><span class="p">,</span> <span class="n">Double</span><span class="p">)</span>
</span><span class='line'>    <span class="k">case</span> <span class="nf">Square</span><span class="p">(</span><span class="n">Double</span><span class="p">)</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">func</span> <span class="nf">area</span><span class="p">(</span><span class="n">s</span> <span class="p">:</span> <span class="n">Shape</span><span class="p">)</span> <span class="p">-&gt;</span> <span class="n">Double</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">switch</span> <span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">case</span> <span class="p">.</span><span class="n">Circle</span><span class="p">(</span><span class="n">let</span> <span class="n">radius</span><span class="p">):</span> <span class="k">return</span> <span class="m">3.14159</span> <span class="p">*</span> <span class="n">radius</span> <span class="p">*</span> <span class="n">radius</span>
</span><span class='line'>    <span class="k">case</span> <span class="p">.</span><span class="n">Ellipse</span><span class="p">(</span><span class="n">let</span> <span class="n">min</span><span class="p">,</span> <span class="n">let</span> <span class="n">maj</span><span class="p">):</span> <span class="k">return</span> <span class="m">3.14159</span> <span class="p">*</span> <span class="n">min</span> <span class="p">*</span> <span class="n">maj</span>
</span><span class='line'>    <span class="k">case</span> <span class="p">.</span><span class="n">Square</span><span class="p">(</span><span class="n">let</span> <span class="n">width</span><span class="p">):</span> <span class="k">return</span> <span class="n">width</span> <span class="p">*</span> <span class="n">width</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">area</span><span class="p">(</span><span class="n">Shape</span><span class="p">.</span><span class="n">Circle</span><span class="p">(</span><span class="m">10</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>&hellip;plus, if you add a new value (say, Rectangle) to the enumeration the <code>area()</code> function will fail to compile, as the compiler will complain that the switch <em>must</em> be exhaustive. Take that scala!</p>

<p>Tuples can be <em>pattern matched</em> using placeholders, bound parameters and <em>where</em> clauses, which is a fairly awesome thing:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">switch</span> <span class="p">(</span><span class="n">bounds</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">case</span> <span class="p">(</span><span class="m">0</span><span class="p">,</span> <span class="m">0</span><span class="p">):</span> <span class="n">println</span><span class="p">(</span><span class="s">&quot;zero bounds!&quot;</span><span class="p">)</span>
</span><span class='line'>   <span class="k">case</span> <span class="p">(</span><span class="m">0</span><span class="p">,</span> <span class="n">_</span><span class="p">):</span> <span class="n">println</span><span class="p">(</span><span class="s">&quot;x == 0&quot;</span><span class="p">)</span>
</span><span class='line'>   <span class="k">case</span> <span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="m">0</span><span class="p">):</span> <span class="n">println</span><span class="p">(</span><span class="s">&quot;y == 0&quot;</span><span class="p">)</span>
</span><span class='line'>   <span class="k">case</span> <span class="nf">let</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="k">where</span> <span class="n">x</span> <span class="p">&lt;</span> <span class="m">0</span> <span class="p">||</span> <span class="n">y</span> <span class="p">&lt;</span> <span class="m">0</span><span class="p">:</span> <span class="n">println</span><span class="p">(</span><span class="s">&quot;invalid bounds!&quot;</span><span class="p">)</span>
</span><span class='line'>   <span class="k">case</span> <span class="nf">let</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="p">:</span> <span class="n">println</span><span class="p">(</span><span class="s">&quot;bounds are [\(x),\(y)]&quot;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>There is no true currying though of course it can be simulated by having functions return other functions &ndash; garbage collection + closures means that you can create generators along the lines of:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">func</span> <span class="nf">makeGenerator</span><span class="p">(</span><span class="n">increment</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">-&gt;</span> <span class="p">()</span> <span class="p">-&gt;</span> <span class="n">Int</span> <span class="p">{</span>
</span><span class='line'>    <span class="kt">var</span> <span class="n">x</span> <span class="p">=</span> <span class="m">0</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">{</span>
</span><span class='line'>        <span class="n">x</span> <span class="p">+=</span> <span class="n">increment</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">x</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kt">var</span> <span class="n">gen</span> <span class="p">=</span> <span class="n">makeGenerator</span><span class="p">(</span><span class="m">10</span><span class="p">)</span>
</span><span class='line'><span class="k">for</span> <span class="kt">var</span> <span class="n">n</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">n</span> <span class="p">&lt;</span> <span class="m">100</span><span class="p">;</span> <span class="n">n</span> <span class="p">=</span> <span class="n">gen</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="n">println</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="c1">// prints 0, 10, 20, 30...</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>On a side note, Scala&rsquo;s currying leaves a lot to be desired, as does it&rsquo;s support of ADTs &ndash; one must explicitly make structures a </em>case class<em> before you get functionality approaching an ADT.</em></p>

<p><em>Optional types</em> are also supported in the library but also with nice syntactic sugar. The <code>?</code> operator defines an optional type (similar to C#) and also allows operations on that type to be optionally unwound. The <code>!</code> operator forces unwinding, and causes an error if the optional type is not set.</p>

<p>Also, there is some fancy syntax for switching on an optional type:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">struct</span> <span class="nc">Job</span> <span class="p">{</span>
</span><span class='line'>    <span class="kt">var</span>  <span class="n">title</span><span class="p">:</span> <span class="n">String</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">struct</span> <span class="nc">Person</span> <span class="p">{</span>
</span><span class='line'>    <span class="kt">var</span> <span class="n">name</span><span class="p">:</span> <span class="n">String</span>
</span><span class='line'>    <span class="kt">var</span> <span class="n">job</span><span class="p">:</span> <span class="n">Job</span><span class="p">?</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// create a person with no job!</span>
</span><span class='line'><span class="kt">var</span> <span class="n">paul</span> <span class="p">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="s">&quot;Paul&quot;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span> <span class="n">let</span> <span class="n">title</span> <span class="p">=</span> <span class="n">paul</span><span class="p">.</span><span class="n">job</span><span class="p">?.</span><span class="n">title</span> <span class="p">{</span>
</span><span class='line'>    <span class="n">println</span><span class="p">(</span><span class="s">&quot;you are a \(title)!&quot;</span><span class="p">)</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">else</span> <span class="p">{</span> <span class="c1">// fallthrough because there was a nil optional</span>
</span><span class='line'>    <span class="n">println</span><span class="p">(</span><span class="s">&quot;you have no title!&quot;</span><span class="p">)</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Note: this doesn&rsquo;t currently compile &ndash; the current XCode 6 beta does not compile the samples provided by the documentation. I&rsquo;ll leave this here though because it still captures the intent of the optionals feature</em></p>

<p>Notice how the <code>if`` resolves the expression as false because the</code>?&#8220;` operator did not resolve.</p>

<p>I haven&rsquo;t even touched on a few other cool features like <code>@lazy</code> annotation, generics, variadic parameters, or the myriad ways closures can be specified (it turns out <code>{$0}</code> is a valid closure, with inferred argument and return value!)</p>

<h2>OO niceties</h2>

<p>I&rsquo;ll describe some features based on where I find them most familiar from:</p>

<ul>
<li><em>C#</em> &ndash; <code>struct</code> and <code>class</code> types. Classes are reference-counted (see below) while structs have value semantics (are destroyed automatically.)</li>
<li><em>C#</em> &ndash; extensions and computed properties remind me of C# <em>extension methods</em></li>
<li><em>Objective-C</em> &ndash; <em>Automatic Reference Counting</em> (ARC) provides a kind of semi-manual garbage collection. Essentially whenever you set a reference type to <code>nil</code> it will be collected. (The language also supports weak references.) This system is similar to using <code>shared_ptr</code>s in C++ in that you can end up with circular references, but unlike C++ there don&rsquo;t seem to be any automatic scoping facilities that relinquish resources as they move out of scope. I might be wrong about this.</li>
<li><em>Objective-C</em> &ndash; Swift supports the notion of <em>protocols</em> for polymorphic behaviour</li>
<li><em>?</em> &ndash; Object identity can be compared (i.e., are these references to the same object?) using the <code>===</code> operator.</li>
</ul>


<h2>Does it go far enough?</h2>

<p>In many ways this is a fairly conservative language &ndash; Swift is clean and nice to use, and I think would make a good replacement for Objective-C, but most other modern languages are focusing on higher level concepts that don&rsquo;t seem to be getting a showing here.</p>

<p>The main thing that comes to mind is the lack of language features to help out with thread synchronisation and concurrency. Other languages are focusing on lightweight thread-like structures or coroutines, asynchronous actors or asynchronous computation expressions/monad type syntax (think F# <code>async {}</code>.)</p>

<p>This is the first release of this language and I think some initial conservatism might be sensible. Typically I think compiled and C-based languages have preferred to put new functionality into libraries and only reluctantly add keywords and syntax to the existing base language. On the other hand, other languages (C# 5, F#, Haskell) have shown that without syntactic sugar (like <code>async { }</code>, <code>do { }</code>, <code>yield</code> and the like) it is seemingly implausible to make async-friendly code look super readable and imperative, avoiding what is often known as <em>callback hell</em>.</p>

<p>So here&rsquo;s hoping this project keeps the steam it&rsquo;s started off with.</p>

<h2>Do we need another language?</h2>

<p>Swift is certainly more approachable than Objective-C, which I very much appreciate. Apple have always been quite good at providing an environment where different languages interoperate seamlessly, so there really seems no downside &ndash; if you have a lot invested in Objective-C you can still leverage all your previous work with Swift, or presumably use other peoples swift libraries in your own Objective-C applications.</p>

<p>There will always be curmudgeons of course, but they should be ignored. The lengths that some will go to to justify not having to learn new concepts is always amazing to me, especially when doing so is the best way to progress in our industry!</p>

<p>Apple takes the development of programming languages quite seriously. They are heading up some of the more interesting additions to new versions of C++, most anticipated (by me) being the &lsquo;modules&rsquo; concept that promise to bring C++ compile times and binary interfaces in line with more modern high-level languages. They play this role of innovator well here because the concepts outlined in their proposal are drawn directly from practical experience in implementing said features in the
Objective C language itself.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Week in Review: Running in an infinite world]]></title>
    <link href="http://seshbot.com/blog/2014/05/31/week-in-review-running-in-an-infinite-world/"/>
    <updated>2014-05-31T11:24:19+00:00</updated>
    <id>http://seshbot.com/blog/2014/05/31/week-in-review-running-in-an-infinite-world</id>
    <content type="html"><![CDATA[<p>Here&rsquo;s a quick snap of the 2D SFML client alongside a new OpenGL client:
<img src="http://seshbot.com/images/upload/2014-05-31-compare.png" title="&#34;SFML client alongside OpenGL client with QML overlays&#34;" alt="&#34;SFML client alongside OpenGL client with QML overlays&#34;"></p>

<p>OK I could have spent a bit longer on the screenshot &ndash; I haven&rsquo;t made any models yet other than cubes, and I&rsquo;m not using any textures, and I should have adjusted the angle and colour of the directional light to make it look like evening or morning or something, to show off some of the immediate benefits of going to 3D.</p>

<p>I did spend some time making the camera zoom in from a map-like view to a chase-cam view:
<img src="http://seshbot.com/images/upload/2014-05-31-zoomed.png" title="&#34;The camera is tethered to the player character&#34;" alt="&#34;The camera is tethered to the player character&#34;"></p>

<p>In general however I&rsquo;m hoping to ramp-down on the OpenGL stuff and go back to working on the core functionality. The last week was actually pretty productive:
<img src="http://seshbot.com/images/upload/2014-05-31-bugfixes.png" title="&#34;Most recent git checkins&#34;" alt="&#34;Most recent git checkins&#34;"></p>

<p>Also I&rsquo;ve been spending a fair amount of time in <a href="http://picopicocafe.com">PicoPico Cafe</a> when it&rsquo;s open, and I&rsquo;m guessing I&rsquo;ll be spending more time there in the coming weeks as a bunch of construction is scheduled outside my house during business hours when nobody is supposed to be home.</p>

<!-- more -->


<h2>World Building</h2>

<p>The 3D functionality in my game so far is provided by a thin layer that invokes the exact same service layer (game, player, mobile and prop unit services) used by the 2D client. I took the time to finally make some extensive refactorings that I&rsquo;ve been planning for some time:</p>

<h4>Infinte Terrain!</h4>

<p>The terrain now runs effectively infinitely, in that it can cache any combination of arbitrary regions. The complicating factor was the fact that I want the regions to be stored in a sensible way that provides for really fast lookups many times per second as entities roam around the countryside, even outside of the player&rsquo;s view. More work needs to be done on this to unload cached regions that are no longer relevant.</p>

<h4>Infinte Entities!</h4>

<p>The entity service, responsible for facilitating rapid interactions with many geographically-local entities, can now scale out exponentially more efficiently than before. Entity &lsquo;moment&rsquo; information is stored contiguously in memory for super cache friendly iteration. Unfortunately this encourages the programmer to pre-allocate large portions of memory to allow the number of entities to fluctuate without large re-allocations.</p>

<p>Because of this obsession with data locality, every region was previously allocating enough space for all entities in the game to coexist at once so I could trivially say <code>auto moment = entities_[entityId].moment;</code> (or something kinda like that.) Now I changed it so there is a single ledger shared outside the specific regions with lookup instructions for each entity indicating that entity&rsquo;s region and index within that region. This means that the regions can be much smaller, reducing the region-to-memory relationship from exponential to linear, which is HUGE. (Of course, the old scheme was never meant to stay in there.)</p>

<p>I now have 1,000,000 entities pre-allocated without straining memory or computational resources at all (about 100MB memory for the whole app) whereas before I was settling for about 10,000 lest I run into gigabytes for a game with a relatively small number of regions.</p>

<h4>Lots more stuff of course</h4>

<p>I also made an interesting change to the core &lsquo;entity moment&rsquo; structure so it includes a &lsquo;facing direction&rsquo; as well as the existing velocity vector that indicates which direction and at what speed the entity is moving. I was having trouble determining the direction an entity should face when it is not moving (the velocity is 0,0 so has no implicit direction.) This wasnt a problem when I was rendering all entities as circles.</p>

<h2>Back to OpenGL 2 again</h2>

<p>The more I learn about the troubles people have with OpenGL the more concerned I became about getting my app to work on Windows. Through a fine bit of serendipity I met the always helpful <a href="http://greggman.com/">Greggman</a> at PicoPico, who was one of the devs who implemented WebGL in Google Chrome. He gave me some great advice that lined up with a few things I&rsquo;d found on the internet and convinced me to move to OpenGL ES 2.0.</p>

<p>As I mentioned last week OpenGL support in Windows is lacking due to MS pushing their own DirectX 3D stack. But fortunately Google have written a library called <a href="https://code.google.com/p/angleproject/">ANGLE</a> that is a &lsquo;conformant implementation of the OpenGL ES 2.0 specification that is hardware‐accelerated via Direct3D.&rsquo; This means that if you write conformant OpenGL ES 2.0 code you get DirectX compliance for free (at least that is the idea.)</p>

<p>Another advantage of OpenGL ES (other than the widespread support, including on mobile devices) is that it is much more stringently standardised. Apparently standard OpenGL does not come with conformance tests of any kind, so vendors don&rsquo;t have a mechanical way of verifying that they have implemented conformant drivers. ES does have such tests however so anecdotally provides a much cleaner integration experience.</p>

<p>Of course I&rsquo;m effectively going back to OpenGL 2 syntax and functionality which is a bit of a drag, but I wasn&rsquo;t really using geometry shaders or complex alternative rendering pipelines anyway.</p>

<h2>Object Picking with the mouse</h2>

<p>If someone clicks on a pixel on the screen (in pixel coordinates), how do you discover which object they were clicking on? This is deceptively difficult! The old way of doing it involved using a special part of OpenGL called <em>selection buffers</em> that allows you to assign a name to each entity being rendered, and query a pixel for the name of the entity rendered therein. That is deprecated however.</p>

<p>The modern analog of this is a manual process called <em>colour picking</em>, which involves rendering identifying values instead of colours to a special buffer that is not rendered. This image can be queried via <code>glReadPixels()</code>, the returned result is the identifying value of the object at that pixel. I chose not to go down this route though.</p>

<p>Instead, I chose to do it entirely on the CPU by performing the rendering calculations in reverse, in a process often known as <em>raycasting</em>. The rendering process involves taking each entity in your scene and multiply its coordinates by a <em>model matrix</em>, then a <em>view matrix</em> and then a <em>projection matrix</em>, transforming it into world space, then into camera space, and then into screen space. To figure out what object is at a pixel, I perform these operations in reverse by passing those pixel coordinates to the <em>inverted</em> perspective matrix and then to an <em>inverted</em> view matrix. This gives you the location of a point in
space corresponding to that point on the screen. If you draw a line from the location of the camera through that point, you have a <em>ray</em> into 3D space that is every point behind that pixel! The object picked is the object intersecting with that ray that is closest to the camera (I&rsquo;m just iterating through every object near the camera for now.)</p>

<p>For more information on this have a look at <a href="http://antongerdelan.net/opengl/raycasting.html">this article on raycasting</a>. I like this because it is purely algorithmic and doesn&rsquo;t require special shader code or anything.</p>

<h2>Qt Quick and OpenGL</h2>

<p>I continue to be happy with Qt &ndash; they are so active, they&rsquo;re always releasing interesting new tech. It is hard to catch them for feedback but it can be done and when they are on IRC they are very helpful.</p>

<p>Unfortunately the OpenGL support in Qt Quick is still in a great state of flux, so finding the correct way to use OpenGL ES was quite tricky. Turns out however that simply <em>not</em> specifying an OpenGL version, and using the default function pointers their <a href="http://qt-project.org/doc/qt-5/qopenglfunctions.html">utility library provides</a> is the proper way of using OpenGL ES in a portable fashion, even when your platform does not provide it (it falls back on the &lsquo;desktop&rsquo; 2.0 functions.)</p>

<h2>Up Next</h2>

<p>My representation of the world in the core code is still effectively 2D in that all entities have an <em>x</em> and a <em>y</em> but no altitude component. For rendering purposes that is extracted from the terrain service by the rendering engine for visual effect only. But if I am to allow jumping and have some notion of visual occlusion I will soon have to add a <em>z</em> component to the velocity and the position of each entity. This will also mean that the entity service will need to be dependent on the
terrain service.</p>

<p>I also want to implement a proper day/night cycle and some fancy controls in the GUI, like a slider that allows you to choose the time of day. This will hopefully provide a large ambiance improvement at little cost.</p>

<p>As far as blogging goes, last week I was intending my next post to be about my adventures in OpenGL and to provide a clear roadmap for others who want to follow the same path I took, but it is such a <em>huge</em> topic, and I am still not certain I have all the facts right, that I have put it off so far. We&rsquo;ll see how that goes&hellip;</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Week in review: Porting to Qt/QML with OpenGL]]></title>
    <link href="http://seshbot.com/blog/2014/05/16/week-in-review-c-plus-plus/"/>
    <updated>2014-05-16T00:56:26+00:00</updated>
    <id>http://seshbot.com/blog/2014/05/16/week-in-review-c-plus-plus</id>
    <content type="html"><![CDATA[<p><em>So I took a month holiday, and got out of the habit of writing blogs&hellip; hopefully this will break the dam, it&rsquo;s not like I don&rsquo;t have a billion things to write about</em></p>

<p>Over the last many weeks I have been ploughing through a whole lot of new stuff I&rsquo;ve never used before. As mentioned in my last post I decided to up the graphics a bit, but specifically I wanted to figure out a system for a extensible UI for menus and other 2D overlays, and 3D or pseudo-3D graphics. Creating a decent UI controls library I have learned is very difficult (if kind of fun to be honest.) Making something that is flexible enough to automatically layout your controls in a sensible way where everything resizes based on the
content contained within is a very difficult problem that nobody should have to re-solve in this day and age. So I wanted to re-use one that I also wanted to learn for myself.</p>

<p>In order to add these to my existing framework I took on the (it turns out) monumental task of learning OpenGL and integrating it with Qt/QtQuick/QML.</p>

<p>So far things are looking OK, but I have found the learning curve greater than I&rsquo;d originally anticipated &ndash; OpenGL in particular is a rabbit warren of deprecation and messy global state idioms. That said, I currently have:</p>

<ul>
<li>the UI menu/control system is entirely QML based and very simple to extend and use</li>
<li>the game terrain is constructed using <a href="http://www.volumesoffun.com/polyvox-about/">PolyVox</a> because I wanted to avoid having to figure out mesh generation along with all this other stuff</li>
<li>the OpenGL shaders incorporate basic lighting and not much else</li>
</ul>


<p>The main value I&rsquo;ve gained is a fairly decent understanding of what it takes to create modern OpenGL applications (though how useful that knowledge is in this day and age I am not sure.) I have not tried porting any of this across to Windows yet (I&rsquo;ve written it all in OSX) but hopefully the fact that I&rsquo;m using entirely cross-platform technologies will help a little there &ndash; though Windows is known to have very dodgy OpenGL support so I suspect that will be the cause of most of my porting
troubles.</p>

<!-- more -->


<h2>The Qt Stack</h2>

<p>I&rsquo;ve always been interested in <a href="http://qt-project.org/">Qt</a> &ndash; I don&rsquo;t know of any more highly polished user interface libraries for C++ out there, and they&rsquo;ve been producing really interesting technologies out that seem like they were created by people who actually understand C++. As a developer who opted to buy in to the Microsoft WPF UI framework, I find the QtQuick and QML libraries to be thoroughly refreshing and intuitive.</p>

<p>QML is a clean and simple markup language for writing user interfaces in a declarative fashion. The most apparent advantages over WPF for me were that the syntax is not XML based and that the property bindings may be declared in javascript, within which any properties are automatically dynamically bound so that property updates are detected and cascade automatically through the entire scene graph. In addition to that, the C++ to QML binding mechanism entirely leverages the Qt
metadata system that they&rsquo;ve tooled out and honed over the last more-than-a-decade, so everything just seems to work!</p>

<h3>QML basics</h3>

<p>Here&rsquo;s a simple QML example:</p>

<figure class='code'><figcaption><span>Simple QML example</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kr">import</span> <span class="nx">QtQuick</span> <span class="mf">1.0</span>
</span><span class='line'>
</span><span class='line'><span class="nx">Rectangle</span> <span class="p">{</span>
</span><span class='line'>   <span class="nx">width</span><span class="o">:</span> <span class="mi">200</span>
</span><span class='line'>   <span class="nx">height</span><span class="o">:</span> <span class="mi">200</span>
</span><span class='line'>   <span class="nx">color</span><span class="o">:</span> <span class="s2">&quot;blue&quot;</span>
</span><span class='line'>
</span><span class='line'>   <span class="nx">Image</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">source</span><span class="o">:</span> <span class="s2">&quot;pics/logo.png&quot;</span>
</span><span class='line'>      <span class="nx">anchors</span><span class="p">.</span><span class="nx">centerIn</span><span class="o">:</span> <span class="nx">parent</span>
</span><span class='line'>   <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>C++ QML components are essentially just regular C++ classes that use the Qt metadata system to expose properties, signals and slots &ndash; there really is no special QML magic required. These types are exposed to the QML engine through a single C++ commmand <code>qmlRegisterType&lt;MyCoolControl&gt;("com.seshbot", 1, 0, "CoolControl");</code>. This can then be consumed from within your QML by first <code>import com.seshbot 1.0</code> and then declaring your <code>CoolControl { }</code> just like the <code>Rectangle</code> in the above example.
All properties declared in the C++ class are immediately available from within QML &ndash; any changes made from the QML file will automatically call your setters, and any updates from within your C++ class will automatically propogate out to the QML file. MAGIC!</p>

<h3>QML with OpenGL</h3>

<p>As of Qt Quick 2.0, QML internally uses OpenGL to do all its own rendering so rendering your own OpenGL should theoretically not be too difficult. In fact, check out this <a href="https://www.youtube.com/watch?v=P4kv-AoAJ-Q">awesome demo</a> of a guy messing with an OpenGL shader in QML in real time. In the end however it took a few weeks to iron out, largely because this technology is pretty new and still has some kinks, and is not well documented yet (at least the stuff I wanted to do.)</p>

<p>There are three ways I know of putting your OpenGL content into a QML scene:</p>

<ul>
<li>create a custom Qt control that does all the OpenGL stuff internally and include that control in your <code>QtQuickView</code></li>
<li>extend <code>QtQuickView</code> and do the OpenGL stuff in its constructor</li>
<li>rendering your OpenGL to a frame buffer and having Qt inject that into its own layout. This is what <a href="http://advancingusability.wordpress.com/2013/03/30/how-to-integrate-ogre3d-into-a-qt5-qml-scene/">Ogre integration</a> does, but I haven&rsquo;t explored this</li>
</ul>


<p>There&rsquo;s not much difference between the two approaches &ndash; I went with the second because creating a control that is invoked from QML raises questions of how you inject your game state into the view. I wanted to just pass my game data into the constructor.</p>

<p>The Qt libraries come with an example called &lsquo;Scene Graph &ndash; OpenGL under QML&rsquo; that I found very helpful.</p>

<p>I did encounter a few problems:</p>

<ul>
<li>the QtQuick Controls library (which provides native-looking controls you can use in your QML files) don&rsquo;t seem to work with OpenGL versions older than OpenGL 4. After consulting the Qt guys on their IRC channel (#qt-quick on freenode) I <a href="https://bugreports.qt-project.org/browse/QTBUG-38817">filed a bug</a>, so hopefully it will be addressed in future versions.</li>
<li>my specialised QtQuickView class (that renders my game in the background under the QML stuff) didn&rsquo;t want to render any of my immediate mode OpenGL code &ndash; this is probably OK because immediate mode has been deprecated since version 1. (more on OpenGL versions and immediate mode and such in the future!)</li>
<li>all of the demos use older versions of OpenGL (probably to minimise compatability issues on Windows) so I had a bunch of surprises when I tried modernising it (basically had to learn each version of OpenGL as I progressed)</li>
</ul>


<p>The Qt quick guys are on the #qt-quick IRC channel around 9pm japan time by the looks, so that&rsquo;s generally the best time to get live help if you need it.</p>

<h2>OpenGL</h2>

<p>My god, OpenGL is a mess. Each version of OpenGL (there are 4) seemed to deprecate the old way of doing things and introduce entirely new idioms:</p>

<ul>
<li>OpenGL 1 was all about &lsquo;immediate mode&rsquo; because there were no shaders yet. You just tell OpenGL (in your C++ code) where the primitives and lights are and it takes care of all the rendering details</li>
<li>OpenGL 2 introduced the GLSL shader language for writing &lsquo;vertex&rsquo; and &lsquo;fragment&rsquo; shaders. This was a huge step forward in performance because you pipe all your vertex data into the graphics card in one go, but it meant that you have to do all the lighting and model/view/perspective transformations yourself in the shader. This makes it a lot harder to pick up for newbies.</li>
<li>OpenGL 3 totally messed with the GLSL syntax, and added the notion of vertex buffer objects (VBOs) which I found out are <em>mandatory</em> to use although nothing will warn you if you do not use them. Things just wont show up. Also there is a new type of shader &ndash; the &lsquo;geometry&rsquo; shader.</li>
<li>OpenGL 4 introduced the &lsquo;tessellation&rsquo; shader. I have no idea what that does yet as I have not started down the OpenGL 4 road.</li>
</ul>


<p>In addition to this, Windows only natively supports OpenGL 1, because they follow their whole DirectX thing. You can ask your users to upgrade their video drivers, or you can use an OpenGL &ndash;> DirectX translation layer to get around this problem (Qt apparently offers optional compatability via Googles <a href="https://code.google.com/p/angleproject/">ANGLE</a> library.)</p>

<p>Plus, any platform may support any number of &lsquo;extensions&rsquo; which provide capabilities on top of the &lsquo;core&rsquo; functionality offered by that OpenGL version. A good application will check the availability of all extensions they are using, which seems like a massive hassle to me at this point. Theres a library called the GL Extension Wrangler (GLEW) thats supposed to help with this, and Qt has its own set of helpers to ensure that youre only able to invoke functionality thats actually provided by
your chosen GL version.</p>

<p>Oh, there are also the &lsquo;embedded&rsquo; versions of OpenGL &ndash; OpenGL ES. These are apparently much smaller and well supported so I think I will migrate towards using some OpenGL ES version in the near future &ndash; probably OpenGL ES 2.0, which is supposed to be compatible with OpenGL 4.1 I believe.</p>

<p>In general I&rsquo;d say stay away from writing your own graphics drivers at this level &ndash; use higher level stuff that abstracts your OpenGL vs DirectX decisions from you. I went with OpenGL because I was suffering the delusion that it would make my experience with my QML layer simpler, but looking at the incompatabilities and weird differences between platforms I can see a lot of trouble in my future if I continue down this route.</p>

<p>I plan to write a more thorough map of the path I took through this so that hopefully others do not have to make the same mistakes I did.</p>

<h2>PolyVox voxel mesh generation</h2>

<p>I didn&rsquo;t want to also have to figure out how to generate meshes for my game at this point, so I decided to go with a library that allows the easy generation of voxel meshes.</p>

<p>PolyVox is actively being developed by a couple of pretty smart guys. A lot of it has the feel of a university thesis project, but it seems to work quite well, which is the most important thing. Most helpfully for me, they seem to be writing their examples using Qt in Windows and Linux, so I can learn from their mistakes with OpenGL on Windows (something I&rsquo;ll have to do soon.)</p>

<p>I plan to try generating some models in Blender and use something like <a href="http://assimp.sourceforge.net">AssImp</a> to import them into my game soon.</p>

<h2>General application design</h2>

<p>I really want to put my stuff on github but I&rsquo;m finding myself a bit recalcitrant on that front, because its still got so much half-baked experimental stuff in it. I will push myself to do it soon however because I&rsquo;d like to link to parts of the code when writing these blog posts.</p>

<p>It was somewhat satisfying to realise that all of the changes and work I&rsquo;ve done in the last couple of months has had no effect on the core modules I established for the 2D version of my game. All the terrain and entity management, along with the core module message passing mechanisms have remained the same.</p>

<p>I spent some time discovering an intuitive way to describe my 3D scene for rendering in OpenGL (i.e., for encapsulating all the OpenGL buffers, shader programs and shader program attribute bindings.) Of course this has been done many times before but OpenGLs &lsquo;stateless&rsquo; approach (or whatever they call having to bind your objects to global state) makes this a challenge.</p>

<p>The fundamental types in my scene description are:</p>

<ul>
<li><code>camera</code> encapsulates the perspective and view matrices (mapping world-space coordinates to pixels in the view). This has a <code>render()</code> method which tells the <code>scene</code> to render itself using this camera&rsquo;s view data</li>
<li><code>scene</code> contains all the entities and light data that may be rendered into the view, as well as the active shader program. The scene invokes each <code>entity</code>s <code>render()</code> method</li>
<li><code>entity</code> encapsulates a <code>model</code> that is to be rendered as well as the model matrix which maps the mesh from local &lsquo;model coordinates&rsquo; into the world coordinates, oriented the correct way and all that jazz</li>
<li><code>model</code> encapsulates all the buffers and VBOs required to render a mesh</li>
</ul>


<p>My system is also pretty dynamic &ndash; changes to the shader program files on disk immediately cause the application to re-compile and start using the new shader in the application, which helps speed things up on occasion.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Week in Review: Making Games]]></title>
    <link href="http://seshbot.com/blog/2014/02/22/week-in-review-making-games/"/>
    <updated>2014-02-22T01:35:00+00:00</updated>
    <id>http://seshbot.com/blog/2014/02/22/week-in-review-making-games</id>
    <content type="html"><![CDATA[<p>I have once again bitten off a whole lot &ndash; I started making a game based on my fairly limited knowledge of how such things are done, and have found it very difficult to take a moment to distill my thoughts. In fact it has been nearly impossible as I have been constantly unsure of whether the approach I&rsquo;m taking is actually going to pay off in the long run!</p>

<p>This is just a catch-up on my experiences over the last few weeks, a few discoveries and surprises, and perhaps my plans for the immediate future. I decided at the last moment to include a screenshot here, but I&rsquo;m sure we&rsquo;ve all seen brown circles on green backgrounds before&hellip;</p>

<p><img src="http://seshbot.com/images/upload/2014-02-22-game-screenshot.png" title="&#34;This is a 100m section of a 10km world&#34;" alt="&#34;This is a 100m section of a 10km world&#34;"></p>

<p>I also created a (low framerate) <a href="http://seshbot.com/images/upload/2014-02-22-game-early.gif">animated gif</a> of this in action.</p>

<!-- more -->


<p></p>

<h2>Making a game/engine</h2>

<p>The general advice people give new game developers is to never make a game engine &ndash; focus on just getting your game concept out. I will largely be ignoring this advice because I don&rsquo;t have a specific idea for a game yet, just a general notion that it will be client/server and a kind of town-builder. Based on this alone I believe that careful work now will be necessary to ensure the scale of the world I have in mind will be possible &ndash; the virtual world will almost certainly need
geo-spatial partitioning to ensure location-based entity lookups and collision detections can be performed in decent time, and because only a small portion of the virtual world will likely be viewed, and likely only viewed in a separate client application altogether, there is no reason to have the core game logic mixed in with rendering logic at all.</p>

<h3>Modularity and the basic framework</h3>

<p>I intend to write a separate article on this, but first a quick rundown on my PCX library. I actually spent a lot of time trying to bring some of the nicer IOC container abstractions I&rsquo;ve grown used to in .Net and Java to my C++ environment. Breaking an application up into abstract services is a great way to ensure minimal coupling and well designed boundaries around modules of code. This usually involves a lot of reflection in newer languages. My solution in C++ involves run-time type identification (RTTI) which is generally considered anathema in C++, but it can facilitate the creation of libraries that deal in terms of interdependent types, and have nothing to do with the functionality of those types per se.</p>

<p>I decided on these core high-level abstractions:</p>

<ul>
<li><em>services</em> are the core contracts that different sections of code use to communicate with each other. If you want to work with the weather, get yourself a hold of the weather service</li>
<li><em>commands</em> are messages sent into the application as a whole from outside &ndash; services can advertise which commands they can respond to, and the client application can bind keys or whatever to these commands. This abstraction is probably more focused on games</li>
<li><em>modules</em> provide concrete implementations of a bunch of specifically configured services and expose commands. The application mainline only interacts with modules &ndash; it starts them up and shuts them down, and the modules provide all the functionality of the application</li>
<li><em>message bus</em> provides singleton channels for application-wide cross-cutting concerns. I have not yet found a particular use for this, but intend to use it for sending &lsquo;hints&rsquo; out that have no true affect on the state of the application, such as <em>dump debug information now</em>.</li>
</ul>


<p>The central idea is that different abstract concepts such as geography, creature behaviour, economy, weather, client UI etc are all provided by separate modules. When started up, a module can publish services they provide and consume services provided by other modules via a &lsquo;service locator&rsquo;. It is very important that the &lsquo;service locator&rsquo; is only used by the high-level module code directly to ensure they&rsquo;re not used to hide globals and introduce crazy interdependencies. The module creation
mechanism provides a fluid dependency syntax that ensure each module is initialised after the modules on which it depends (i.e., publishes services which this module consumes.)</p>

<p>I created a core library (I named <code>pcx</code> after my own initials and the letter &lsquo;x&rsquo; which is super cool) that I intend to be useful as a general-purpose C++ library for anyone wanting to add these concepts to their own application.</p>

<h3>Deciding on core abstractions</h3>

<p>I&rsquo;ve been thinking about making a game for a long long time now, and have had a myriad of thoughts on how I would create all the major abstractions, modularise the code, and manage multiple clients, network latency, sharding, etc. But when I actually sat down and put hands to keyboard, the first problems I ran into were hugely and unexpectedly daunting &ndash; how should position and rotation be stored? And time? Should position be a vector of floating point numbers or integers? And
should velocity be another vector, or polar coordinates (rotation and magnitude). Should rotation be implicit from velocity, or should entities be able to face one direction but move in another?</p>

<p>These are all decisions that will affect the application in almost every way, and doubtless create deep-seeded performance and functionality trade-offs, and as this is my first game I wasn&rsquo;t really sure what those might be. For example, if I choose to represent velocity as a vector (x, y components), then I lose the ability to determine the direction a stationary unit is facing ([0,0] gives no information in that aspect). Polar coordinates do not suffer this problem however. But the
calculation for moving an entity with cartesian vector velocities is so trivial! Just <code>newPos = pos + velocity * time</code>&hellip; It&rsquo;s very tempting to go with that!</p>

<p>And if I store latitude/longitude of an entity as floating point numbers, I expect I might run into rounding problems with entities far from the origin point. Or when comparing entities close to the origin with those far from the origin. But floating point numbers allow me to say &lsquo;all distances are in meters&rsquo; which makes thinking about and configuring the application that much easier for me.</p>

<p>In the end I kind of arbitrarily chose to store locations and velocities as vectors of doubles, and will probably store a &lsquo;facing direction&rsquo; as a float in radians. Real-time time is likewise a double, indicating fractions of a second. I have not yet implemented any concept of in-game time however.</p>

<h3>Discovering engine capabilities</h3>

<p>I quickly found it very important to keep a close eye on the performance impact of all my decisions as well. It was quite exciting to get my original simple framework up (a &lsquo;world&rsquo; module that holds all the entities and their locations/momentums in the game) and determine the maximum number of visible entities it could support. I found it started dropping frames at around 40,000 moving entities in the world, but I quickly realised however that I have no idea what a good number is &ndash; how many entities <em>should</em> it be able to support?</p>

<p>Most engines I&rsquo;ve looked at (e.g., Quake and Source engines) suport the low 1000&rsquo;s of entities, but most of those are client-only frameworks. I couldn&rsquo;t find a lot of info on MMOs (not that I&rsquo;m making an MMO but I would like to get a feel for scale), and could only find indirect references to EVE online supporting <a href="http://www.gamasutra.com/view/feature/132563/infinite_space_an_argument_for_.php?page=2">up to 30K entities in some of their major battles</a>, but they apparently do all sorts of crazy stuff to support that such as slowing down time and moving entities not directly involved out onto other shards.</p>

<p>In the end it&rsquo;s all moot however, as my game is still very trivially implemented and is not a real-world example of how it will eventually work. For one, all moving entities in the world just walk in an anti-clockwise circle and don&rsquo;t look at the world around them (this will add a lot of complexity to say the least!). Secondly, the game currently updates every entity in the game 60 times per second. I should definitely make entities further from the player &lsquo;stupider&rsquo; and less
frequently updated, and there is actually no good reason to update all entities 60 times per second anyway &ndash; that number was chosen because that is the framerate of the GUI and I have currently tightly bound the world update logic to the core game loop. I will be decoupling these soon.</p>

<p>I have found it&rsquo;s very interesting to keep a good feel for the performance of the application as I work on its foundation &ndash; every time I make a significant modification I run it with varying conditions and check how it performs relative to previous iterations. This has led to some interesting discoveries regarding performance of iterators and iterator adapters, and some very puzzling edge-cases where the Clang optimiser seems to suddenly start borking. But more on that some other time.</p>

<p>The &lsquo;modules&rsquo; abstraction is really helpful in monitoring performance &ndash; the core game loop just iterates over each module, effectively saying <code>for each module m, m.update(timeSinceLastUpdate)</code>. I put a basic metrics counter around this tight loop and get some pretty useful output that shows how many milliseconds each module consumes per tick:</p>

<figure class='code'><figcaption><span>Stats are dumped to standard output ever second</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>Job <span class="nb">time </span>accumulations in 1000ms:
</span><span class='line'> -               client - 60 ticks, avg: 0ms max: 0 total: 0ms <span class="o">(</span>0%<span class="o">)</span>
</span><span class='line'> -                 mobs - 60 ticks, avg: 0ms max: 3 total: 9ms <span class="o">(</span>27%<span class="o">)</span>
</span><span class='line'> -                props - 60 ticks, avg: 0ms max: 0 total: 0ms <span class="o">(</span>0%<span class="o">)</span>
</span><span class='line'> -                world - 60 ticks, avg: 0ms max: 0 total: 23ms <span class="o">(</span>72%<span class="o">)</span>
</span><span class='line'> -      render entities - 58 ticks, avg: 5ms max: 8 total: 339ms
</span><span class='line'> -   update all modules - 58 ticks, avg: 0ms max: 3 total: 33ms
</span></code></pre></td></tr></table></div></figure>


<p>From this output it is obvious that the &lsquo;render entities&rsquo; step is taking a long time &ndash; I should really investigate this!</p>

<h3>C++ development experiences</h3>

<p>Regarding the choice of C++ as a language, it is sometimes a boon and often times a bane. The absolute major pain I&rsquo;m trying to avoid is massive compile and link times. These can only be mitigated through careful control of modularity and inter-dependencies. This is something one should struggle to achieve in any case, but it is constantly undermined by the use of templates and libraries that use templates.</p>

<p>And the Eigen C++ matrix library seemed like a good choice, but it comes with a harrying legacy &ndash; it prefers to use special high-performance instruction sets available on some machines that require your objects to be defined in a certain way (with special alignment specifications when memory is allocated.) These are known as <a href="http://eigen.tuxfamily.org/dox-devel/group__TopicFixedSizeVectorizable.html">fixed-sized vectorisable</a> types and can cause segmentation faults if used incorrectly. Fixed-size vectorisable types cannot be passed by-value to functions or methods, and all classes that contain
such types must themselves specially override the <em>new</em> operator to ensure these alignment requirements are maintained. And STL classes that contain these types must take this into account, so Eigen provides its own implementation of the STL vector that you must use. PLUS all of these restrictions apply to types that you create that have eigen members, and I think also to classes that aggregate THOSE types! It is a huge pain in the ass if you like creating abstract interfaces, to say the least.</p>

<p>I suspect that Eigen will cause all sorts of problems when I move to Windows, so I want to try that out sooner rather than later. The special vectorisation can be disable at compile time but I&rsquo;d rather see if it causes problems first.</p>

<h2>Qt Creator and CMake</h2>

<p>I was originally going to go with XCode for development on OSX &ndash; I&rsquo;d really love to learn how to use that well as it seems quite different to most other editors and not intuitive for me. Ultimately however I decided against it because it doesn&rsquo;t work well with CMake (I think I would have to constantly be re-loading the project) and, at the time anyway, I was thinking that I really wanted to work with QT Quick and other Qt technologies.</p>

<p>So I decided to go with Qt Creator as a development IDE. It is certainly a huge pleasure to use, and has more than the usual amount of high-level functionality one would expect in a C++ development environment. As a bonus it has fairly decent integration with CMake &ndash; the only missing aspect here is that it doesn&rsquo;t allow you to easily add files to your CMake project, but I have made a few tools that allow me to do this easly from the command prompt (more below.)</p>

<p>The main problem I&rsquo;ve had so far is that in order to use the latest C++11 functionality I went with Clang over GCC as a compiler. While Qt Creator supports this, it still seems to try to use the GDB and GProf etc for debugging and profiling, which don&rsquo;t work with Clang. I am going to spend some time soon figuring out how to fix this, but it seems to involve creating a new &lsquo;kit&rsquo; that defines which dev tools the IDE should invoke. It seems complicated however&hellip;</p>

<h2>OSX Development</h2>

<p>I really enjoy working on OSX &ndash; it has all the goodness of a good linux development environment along with some really smooth apps.</p>

<p>One of the worst aspects of Windows development is the extremely weak command line environment. The history of the command line shell (MS-DOS prompt) still seems mired in its QDOS (Quick and Dirty Operating System) origins from the very early &lsquo;80s. While it supports basic pipes and has a few commands like <code>find</code> and&hellip; erm&hellip; anyway, while it has some limited functionality available, it is not a scratch on the highly evolved GNU/Linux environment that has been continually improved over
the last 30 years or so. If you want a tool that does anything moderately complex in Windows you need to find one on the internet generally, whereas in Linux there is no limit to what can be accomplished with <code>sed</code>, <code>grep</code>, <code>find</code>, <code>cut</code>, <code>awk</code>, <code>tr</code> and the like.</p>

<p>For instance, one real annoying aspect of C++ development for me has always been the relative difficulty of creating new projects. Java IDEs can easily provide the ability to create new projects and packages through a simple right-click in your project tree, because Java is very opinionated about where such files go. C++ just requires the symbols to <em>exist</em> at link time, so they could come from anywhere, and there are limitless conventions about how to manage header files in your filesystem.</p>

<p>I have my own conventions for managing my hierarchy of source and header files, and decided to create template projects and modules (my own abstraction for this project) and create shell scripts that allow me to set up entirely new projects with a simple <code>x.new-module thing Thing</code>, which will create all the necessary headers, source files and CMake files, with default sensible names and namespaces, and include them into my current project. This would have been a nightmare to put together
in Windows but has been trivial in OSX.</p>

<h2>Next steps</h2>

<p>I recently added the all-important geo-spatial partitioning in a very simple way, but this seemed to cause some significant performance penalties. I have decided to take the plunge and figure out how to get the profiler working properly with Qt Creator to help me investigate this, because working on a large project without a profiler is like driving a car with a map but no windows &ndash; it&rsquo;s hard to tell if you&rsquo;re still on the road.</p>

<p>I really want to get some graphics in there but I have no experience with that, so am considering messing around with shaders to see if I can get a good lighting model in there first. This should really help me figure out the environmental aesthetic I&rsquo;m going for.</p>

<p>At some stage I&rsquo;ll need to figure out how I&rsquo;m going to make the game overlays such as menus, dialogs, text boxes etc. Previously I&rsquo;ve used SFGUI (works well with SFML which is the C++ GUI library I&rsquo;m using) but I would like to see if I can get QT Quick and QML working with SFML. I don&rsquo;t want to spend too long on this however because I intend to move the GUI code to perhaps another language (C# and Unity) so effort spent on the GUI might be ultimately wasted.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Week in Review: Pausing Web App, Starting C++ App]]></title>
    <link href="http://seshbot.com/blog/2014/02/02/week-in-review-pausing-web-app/"/>
    <updated>2014-02-02T22:52:52+00:00</updated>
    <id>http://seshbot.com/blog/2014/02/02/week-in-review-pausing-web-app</id>
    <content type="html"><![CDATA[<p>Just over a week ago I decided to put down my web tools for a while and move to working in an environment in which I&rsquo;m much more comfortable &ndash; C++. I will definitely pick up the &lsquo;Table Top&rsquo; app (or whatever it turns into) again soon but I felt the need to do work that resulted in a more <em>tangible</em> product.</p>

<p>Over the last few weeks I&rsquo;ve had a growing realisation that the foundation of web programming is still immature, and I am doubting the value in investing too much time learning the high-level technologies. I am not really one for learning frameworks in general actually &ndash; I much prefer learning languages and idioms &ndash; and modern web programming is all about rapidly changing high-level frameworks.</p>

<p>That said however, I feel that I&rsquo;m finally at a point where I can start making useful stuff in Ember and Rails without feeling like I&rsquo;m misusing the tools or spending most of my time in Google. So last week I knocked off a few high-level features in my app to show the basic scaffolding I was considering (it only took a few hours in the end!), and then set it aside.</p>

<p><img class="center" src="http://seshbot.com/images/upload/2014-02-03-seshbot-framework.png" title="&#34;Game Table App as of Feb 2014 - still doesn't do much&#34;" alt="&#34;Game Table App as of Feb 2014 - still doesn't do much&#34;"></p>

<p>There is a very duct-tape and chicken-wire feel to web technologies, but once you&rsquo;re familiar with the tech you can pump stuff out pretty quickly. Because of the immediate and ethereal nature of the web it can be a fantastic way of creating a product that is immediately globally available. All of the magic we see however is still largely magic however, and magic doesn&rsquo;t bode well in any application. The web as a platform for applications is still unbaked and young, and I feel that unless you&rsquo;re forging new territory on the frontier you&rsquo;re probably working with technologies that won&rsquo;t be interesting in a few years time.</p>

<!-- more -->


<h2>The Web as a Software Platform</h2>

<p>HTTP, HTML, JavaScript and CSS have been around for a while now, so why have all the useful standards for building proper web applications (like WebGL, WebSockets, local storage, drag-and-drop and all those other HTML5 goodies) only started coming along recently?</p>

<p>It turns out that for a long time web standards were committee-driven by a group of beard-stroking high-falutin non-visionaries called W3C. I still recall fairly recent times when the latest advances in the web were all about creating HTML that was also standards-conforming XML for some reason (so that perhaps machines could deal with it more easily or something?) and very little practical advancement was being made. (Side note: the same thing seems to be happening with OAuth, which is a morass of unproven ideas and conflicting ideals.)</p>

<p>At some stage however another working group arose called <a href="http://en.wikipedia.org/wiki/WHATWG">WHATWG</a>, formed of people that were actually interested in pushing practical new technologies onto the web, and they pretty much ignored the W3C&rsquo;s direction.</p>

<p>The WHATWG formed in 2004 in response to the stagnating web standards, and in 2007 the W3C finally got on board and standardised HTML5 based on a whole bunch of the WHATWG&rsquo;s tools. They pretty much totally abandoned their whole XHTML thing, which I don&rsquo;t think anyone really regrets.</p>

<p>All of a sudden there have been bursts of innovation on the web, but without a fully baked platform on which to create them. So all these high-level frameworks have temporarily filled the gaps while the HTML spec catches up. In fact, Google&rsquo;s Angular framework (an alternative to Ember.js) has the explicit goal of becoming obsolete when Google manages to get their tools into the standard &ndash; it&rsquo;s a kind of proof-of-concept of Google&rsquo;s vision for client-side application development.</p>

<p>I chose Ember because if you&rsquo;re going with a framework, you might as well go with one that provides abstractions that make sense to you. But I don&rsquo;t have high hopes for it&rsquo;s long-term availability as the web matures, and so feel that there is limited long-term value in becoming some kind of Ember guru.</p>

<h2>My Web App</h2>

<p>The current proof of concept is at <a href="http://seshbot.herokuapp.com.">http://seshbot.herokuapp.com.</a> It still doesn&rsquo;t have the meat in it but it has the authentication, some mobile-friendliness, and sorta models the notions of &lsquo;games&rsquo; and &lsquo;players&rsquo; in games.</p>

<p>I was much surprised to find out that there is not much of a story yet for how to provide a real-time connection between the backend and the Ember application, where updates on the server are actively pushed out to the client. This is probably the next big thing I&rsquo;ll have to do &ndash; create an adapter that connects to the server (probably using server-side events and one of the <a href="http://www.sitepoint.com/streaming-with-rails-4/">Rails4 streaming APIs</a>) and injects incoming updates into the model using the Ember Data API, similar to the <a href="https://github.com/thomasboyt/ember-firebase-adapter">EmberFire Firebase library</a>.</p>

<p>Other than that, the two remaining things I can think of are: making it look like a gaming application (nice rose-wood tabletop look or something?) and adding a few components that I want to have in there like a chat client, a dice area and some kind of card game. This is the nice bit where I get to play around with things, I&rsquo;m looking forward to experimenting with the interactivity side of things, perhaps dragging cards around or having some sound built into it.</p>

<p>I have put this aside however because I don&rsquo;t want to burn out on it. I think it&rsquo;s time to take a break so that I can come back with a fresh set of eyes &ndash; perhaps I&rsquo;ll decide it&rsquo;s not worth continuing at all in lieu of some other app.</p>

<h2>New C++ App</h2>

<p>I&rsquo;ve been wanting to mess around with C++11 for a long time now, and have made a lot of little sample applications that allow me to get a feel for it. I really want to try creating a real application that is:</p>

<ul>
<li>cross platform</li>
<li>uses built-in C++11 stuff like chrono, threads, lambdas, auto etc</li>
<li>provides a few services I&rsquo;ve come to enjoy in newer languages such as dependency containers (if feasible!)</li>
<li>allows me to experiment with GL shaders, which I&rsquo;ve wanted to play with for <em>years</em>.</li>
</ul>


<p>So I spent a few days writing a basic app in <a href="https://qt-project.org/wiki/Category:Tools::QtCreator">QT Creator</a> using <a href="http://www.cmake.org/">CMake</a> as the build system. There were a few hurdles but it didn&rsquo;t take long to get up and running. Because I&rsquo;m limiting myself to core C++, boost and a couple of cross-platform libraries (<a href="http://www.sfml-dev.org/">SFML</a> for graphics and <a href="http://eigen.tuxfamily.org/index.php?title=Main_Page">Eigen</a> for linear algebra stuff) it&rsquo;s still pretty versatile. And because I&rsquo;m using CMake I&rsquo;ll be able to use Visual Studio to develop in Windows and QT Creator or XCode or whatever I want in OSX. I&rsquo;ll try to stick with QT Creator where possible though for consistency.</p>

<p><img class="center" src="http://seshbot.com/images/upload/2014-02-03-qtcreator.png" title="&#34;QT Creator actually looks pretty nice&#34;" alt="&#34;QT Creator actually looks pretty nice&#34;"></p>

<p>I am a bit worried about Windows compatability &ndash; Visual C++ has always lagged behind in standards conformance, but they have picked up their pace somewhat in the recent future. I am avoiding some of the more esoteric stuff however, such as variadic templates, because of VC++.</p>

<p>I would also really like to try messing around with QML &ndash; Qt&rsquo;s DSL for writing GUI applications. It reminds me of WPF only in a much cleaner, less hacky way, with JavaScript capabilities built straight into it. Ideally I will figure out a way to use Qt Quick/QML seamlessly with the OpenGL stuff provided by SFML, though I am less optimistic about that. Previous experience tells me that you don&rsquo;t want to be re-creating GUI widget libraries because layout management is a complete bitch, but I think QML is still a bit young to work in arbitrary circumstances.</p>

<h2>Blogging</h2>

<p>I found it very difficult to blog about my experiences with Ember and Rails. There is a lot of stuff out there covering the same stuff I would cover, only terribly out of date. This made me feel that my posts too would just become so much flotsam on a sea of irrelevant minutiae.</p>

<p>The main value I was really getting though was as a reference for myself so I could close some of my browser tabs without worrying that I wouldn&rsquo;t be able to find that one piece of information again, and also so that I could distill my thoughts on something before putting it aside.</p>

<p>I have about 3 unpublished posts on my experience over the last few weeks &ndash; I&rsquo;ll probably put them together under one post about Ember development, but not for a little while now I&rsquo;m guessing.</p>

<p>I am much more certain of my opinion on C++ related matters, so I imagine that there will be a few long rants in that general direction coming up.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The best way for programmers to interview programmers]]></title>
    <link href="http://seshbot.com/blog/2014/01/23/the-best-way-for-programmers-to-interview-programmers/"/>
    <updated>2014-01-23T20:56:52+00:00</updated>
    <id>http://seshbot.com/blog/2014/01/23/the-best-way-for-programmers-to-interview-programmers</id>
    <content type="html"><![CDATA[<p><strong>Every programmer should know how to give technical interviews.</strong> Although you will rarely be judged on your interviewing abilities, it is definitely in your best interest to help ensure your company is hiring effective programmers. If you manage to surround yourself with great programmers you&rsquo;ll foster a much better environment in which you can become a great programmer yourself. If you find yourself surrounded by programmers you consider sub-par you&rsquo;ll end up supporting their crappy software.</p>

<p><span class='pullquote-right' data-pullquote='the best way to find great programmers is by giving them some control over the interview topic, and then going deep into a few questions instead of broad across many topics'>
I have been interviewing programmers for many years and reckon the best way to find great programmers is by giving them some control over the interview topic, and then going deep into a few questions instead of broad across many topics. This takes a lot of guts however &ndash; it requires the interviewer to pay attention, and ideally (though not necessarily) to have a fairly broad knowledge base themselves.
</span></p>

<p>I believe this advice applies to all programmers &ndash; of course interviewing is rarely in your job description, but it is definitely in your best interest to make sure interviews get done well at your company. Unfortunately most companies will allow anyone to interview and won&rsquo;t have a good way to tell that they&rsquo;re not doing it well, ultimately damaging the work environment.</p>

<!-- more -->


<h2>The mediocre way</h2>

<p>Typically interviewers will be given a list of questions to ask and some criteria by which to judge the answers to these questions. Perhaps the interview will follow some format of scripted grilling, perhaps a practical section, and some kind of open two-way forum. Following a script is supposed to allow the candidates to be compared fairly on a level playing field. The practical section might consist of taking apart a printed code sample or even writing some code, and the forum provides the candidate the opportunity to explain their situation and determine if they actually want to work at the company themselves.</p>

<p>This has a lot of problems however:</p>

<ul>
<li>if the interviewer completely controls the questions the candidate may come across poorly because they don&rsquo;t happen to have experience in the specific fields chosen, or because he or she is just very nervous</li>
<li>it promotes a one-size-fits-all mentality, which will lead to a homogenous work environment</li>
<li>it is too easy for the interviewer to just phone it in without truly probing for deeper knowledge. In fact this becomes more likely as the interviewer becomes bored of the questions</li>
<li>it is too easy for candidates to blag &ndash; some people can sound like experts when all they have is brash confidence and a few keywords. Plus, recruitment companies often coach candidates on what questions might be asked so those keywords are likely to be there</li>
<li>quiz-type interviews often fail to test higher-level proficiencies, such as communicating architecture and design information</li>
</ul>


<p>I think it&rsquo;s well worth throwing away the &lsquo;standardised&rsquo; approach to testing technical capabilities. There is too much risk of false negatives <em>and</em> false positives along this approach &ndash; a poor programmer may have been well coached, and a good programmer might have an unfortunate gap right where your questions probe (surely I could have worded that better&hellip;)</p>

<h2>The Seshbot way</h2>

<p>While it is important to cover several bases in an interview, the most important question I always ask is <strong>&lsquo;what was the most recent interesting project in which you were heavily involved?&rsquo;</strong> I almost always spend most of the interview going deep into a few questions that branch off the answers to this question.</p>

<p><span class='pullquote-right' data-pullquote='If a programmer can&#8217;t talk throughly about a topic about which they chose themselves and are purportedly very interested, they probably aren&#8217;t right for the job'>
This question puts the ball firmly in the candidate&rsquo;s court, and largely eliminates the problems outlined above. If a programmer can&rsquo;t talk throughly about a topic about which they chose themselves and are purportedly very interested, they probably aren&rsquo;t right for the job (at whatever company I&rsquo;m working for anyway!)
</span></p>

<p>Once the candidate has explained the project, the interviewer can then challenge the details of that project as a way of testing the candidate&rsquo;s knowledge of that system and the reasoning behind its design. The types of question would vary depending on the workplace, but at my last job for example I probably would have asked:</p>

<ul>
<li><em>architecture:</em> please outline for me (ideally on a whiteboard or paper) how the whole system hangs together. I might expect the candidate to talk about the systems involved, data flows, security considerations, or data storage and integrity for example.</li>
<li><em>design quality attributes and compromises:</em> how does this system provide, or how would you adjust this architecture to provide, various quality attributes (high availability, reliability, scalability, performance, security)? What compromises would these changes entail?</li>
<li><em>design:</em> if I were a new developer working on this team, how would you describe the design of this system to me?</li>
<li><em>specifics:</em> I also spend a lot of time asking &lsquo;what is the purpose of that service/component/class&rsquo;</li>
</ul>


<p><span style="color: green; font-weight: bold;">Pros:</span> This addresses all of the problems I outlined with the more traditional approach:</p>

<ul>
<li>the candidate is talking about something they are presumably proud of and know inside-out. If they can&rsquo;t talk happily on this subject they won&rsquo;t be able to talk about any subject</li>
<li>the candidate is more able to show you what their particular skill set entails, and what they believe is their forte without them awkwardly spelling it out (through stupid &lsquo;what are your strengths and weaknesses&rsquo; questions)</li>
<li>the interviewer must be engaged in the process in order to ask relevant questions. It is in fact a great way to keep the interviewing process more interesting &ndash; and even educational &ndash; for the interviewer</li>
<li>because it is a &lsquo;deep&rsquo; and detailed question, it is very difficult to blag. Someone might be able to re-draw arcitectural diagrams they had to become familiar with in the past, but they would still need to know <em>why</em> the system was configured that way to answer the questions</li>
<li>the test focuses on communication of ideas, which I believe is the most important skill for a team member to have. You may or may not agree with this, but you certainly want to have tested it</li>
</ul>


<p><span style="color: red; font-weight: bold;">Cons:</span> There are some caveats however:</p>

<ul>
<li>do not let the candidate run the interview. It can be too easy to tackle a question by diverting into another topic &ndash; make sure that the candidate answers the questions you ask to your satisfaction</li>
<li>keep an eye on the time, because although you want to go deep on few questions, there&rsquo;s no point going deeper into a topic once the candidate has demonstrated their knowledge in that area</li>
<li>it can be difficult to recall what you discussed later when you&rsquo;re trying to make a decision about the candidate. Take notes constantly, and summarise the interview in an email directly after you finish it</li>
<li>if the candidate chooses to talk about technologies with which you&rsquo;re not very familiar yourself you&rsquo;ll be forced to ask largely high-level questions. This is not terrible as I believe you can still figure out if they know their stuff, but you might end up having to take their word on a few things</li>
</ul>


<h2>How to measure success</h2>

<p>Other than retention rates I am not certain of how to measure if your technique is successful, but in my experience most prospective programmers in the job market are not very good (something like 1-in-10), and so if you&rsquo;re hiring a high percentage of applicants you&rsquo;re probably letting in a few duds.</p>

<p>This might seem depressing and I feel bad about saying that, but this is my blog and I want to put my honest opinion up here. Take it as you will. <a href="http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html">Others agree with me</a> however.</p>

<p>Because of this it is a very good idea to have a basic pre-screening done before the proper interview. It should be very simple and not take too long &ndash; a simple test should be sufficient to weed out most of the poor programmers, and you need to remain respectful of the candidate&rsquo;s time as they are interviewing <em>you</em> as well.</p>

<h2>What about live coding?</h2>

<p>Here&rsquo;s an anecdote: once while applying for a job at a large investment bank I was given an almost purely practical interview. On arriving I sat down with the lead developer and chatted for a bit before heading into the programming room to do some pair programming. Sweet right?</p>

<p>Anyway I sat at this Windows box with Visual Studio on it (this was for a largely .Net job) and was given the basic <a href="http://c2.com/cgi/wiki?FizzBuzzTest">fizzbuzz test</a>. There is a lot of controversy around this interview technique but I actually enjoy practical questions so didn&rsquo;t have a problem with the idea. The interview was a shambles however, and although I did well I count it as a terrible interview that did not serve its purpose at all.</p>

<p>First I had trouble with their development environment. The machines at this bank were ridiculously slow &ndash; they were running a special (presumably super-secure) build of Windows 95 that was by now literally something like 13 years old, and they couldn&rsquo;t change because it would be too costly to get a special build of a more modern Windows. So we sat there for a long time waiting to get all the software up and running, and every button click seemed to require the human genome to be re-calculated.</p>

<p>The next problem was that making sure that the interviewer and I were on the same page took way too long. I did the fizz-buzz program, and decided to show him how I would do it declaratively (with LINQ) so we could talk about the benefits of declarative programming. Of course if I were interviewing someone I would want them to solve the problem as simply as possible first, then make it more complicated later. I know through experience that many candidates think that they are expected to say things like <em>I would never start programming without a firm set of requirements!</em> or some other approach showing that they know about all areas of software development.</p>

<p>Turns out this guy wanted me to demonstrate some test-driven development, and so was expecting me to have started by writing tests. So OK, I figured I&rsquo;d download <a href="http://www.specflow.org/">SpecFlow</a> because I had used it successfully recently and really liked it. But no, this is a bank I&rsquo;m sitting in so we can&rsquo;t just download stuff &ndash; things have to go through a days-long process of scanning and justification before new software is installed. So I ask what they use and he mentioned some package or other. So I had to read the docs on that, and we had trouble actually running it on this machine in the end because we had to configure some directories in Visual Studio or something, and much more time was wasted.</p>

<p>I&rsquo;m not saying it can&rsquo;t work, but in my opinion live coding is fraught with dangers. A much better alternative is to browse the applicant&rsquo;s source code online for projects they have worked on. Realistically though the number of people I have interviewed that had  online code I could evaluate was exactly 1 (I did hire him though!)</p>

<h2>General interviewing advice</h2>

<p>Obviously interviewing is a difficult thing to do well. You have a small amount of time to decide whether to commit your company to filling a permanent seat on your team, which is a <em>huge</em> deal. Probably practice is the only thing that helps mitigate this (and the Seshbot technique of course) but here&rsquo;s a few other pointers that come to mind:</p>

<ul>
<li><em>take notes constantly!</em><br />One of the problems you can encounter with a less scripted interview is that when summarising how the interview went, it can be difficult to recount all the things you talked about. I tend to fill a couple of pages in my notebook with bullet-pointed scribbles during each interview</li>
<li><em>know when you know</em><br />The best interview I ever gave was a really nice guy called Phil. Only a few minutes into the interview I realised that he had probably handled my questions better than I could have. So I just sat back and told him &lsquo;I don&rsquo;t think we really need to go any further&rsquo;, then I walked out and asked HR to give him an offer on the spot. I was always happy that I did that.</li>
<li><em>do basic screening</em><br />If no screening has been performed it is worthwhile asking a couple of basic language-specific technical questions to make sure you&rsquo;re not wasting your time</li>
<li><em>the interviewer doesn&rsquo;t need to know the answer to all the questions he or she asks</em><br />You can choose to pretend that you really know and are just testing their knowledge, but if I don&rsquo;t know something I usually don&rsquo;t mind asking questions in an outright manner &ndash; there&rsquo;s no need to maintain a facade of superiority and being honest helps promote a candid atmosphere</li>
<li><em>have a standard approach to summarising the interview</em><br />At the end of the day you need to provide some quantifiable metric by which to decide who to hire. Plus HR and the recruiter usually require some specific information. At my last place HR was happy with just the name, date, my decision/recommendation, and justification for that decision</li>
<li><em>if you&rsquo;re doing a phone interview (unfortunate!) follow a script for the scaffolding for the interview</em><br />This keeps you from spending too much time on the plesantries and keeps you from waffling on</li>
<li><em>I usually like to ask if there&rsquo;s any good books a person would recommend, and ask what they got from it</em><br />It may be curmudgeonly of me but I don&rsquo;t think a person can learn fundamentals very well from Stack Overflow alone</li>
<li><em>Work with your recruiter, but assume they are coaching the candidates</em><br />A cool side-effect of this techinique is that it doesn&rsquo;t matter if candidates are coached &ndash; I told our recruitment agencies to feel free sharing information about our interviews with candidates</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Client-side authentication with ember and rails]]></title>
    <link href="http://seshbot.com/blog/2014/01/22/client-side-authentication-with-ember-and-rails/"/>
    <updated>2014-01-22T00:30:27+00:00</updated>
    <id>http://seshbot.com/blog/2014/01/22/client-side-authentication-with-ember-and-rails</id>
    <content type="html"><![CDATA[<p><em>This post follows on from the previous post <a href="http://seshbot.com/blog/2014/01/15/creating-a-rails-plus-ember-app-from-scratch/">creating and deploying a rails + ember app from scratch</a>. In that post I created a basic ember application being served from rails. Here I&rsquo;ll be adding user authentication to the application I created using the &lsquo;edge template&rsquo; option I discussed, which uses the &lsquo;ember-rails&rsquo; gem to establish the basic connectivity.</em></p>

<p>I do not want to implement authentication and authorization myself. It is tricky to get right and tends to cause huge damage when it goes wrong in production.</p>

<p>So I have spent at least three full days looking at various solutions I can build into my simple Ember/Rails application and spent a lot of time experimenting.</p>

<p>This post describes my current understanding of authentication for web applications, and the approach I used to implement a basic authentication system I put up on heroku at <a href="http://seshbot.herokuapp.com">http://seshbot.herokuapp.com</a></p>

<p>If you want to see the source code, have a look at <a href="https://github.com/seshbot/new-ember-rails-app">https://github.com/seshbot/new-ember-rails-app</a></p>

<p><img class="center" src="http://seshbot.com/images/upload/2014-01-22-seshbot-login.png" title="&#34;Oh jeez I already forgot my password&#34;" alt="&#34;Oh jeez I already forgot my password&#34;"></p>

<p><em>NOTE: this is very text-heavy because after three full days I decided not to spend too long on this blog post. Therefore there are no images at this time. I may update it later to have some nice UML or screenshots, but that time is not now.</em></p>

<!-- more -->


<h2>Learning the basic concepts</h2>

<p>I found a few very detailed introductions to client-side authentication with ember which helped me through all stages of implementation of my system. I highly recommending going through the following resources and comparing the different approaches&#8217; overlaps and differences. I also got a lot of value out of re-visiting them after I finished implementing my own solution, because it made me think about some of the trade offs I had made.</p>

<h3>Watch these awesome client-side suthentication videos</h3>

<p><a href="http://www.embercasts.com/">http://www.embercasts.com/</a> covers the client-side concepts of authentication with Ember in <a href="http://www.embercasts.com/episodes/client-side-authentication-part-1">part 1</a> and <a href="http://www.embercasts.com/episodes/client-side-authentication-part-2">part 2</a> of their &lsquo;Client Side Authentication&rsquo; videos. Specifically:</p>

<ul>
<li>client token authentication concepts</li>
<li>sending auth request to the server and saving the token (in a &lsquo;login&rsquo; controller)</li>
<li>setting up controllers</li>
<li>catching &lsquo;unauthorised&rsquo; error responses and redirecting to login pages</li>
<li>keeping a sane workflow so the login transitions the user back to their original page</li>
<li>storing the auth token in local storage so page refresh doesn&rsquo;t reset it <em>(note: I used cookies instead of local storage)</em></li>
<li>preventing the unauthorized server request if client knows it doesn&rsquo;t yet have a token</li>
</ul>


<p>This doesn&rsquo;t cover the server side, or anything to do with Rails or any other authenticating server specifically &ndash; he used a home-grown demonstration Node.js server for the demonstration. Also doesn&rsquo;t specifically cover authorization (I can see users but can&rsquo;t see their emails for example.) The ember front-end polish in there is all nice though, and I found it very helpful to revisit these videos after I had a basic system in place, in order to add nice error messages and improving the &lsquo;view page/redirect to login/return to page&rsquo; workflow.</p>

<h3>Read about SimpLabs&#8217; experience making Ember.SimpleAuth</h3>

<p>SimpLabs wrote a <a href="http://log.simplabs.com/post/57702291669/better-authentication-in-ember-js">blog post</a> detailing their experiences getting ember authentication to work sensibly and according to the various standards.</p>

<p>They wrapped this functionality up in an ember plugin called <a href="https://github.com/simplabs/ember-simple-auth">Ember.SimpleAuth</a> (and wrote about <a href="http://log.simplabs.com/post/63565686488/ember-simpleauth">how to use it</a>). There&rsquo;s even a <a href="https://github.com/ugisozols/ember-simple-auth-rails-demo">demo rails app</a> that uses it.</p>

<h3>Follow the very detailed ember-auth + devise tutorial</h3>

<p>Someone else has written a rails plugin called <a href="https://github.com/heartsentwined/ember-auth-rails">ember-auth</a> that presumably takes care of both sides (rails server and ember client) of the problem. The true value for learning is in the <a href="https://github.com/heartsentwined/ember-auth-rails-demo/wiki">demo application&rsquo;s tutorial</a> however, which covers:</p>

<ul>
<li>setting up your rails app</li>
<li>setting up devise for rails</li>
<li>modeling the server entities and API endpoints</li>
<li>writing tests for all of the above</li>
<li>setting up your ember app</li>
<li>creating front-end UIs for authentication with ember</li>
</ul>


<p>It also has a separate page that goes into <a href="https://github.com/heartsentwined/ember-auth/wiki/Security">security concerns</a> that highlights a few best practices to keep in mind that frameworks will probably not implement for you:</p>

<ul>
<li>always use https</li>
<li>authentication checks in the client are a convenience only and should never replace auth validation in the server</li>
<li>do not use the &lsquo;current user&rsquo; ID when retrieving priveleged resources (i.e., don&rsquo;t use client-provided data when performing authorization related functionality)</li>
<li>never store any credential information in cookies &ndash; generally just store the server token, which is expendable</li>
<li>do not rely on the client framework alone to clear caches etc when logging out &ndash; ember data for example doesn&rsquo;t offer a way to clear the data store</li>
</ul>


<h3>A few other side-notes while we&rsquo;re talking theoretical</h3>

<p><a href="https://github.com/kristianmandrup/ember-beercan">ember-beercan</a> seems to explore a different approach that I don&rsquo;t really like, but does have some interesting information on using rails and devise on the server side that I might look at later.</p>

<p>A general concern to keep in mind is that for security reasons if the client-side application is not running on the same url/port as the server application the browser might refuse to let them communicate. In this case apparently you should add Rack::Cors to your app (haven&rsquo;t looked into that yet.)</p>

<p>There is also a lot of discussion around whether the client side should be involved at all in the auth negotiation, and perhaps leaving that up to a separate set of pages served by the server, and the server refuse access to the app at all until that time. This makes the client app much simpler as it can always assume that the user is authenticated (see stack overflow questions <a href="http://stackoverflow.com/questions/19401087/ember-js-how-to-get-access-to-store-from-app-object">how to access store from app object</a>, <a href="http://stackoverflow.com/questions/19414393/ember-js-session-cookie-based-authentication-with-rails-and-devise">session cookie based auth with rails and devise</a>.)</p>

<p>When looking into server-side authentication information I found <a href="http://www.robertsosinski.com/2008/02/23/simple-and-restful-authentication-for-ruby-on-rails/">this description of a simple hand-rolled solution</a> to be quite helpful, because it is quite short and covers only the rails side.</p>

<h2>What we want from an auth system</h2>

<p>A minimal authentication system should provide:</p>

<ul>
<li><em>create user</em>: an interface for creating users</li>
<li><em>login user</em>: an interface for authenticating a user based on username or email address and password</li>
<li>error handling: the interface should provide nice handling for errors (if there&rsquo;s an error message it should be printed nicely)</li>
<li>allow session to persist for some amount of time so the user doesn&rsquo;t have to log in every time they come back</li>
</ul>


<p>In addition however, we want the system to provide authrisation:</p>

<ul>
<li>separation of user roles (administrators, regular users, guests/unauthenticated users)</li>
<li>authorisation of access to server resources &ndash; the server should send a <em>401 unauthorized</em> response to unauthorised requests</li>
<li>sensible UI workflow for logging in and unauthorised access attempts

<ul>
<li>when a server responds with a 401 response, the UI should take the user to the login screen</li>
<li>after login, the user should be returned to a sensible page, possibly based on what they were trying to achieve before being redirected to the login page</li>
</ul>
</li>
</ul>


<p>Of course the system has to follow industry practices and where possible use well-established technologies to offload all the dangerous stuff like dealing with passwords and hashing.</p>

<h2>Building an Authenticating app</h2>

<p>I spent a <em>lot</em> of time experimenting with the various options, generally with little success. The executive summary is that most high-level plugins are generally not production ready, or don&rsquo;t work well together with the latest versions of other parts of the architecture. I ended up following a great tutorial on how to hand-roll your own authentication framework in Ember and Rails, using only a single bcrypt Rails gem for the password stuff.</p>

<h3>Failed attempt 1: ember-auth-easy Rails gem</h3>

<p>I was quite hopeful when I found <a href="https://github.com/mharris717/ember-auth-easy">ember-auth-easy</a> which was made to work with <a href="https://github.com/mharris717/ember_auth_rails">ember-auth-rails</a> to provide a full Rails backend/Ember frontend token based authentication solution.</p>

<p>Unfortunately as with so many things in Rails these days, lots of stuff doesn&rsquo;t work with lots of other stuff if you&rsquo;re trying to use the latest versions of things. The devise rails integration was found to be lacking for some reason and there was some mass change involved that broke backwards compatability, and many slightly older gems don&rsquo;t seem to work well anymore. I think it was made to work with Rails 3 as well (I&rsquo;m on Rails 4.)</p>

<p>In addition, there&rsquo;s a whole lot of gems up there and I&rsquo;m starting to get pissed off at having to learn 5 new buzzword-riddled technologies for every one new one I learn.</p>

<p>Before I decided to abandon it I created the following steps (I write it here in case I decide to go back to it later)</p>

<figure class='code'><figcaption><span>Rails Trying to install ember-auth-rails on Rails</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>vim Gemfile
</span><span class='line'><span class="c"># add the following: # gem &#39;ember_auth_rails&#39;, :git =&gt; git://github.com/seshbot/ember_auth_rails.git</span>
</span><span class='line'><span class="c"># gem &#39;ember-data-source&#39;, &#39;&gt;= 1.0.0.beta.3&#39;, &#39;&lt; 2.0&#39; # ember-data not yet out of beta</span>
</span><span class='line'><span class="c"># gem &#39;emblem-rails&#39;, &#39;~&gt; 0.1&#39; # easier to write templates</span>
</span><span class='line'><span class="c"># </span>
</span><span class='line'><span class="c"># gem &#39;ember-auth-rails&#39;, &#39;~&gt; 5.0&#39; # client-side authentication</span>
</span><span class='line'><span class="c"># gem &#39;ember-auth-request-jquery-rails&#39;, &#39;~&gt; 1.0&#39; # auth requests via jQuery.ajax</span>
</span><span class='line'><span class="c"># gem &#39;ember-auth-response-json-rails&#39;, &#39;~&gt; 1.0&#39; # responses in json</span>
</span><span class='line'><span class="c"># gem &#39;ember-auth-strategy-token-rails&#39;, &#39;~&gt; 1.0&#39; # token authentication</span>
</span><span class='line'><span class="c"># gem &#39;ember-auth-session-cookie-rails&#39;, &#39;~&gt; 1.0&#39; # use cookies</span>
</span><span class='line'><span class="c"># gem &#39;ember-auth-module-ember_data-rails&#39;, &#39;~&gt; 1.0&#39; # ember-data integration</span>
</span><span class='line'><span class="c">#</span>
</span><span class='line'><span class="c"># gem &#39;devise&#39;</span>
</span><span class='line'>
</span><span class='line'>vim config/application.rb
</span><span class='line'><span class="c"># add &quot;require &#39;devise&#39;&quot; to bottom</span>
</span><span class='line'>
</span><span class='line'>bundle install <span class="c"># install new gems</span>
</span><span class='line'>bundle <span class="nb">exec </span>rake ember_auth_rails_engine:install:migrations
</span><span class='line'>rails g devise:install
</span><span class='line'>bundle <span class="nb">exec </span>rake db:migrate
</span></code></pre></td></tr></table></div></figure>


<h3>So I hand-rolled my solution</h3>

<p>I eventually found a great post called <a href="http://coderberry.me/blog/2013/07/08/authentication-with-emberjs-part-1/">authentication with ember.js</a> by a dude who seems to really know what he&rsquo;s talking about. It seems to be a culmination of several weeks of work, and a collaboration with a few other developers. It also includes a link to <a href="https://github.com/rails-api/rails-api">Rails::API</a>, which I really want to use in the future.</p>

<p>The Rails server in the tutorial provides an API that allows creation of a new user, authenticates a user/password combination, and provides admin information to authenticated users. The rails implementation code consists of:</p>

<ul>
<li>router exposes a <em>user</em> resource (for creation and reading) and a <em>session creation</em> post route</li>
<li><code>user</code> model is composed of multiple <code>api-key</code>s &ndash; when the model is loaded, it will create a new api-key if there are no remaining active session keys

<ul>
<li>the <code>user</code> model also invokes the <a href="http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password">has_secure_password</a> security method that provides an <em>authenticate</em> method (this is built into the Rails framework and uses the bcrypt gem)</li>
</ul>
</li>
<li><code>api-key</code> model is composed of an <em>access token</em> and an <em>exipiry time</em></li>
<li>all controllers have access to an <em>ensure_authenticated_user</em> function that searches for an active API session key that is associated with the current <em>HTTP_AUTHORIZATION</em> HTTP header</li>
<li>the <code>user</code> controller allows an unauthenticated client to show or create a new user record, but requires an authenticated session to show all users</li>
<li>the <code>session</code> controller (invoked via HTTP <em>post</em> from the <em>session creation</em> route) provides <em>login</em> functionality (session creation)

<ul>
<li>first it looks up a <code>user</code> associated with the given username or email</li>
<li>it then invokes the user object&rsquo;s <em>authenticate</em> method with the given password</li>
<li>if either of these steps fail a HTTP 401 response is returned, otherwise a 201 response with the user&rsquo;s <em>session API key</em></li>
</ul>
</li>
</ul>


<p>In the implementation provided in this system, the notion of a <em>session</em> is not actually stored anywhere in the server &ndash; it is merely an access point to a secure token associated with an <code>api-key</code> the user has (a new <code>api-key</code> is created if the session creation request is valid but no current active session key is available.)</p>

<p>An interesting thing I noticed while re-reading the <a href="http://log.simplabs.com/post/57702291669/better-authentication-in-ember-js">SimpLabs blog post</a> I mentioned previously is that this scheme does not allow a user to delete their <em>access token</em> from the server at all. Logging out just means clearing the token cookie &ndash; if the user re-authenticates the server will just dish them out the same token. If I extended the logout action to clear the token from the server however, all of the user&rsquo;s sessions would become invalidated, so I&rsquo;d have to change the scheme to create new access tokens for every separate login. I&rsquo;ll leave it as is for now and have a think about it.</p>

<p>As with all other ember things, the instructions were written with a prior version of ember and so don&rsquo;t work anymore. I had a bit of fun getting it working but a couple of things to keep in mind:</p>

<ul>
<li>use latest version of bcrypt</li>
<li>use &lsquo;jquery-cookie-rails&rsquo; gem</li>
<li>demo uses the <a href="https://github.com/rails-api/rails-api">Rails::API</a> gem instead of creating a whole Rails application with views etc. Because I previously used the <em>ember-rails</em> gem I didn&rsquo;t do this</li>
<li>retrieving data from the store is done differently now &ndash; see the ember docs</li>
<li>accessing the store from anything other than a router can be difficult. I get it with this hackery: <code>var store = GameTableServer.__container__.lookup('store:main')</code> (see <a href="http://stackoverflow.com/questions/19401087/ember-js-how-to-get-access-to-store-from-app-object">http://stackoverflow.com/questions/19401087/ember-js-how-to-get-access-to-store-from-app-object</a>)

<ul>
<li>TRICK! another problem &ndash; store returns an async promise, so you need to wait for that! god dammit. <code>var self = this; store.get(...).then(function(user) { self.set('apiKey', ...)})</code></li>
</ul>
</li>
<li>if something doesn&rsquo;t seem to be working, keep an eye on your browser&rsquo;s javascript console, net traffic and your rails logs (in heroku you can do this with <code>heroku logs</code> or something)</li>
</ul>


<p>You can have a look at the app as it currently stands (as of Jan 2014) on <a href="http://seshbot.herokuapp.com">seshbot.herokuapp.com</a>. If you&rsquo;re reading this much after Jan 2014 however it probably wont be there any longer.</p>

<h3>Alternative: Use &lsquo;devise&rsquo; gem directly</h3>

<p><a href="https://github.com/plataformatec/devise">Devise</a> seems like a very mature and comprehensive rails &lsquo;authentication solution&rsquo; that seems to handle a lot of authentication related problems out of the box in a very configurable way. It takes care of a lot of stuff like sending password reset emails, locking accounts after failed validations, connecting to various auth providers, and lots of other stuff. I will probably end up moving towards it if I ever make an app that warrants that kind of thoroughness.</p>

<p>I found a pretty useful comment on stack overflow that <a href="http://stackoverflow.com/questions/16513066/devise-with-rails-4">details how to get it running quickly with Rails 4</a> &ndash; not sure if thats more useful than the docs.</p>

<p>I started following <a href="https://github.com/heartsentwined/ember-auth-rails-demo/wiki">this very detailed tutorial</a> on using rails + ember + devise and found it very useful. Again, I couldn&rsquo;t get things working well together and had to abandon it. If I were to revisit I might also consider following these <a href="http://avitevet.blogspot.com.es/2012/11/ember-rails-devise-token-authentication.html">very detailed instructions on devise + ember</a>.</p>

<h3>Alternative: Use SimpleAuth for client-side stuff</h3>

<p>SimpLabs&#8217; <a href="https://github.com/simplabs/ember-simple-auth">SimpleAuth</a> (discussed in <a href="http://log.simplabs.com/post/63565686488/ember-simpleauth">this SimpLabs blog</a> and mentioned previously in this post) looks pretty cool, and is recently very active. It is still v0.1.0 so I&rsquo;d prefer to keep away from it for now, but if I wanted OAuth integration (to have a &lsquo;login with Facebook&rsquo; or whatever) I might look into using this for the client-side code.</p>

<h2>My current conclusion</h2>

<p>It is laughable that Ember and Rails are in such states of flux that it was easier to hand-roll a solution (although based on a very detailed set of instructions!) than it was to use existing gems and plugins. I hope that changes in the future.</p>

<p>If I ever decide I want a more complex auth solution using rails and ember, I&rsquo;d probably look at using devise for the Rails side and SimpleAuth for the ember side. I would expect a lot of heart-ache along the way though.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Creating and deploying a Rails + Ember app]]></title>
    <link href="http://seshbot.com/blog/2014/01/15/creating-a-rails-plus-ember-app-from-scratch/"/>
    <updated>2014-01-15T08:54:16+00:00</updated>
    <id>http://seshbot.com/blog/2014/01/15/creating-a-rails-plus-ember-app-from-scratch</id>
    <content type="html"><![CDATA[<p>Today I decided to wield my new Rails and Ember knowledge and&hellip; look into yet another new technology. I thought it would be helpful to have an online app to demonstrate the fruits of my labours, so am deploying a new app to <strong><a href="http://heroku.com">Heroku</a></strong>.</p>

<p>Heroku is an &lsquo;application platform&rsquo; in the cloud, meaning that you can push certain kinds of apps (written in Ruby, Python, Java and Node.js) and it will ensure all the correct infrastructure is in place. When you sign up you get to host one app for free so it&rsquo;s easy to try out.</p>

<p>Later I will probably move to <a href="http://aws.amazon.com">Amazon Web Services</a>, which provides a basic virtual machine in the cloud that you can do anything with. This will allow me to host multiple applications without having to worry about paying money. Heroku <em>does</em> offer some pretty nice scaling, monitoring and deployment tools though (the admin panel literally has a slider to allow you to spin up new application instances.)</p>

<p>This post shows how I went through all steps, including setting up the PostgreSQL database on OSX, creating a skeleton Rails app, and deploying to Heroku. It is a culmination of having gone through several sources:</p>

<ul>
<li>much was taken from this useful step-by-step &lsquo;<a href="http://www.devmynd.com/blog/2013-3-rails-ember-js">Rails + Ember blog post</a>&rsquo; and this <a href="http://www.devmynd.com/blog/2013-10-live-on-the-edge-with-rails-ember-js">follow up post</a> that incorporates changes for newer versions of the frameworks.</li>
<li>when I got to the part involving installing the &lsquo;ember-rails&rsquo; gem, I found that the <a href="https://github.com/emberjs/ember-rails">ember-rails documentation</a> was pretty useful.</li>
<li>some of the Heroku stuff came from the <a href="https://www.codeschool.com/code_tv/heroku">Heroku Code School lesson</a> summary.</li>
</ul>


<!-- more -->


<h2>Choosing a database</h2>

<p>By default Rails will use sqlite3 for its database, and this isn&rsquo;t by default available in Heroku. As I&rsquo;m going to have to do some configuration anyway, I might as well choose a nicer database.</p>

<p>I was deciding between MongoDb and PostgreSQL. MongoDb offers flexibility when it comes to managing file assets in your database, while PostgreSQL is much more well established in existing hosting infrastructures (AWS and Heroku), so can make initial deployment much simpler. Mongo is also more amenable to schema changes because it&rsquo;s a NoSQL schema-less document database, but I think Rails is supposed to make schema changes easy anyway with the various <code>db:</code> commands.</p>

<p>As Heroku comes with PostgreSQL support out of the box, for now I&rsquo;ll go with Postgres. I&rsquo;m as yet not very familiar with Heroku and want to make things easier on myself.</p>

<p>The following installation instructions came from a blog entry on <a href="http://ricochen.wordpress.com/2012/07/20/install-postgres-on-mac-os-x-lion-with-homebrew-howto/">installing PostgreSQL on OSX with HomeBrew</a>:</p>

<figure class='code'><figcaption><span>Installing PostgreSQL on  OSX</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="c"># easiest if you have homebrew installed</span>
</span><span class='line'>brew install postgresql
</span><span class='line'>
</span><span class='line'><span class="c"># ensure it starts up when your machine starts</span>
</span><span class='line'>ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
</span><span class='line'>launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
</span><span class='line'>
</span><span class='line'><span class="c"># ensure you don&#39;t accidentally run the older version</span>
</span><span class='line'><span class="nb">echo</span> <span class="s1">&#39;export PATH=/usr/local/bin:$PATH&#39;</span> &gt;&gt; ~/.bash_profile <span class="o">&amp;&amp;</span> . ~/.bash_profile
</span><span class='line'>
</span><span class='line'><span class="c"># create a database user for the application to use</span>
</span><span class='line'><span class="c"># (alternatively you should be able to run &#39;createuser -d myapp&#39;)</span>
</span><span class='line'>psql postgres <span class="sb">`</span>whoami<span class="sb">`</span>
</span><span class='line'>create role myapp with CREATEDB login password <span class="s1">&#39;password1&#39;</span>;
</span></code></pre></td></tr></table></div></figure>


<p><em>Notes:</em></p>

<ul>
<li><em>the <code>createuser</code> command can replace the <code>psql</code> command stuff: <code>createuser -d myapp</code></em></li>
<li><em>if the DB username is different to the application name (below) you&rsquo;ll need to change the rails configuration later so it knows which username to use</em></li>
<li><em>I assume Heroku doesn&rsquo;t require you to manage the database at all</em></li>
</ul>


<h2>Creating a simple Rails app</h2>

<p>Creating a Rails app is really simple <em>once you know the commands</em>. So from scratch, if you include all the learning involved behind each command, it&rsquo;s actually not very simple. But these steps make it simple for me.</p>

<p>TIPS: I read somewhere that you should always run <code>bundle exec</code> before running a rails command to ensure that you&rsquo;re only working with gems in your Gemfile. Technically you could run all the commands below without prepending <code>bundle exec</code> however.</p>

<figure class='code'><figcaption><span>Creating the rails application framework</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>rails new myapp --database<span class="o">=</span>postgresql
</span><span class='line'><span class="nb">cd </span>myapp
</span><span class='line'>vim config/database.yml <span class="c"># set the database username and password, and on OSX un-comment the &#39;local&#39; setting</span>
</span><span class='line'>bundle <span class="nb">exec </span>rake db:create    <span class="c"># create databases</span>
</span><span class='line'>bundle <span class="nb">exec </span>rails generate scaffold Thing name:string <span class="c"># generate model/views/controllers</span>
</span><span class='line'>bundle <span class="nb">exec </span>rake db:migrate   <span class="c"># update database with model data</span>
</span><span class='line'>bundle <span class="nb">exec </span>rails s           <span class="c"># start rails server localhost:3000</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Note: I had to uncomment the &lsquo;local&rsquo; setting from my </em>database.yml<em> file because rails couldn&rsquo;t connect due to permission problems on the local socket file. I could have reconfigured postgres instead but meh.</em></p>

<p>OSX users can also use <a href="http://pow.cx/">POW!</a> or <a href="http://anvilformac.com/">Anvil</a> (which uses POW! under the covers) to set up a fake URL pointing to their local rails app directories, so in my case I can visit <a href="http://myapp.dev">http://myapp.dev</a> and it will actually show me the app running on my local machine. It makes the testing cycle a lot quicker.</p>

<p>Add some simple static content:</p>

<figure class='code'><figcaption><span>Generate some simple content in the Rails app</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>rails generate controller StaticPages home about --no-test-framework
</span><span class='line'>
</span><span class='line'><span class="c"># set root &#39;/&#39; route to point to static home page</span>
</span><span class='line'>vim config/routes.rb <span class="c"># add &quot;root &#39;static_pages#home&#39;&quot; beneath other routes</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now you should be able to visit <code>localhost:3000</code> and see a generic &lsquo;home&rsquo; page message.</p>

<!-- x_ -->


<h3>Check in to git</h3>

<p>This creates a local git repository, but during the heroku deployment step I&rsquo;ll push it over there too. I&rsquo;ll also push it to GitHub when it looks like more of an app. So in git parlance, this is what I&rsquo;ll have on my local machine:</p>

<center><img src='http://seshbot.com/images/plantuml/47744a7f09a1979266fbebf4dfaefe7e.png'></center>




<figure class='code'><figcaption><span>Create the local &#8216;master&#8217; git repository</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>rake tmp:clear
</span><span class='line'>git init .
</span><span class='line'>git add -f *
</span><span class='line'>git commit -a -m<span class="s2">&quot;Initial commit&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>I regularly run those <code>git</code> commands to make it easier to revert any mistakes I happen to make.</p>

<h3>Adding ember framework</h3>

<p>I have tried two alternative approaches to creating a new rails app for ember.</p>

<h4>Alternative 1: use the ember &lsquo;edge template&rsquo;</h4>

<p>I think this one is probably the best as it was demonstrated by Yehuda Katz (main Ember guy) in <a href="http://www.youtube.com/watch?v=BpQj9_qEUAc">this live demonstration video</a>. I ran a diff on projects created with and without and it seems to:</p>

<ul>
<li>adds some ember gems to the Gemfile: <code>active_model_serializers</code>, <code>ember-rails</code> and <code>ember-source</code></li>
<li>remove the rails &lsquo;application view layout&rsquo; (<em>app/views/layouts/application.html.erb</em>)</li>
<li>create an ember &lsquo;application template&rsquo; (<em>app/assets/javascripts/templates/application.handlebars</em>)</li>
<li>creates a &lsquo;view asset&rsquo; that generates an index.html with the ember application.js in it (<em>app/views/assets/index.html.erb</em>)</li>
<li>sets up a rails route pointing to the assets controller &lsquo;index&rsquo; action (<em>config/routes.rb</em>)</li>
<li>create empty assets controller and helper files (not sure why)</li>
<li>create a rails ActiveModel &lsquo;application serializer&rsquo; (<em>app/serializers/application_serializer.rb</em>) that does a few things ember requires <!-- x_ --></li>
</ul>


<p>Installing using the edge template is simple. Just replace the <code>rails new</code> step above with the following:</p>

<figure class='code'><figcaption><span>Creating a rails app using the ember template</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>rails new myapp --database<span class="o">=</span>postgresql -m http://emberjs.com/edge_template.rb
</span><span class='line'><span class="nb">cd </span>myapp
</span><span class='line'>
</span><span class='line'><span class="c"># edit your database config and Gemfile as before...</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Note: I had problems using the remote edge template, so downloaded it and used my local copy instad.</em></p>

<h4>Alternative 2: add ember to an existing rails app</h4>

<p>You could also just add the <code>ember-rails</code> gem directly to your Gemfile, then run <code>rails generate ember:bootstrap</code> and you get a basic Ember framework in your <code>app/assets</code> directory. I also prefer to use javascript directly (as opposed to CoffeeScript, which is the default), so add <code>-g --javascript-engine js</code></p>

<figure class='code'><figcaption><span>Add a simple Ember application framework to the Rails app</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>vim Gemfile
</span><span class='line'><span class="c"># add &#39;gem &quot;ember-rails&quot;, github: &quot;emberjs/ember-rails&quot;&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Following this approach I believe you&rsquo;ll have to manually set up the <a href="https://github.com/rails-api/active_model_serializers">Ember ActiveModel Serializer</a> which was written by the Ember guys, and ensures your Ember app understands the format of your Rails app&rsquo;s JSON data. The first alternative does this for you.</p>

<h4>Common to both approaches</h4>

<p>After you have created and updated your Gemfile, you still need to bootstrap the ember environment, and then ensure Ember is running in &lsquo;development&rsquo; mode when Rails is.</p>

<p><em>Note: you can Set &lsquo;developer mode&rsquo; (which enables developer-centric error messages and is apparently quite useful) by updating your </em>config/environments/development.rb<em> with: <code>config.ember.variant = :development</code>. By default running locally will run in dev mode, and running on Heroku will run production mode however.</em></p>

<figure class='code'><figcaption><span>Add a simple Ember application framework to the Rails app</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>bundle install
</span><span class='line'>bundle <span class="nb">exec </span>rails g ember:bootstrap -g --javascript-engine js
</span><span class='line'>bundle <span class="nb">exec </span>rails g ember:install --head
</span><span class='line'>
</span><span class='line'>vim config/environments/development.rb <span class="c"># add config.ember.variant = :development</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Deploying to Heroku</h2>

<p>Heroku requires a few rails settings to be modified to work properly:</p>

<figure class='code'><figcaption><span>Change rails app settings for Heroku</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>vim config/environments/production.rb <span class="c"># heroku runs in prod mode by default</span>
</span><span class='line'><span class="c"># change &#39;config.serve_static_assets&#39; to true</span>
</span><span class='line'>
</span><span class='line'>vim Gemfile
</span><span class='line'><span class="c"># add &quot;gem &#39;rails_12factor&#39;&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>I have already gone through the Heroku sign up process and installed the toolbelt appropriate for OSX (the toolbelt provides the <code>heroku</code> command line tool), so I won&rsquo;t outline that here.</p>

<p>Installing my rails application on Heroku was then a simple matter of:</p>

<figure class='code'><figcaption><span>Add application in the current directory to Heroku</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>heroku login
</span><span class='line'>heroku create --stack cedar
</span><span class='line'>git push heroku master
</span><span class='line'>
</span><span class='line'><span class="c"># whenever you make database changes</span>
</span><span class='line'>heroku run rake db:migrate
</span><span class='line'>
</span><span class='line'><span class="c"># if you want to push your local database contents to heroku</span>
</span><span class='line'>heroku db:push <span class="c"># requires the &#39;taps&#39; gem (&#39;gem install taps&#39;)</span>
</span></code></pre></td></tr></table></div></figure>


<p>This creates an image with a particular configuration of applications and adds a <code>heroku</code> git remote to the git configuration.</p>

<p>Now you can visit the heroku app online (in my case at <a href="http://seshbot.herokuapp.com/">http://seshbot.herokuapp.com/</a>).</p>

<p>TODO: use <code>gem rails_12factor</code>? This alters the rails app a little to make it <a href="http://12factor.net/">12 factor</a>, which is a set of guidelines for how one should build an application to make it easier to administer and deploy. Not really important right now though.</p>

<!-- x_ -->


<h2>Troubleshooting and administering Heroku</h2>

<figure class='code'><figcaption><span>Various heroku debugging commands</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>heroku ps    <span class="c"># list running apps</span>
</span><span class='line'>heroku logs  <span class="c"># show application logs</span>
</span><span class='line'>heroku run console <span class="c"># run interactive ruby console</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>Various heroku administrative commands</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>heroku config  <span class="c"># configure remote app through environment variables</span>
</span><span class='line'>heroku apps    <span class="c"># overview of apps</span>
</span><span class='line'>heroku destroy <span class="c"># deallocate remote server</span>
</span><span class='line'>heroku run rake db:migrate
</span></code></pre></td></tr></table></div></figure>


<p><code>heroku config</code> sets environment variables for things you don&rsquo;t want to commit to git (e.g., passwords). Configure your Rails apps to use <code>ENV['MY_VAR']</code> instead of your super secret key, then run <code>heroku config:add MY_VAR=blahblah</code>.</p>

<p>There are also various <code>heroku pg:</code> commands for updating the application database. The application itself doesn&rsquo;t have full admin access to the database so you can&rsquo;t for example write <code>heroku run rake db:drop</code>. Instead you should run <code>heroku pg:reset</code> if you want to clear the database.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Learning Ruby and Rails]]></title>
    <link href="http://seshbot.com/blog/2014/01/14/learning-ruby-and-rails/"/>
    <updated>2014-01-14T01:32:29+00:00</updated>
    <id>http://seshbot.com/blog/2014/01/14/learning-ruby-and-rails</id>
    <content type="html"><![CDATA[<p><em>Note: The formatting of this article is not great, but I pumped it out quickly after going through the tutorials</em></p>

<p>I dedicated this morning to learning some Ruby and Ruby on Rails (RoR). For my purposes, RoR provides the server-side API to a web application, like this:</p>

<center><img src='http://seshbot.com/images/plantuml/dc42b2dad537dd0af4f1a7d3eed736ba.png'></center>


<p>To my delight, I quickly discovered that Ember (which I have been messing around with quite a bit) is modelled directly on Rails &ndash; not just in the generic they-are-both-MVC-architectures-way, but down to their usages being identical in many respects. I think many new webby techs follow this same style (Meteor seems to, for example.)</p>

<p>This post outlines the core concepts I have picked up from the various tutorials. I also included a RoR cheat-sheet I created while doing the Rails tutorial.</p>

<p>To get started on Windows/Mac, I&rsquo;m guessing the easiest way is by downloading the <a href="http://railsinstaller.org">RailsInstaller</a>.</p>

<!-- more -->


<h2>Learning Ruby</h2>

<p>For an absolute beginner, <a href="http://tryruby.org">Try Ruby</a> takes about 30 minutes, and will show the very basics:</p>

<ul>
<li>basic syntax</li>
<li>standard data structures (strings, arrays, hashes)</li>
<li>defining methods</li>
<li>defining classes (basics on attributes and <code>initialize</code> method)</li>
</ul>


<p>It stays very high-level, but obviously that&rsquo;s the intention. It avoids going into language features such as reflection, lambdas, string manipulation (<code>mystring = "var is #{my-var}"</code>), and doesn&rsquo;t talk about administration etc.</p>

<p>See the <a href="http://ruby-doc.org/core-2.1.0/">Ruby core documentation</a> for reference material.</p>

<h2>Learning Rails</h2>

<p>First, some language references: <a href="http://api.rubyonrails.org">Rails API docs</a> or <a href="http://apidock.com/rails">API Dock</a> or the other seachable <a href="http://railsapi.com">Rails API docs</a> can be downloaded and used locally.</p>

<p>I chose to follow the <a href="http://railsforzombies.org" title="">Rails for Zombies</a> tutorial, as it is often quoted as being helpful as a fully interactive online tutorial. It takes a few hours, but does seem to cover all the fundamentals, namely:</p>

<ul>
<li>Rails conventions

<ul>
<li>syntax for creation, read, update and delete of entities in the database</li>
<li>naming conventions for database table, view, and controller lookup</li>
</ul>
</li>
<li>Models

<ul>
<li>model class structure</li>
<li>invoking <abbr title="Create, Read, Update, Delete">CRUD</abbr> operations on the models</li>
<li>how relationships between entities are expressed, and how they map to the database structure</li>
</ul>
</li>
<li>Views

<ul>
<li>syntax (<code>&lt;% %&gt;</code> and <code>&lt;%= %&gt;</code>)</li>
<li>lookup from URL (searches <code>app/assets</code> folder before trying to run rails routes)</li>
<li>helpers (<code>link_to</code>, <code>edit_thing_path</code> etc)</li>
</ul>
</li>
<li>Controllers

<ul>
<li>controller class structure</li>
<li>rendering alternative views</li>
<li>rendering alternative formats (json, xml)</li>
<li>session variables (used for basic auth checks)</li>
<li>factoring out and configuring common code performed on all actions</li>
</ul>
</li>
<li>Routes

<ul>
<li>defining RESTful resources (automatically direct requests to controllers/views)</li>
<li>defining custom routes</li>
<li>creating helpers for <code>link_to</code> when creating custom routes</li>
</ul>
</li>
</ul>


<p>The main thing it <em>doesn&rsquo;t</em> cover is the administration (installation, deployment) and command-line usage (e.g., automatic generation of controllers and models.) This isn&rsquo;t a big deal however, as the <a href="http://guides.rubyonrails.org/getting_started.html">standard getting started guide</a> does this very well.</p>

<p>I think there are a few bugs in the programme however:</p>

<ul>
<li>the tutorial videos are a bit out of date (for pre-3.0 versions of RoR) but the practical exams use post-3.0 RoR it seems</li>
<li>the last prac exam requires different syntax than that in the tutorial:

<ul>
<li>redirect controller#action case is different (tut vids say <code>Zombies#undead</code> prac requires <code>zombies#undead</code>)</li>
<li>redirect in prac requires prefix &lsquo;/&rsquo; (&lsquo;/zombies => &rsquo;/undead&#8217;). Tutorial vids did not.</li>
</ul>
</li>
</ul>


<h3>Rails Cheat Sheet</h3>

<p>I created this while going through the Zombies tutorial. There&rsquo;s probably better cheat sheets out there, but I highly recommend creating your own as a learning experience.</p>

<h4>RoR&rsquo;s Ruby API syntax</h4>

<ul>
<li>Entity creation syntax (note, Rails will generate an ID for you):

<ul>
<li><code>t = Thing.new; t.status = "something"; t.save</code></li>
<li><code>t = Thing.new(:status =&gt; "something"); t.save</code></li>
<li><code>Thing.create(:status =&gt; "something")</code></li>
</ul>
</li>
<li>Entity query syntax:

<ul>
<li><code>Thing.find(1)</code> (by ID)</li>
<li>many alternate query methods: <code>first</code>, <code>last</code>, <code>all</code>, <code>count</code>, <code>order(:status)</code>, <code>limit(n)</code>, <code>where(:status =&gt; "good")</code></li>
<li>performance note: queries are performed on DB</li>
<li>syntax note: may also chain methods</li>
</ul>
</li>
<li>Entity update syntax:

<ul>
<li><code>t = Thing.find(id); t.status = "bad"; t.save</code></li>
<li><code>...; t.attributes = { :status =&gt; "bad"; ... }; save</code></li>
<li><code>...; t.update_attributes(:status =&gt; "bad"; ...}</code> (no save)</li>
</ul>
</li>
<li>Entity deletion syntax:

<ul>
<li><code>t = Thing.find(id); t.destroy</code></li>
<li><code>Thing.destroy_all</code></li>
</ul>
</li>
<li>on <code>save</code> failure, try <code>t.errors</code> to investigate what went wrong</li>
</ul>


<h4>Models</h4>

<p>Default model definition goes in <code>app/models/thing.rb</code></p>

<figure class='code'><figcaption><span>A simple model of a &#8216;thing&#8217; that has a &#8216;status&#8217; attribute</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">Thing</span> <span class="o">&lt;</span> <span class="ss">ActiveRecord</span><span class="p">:</span><span class="ss">:Base</span>
</span><span class='line'>   <span class="c1"># validation</span>
</span><span class='line'>   <span class="c1">#</span>
</span><span class='line'>   <span class="n">validates_presence_of</span> <span class="ss">:status</span> <span class="c1"># mandatory fields</span>
</span><span class='line'>   <span class="c1"># many other validations: e.g., uniqueness, format, conf/acceptance, etc</span>
</span><span class='line'>
</span><span class='line'>   <span class="c1"># alternative validation syntax:</span>
</span><span class='line'>   <span class="n">validates</span> <span class="ss">:status</span><span class="p">,</span> <span class="ss">:presence</span> <span class="o">=&gt;</span> <span class="kp">true</span> <span class="c1">#, :length =&gt; { :minimum =&gt; 3 }</span>
</span><span class='line'>
</span><span class='line'>   <span class="c1"># relationships (reflected in DB)</span>
</span><span class='line'>   <span class="c1">#</span>
</span><span class='line'>   <span class="n">belongs_to</span> <span class="ss">:person</span>
</span><span class='line'>   <span class="c1"># the Person will have &#39;has_many :things&#39; (note plural)</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<h4>Views</h4>

<ul>
<li><code>thing</code> default view definition goes in <code>app/views/things/index.html.erb</code> and <code>app/views/things/show.html.erb</code>):

<ul>
<li>alternatives actions to <code>show</code> can be added as <code>myaction.html.erb</code></li>
</ul>
</li>
<li>evaluate code with <code>&lt;% ruby code %&gt;</code>, eval and print with <code>&lt;%= ruby code %&gt;</code></li>
<li>shared application stuff (header/footer) goes in <code>app/views/layouts/application.html.erb</code> (use <code>&lt;%= yield %&gt;</code> for body placeholder)

<ul>
<li><code>&lt;%= stylesheet_link_tag :all %&gt;</code> renders stylesheet links for all files in <code>app/assets/stylesheets/</code></li>
<li><code>&lt;%= javascript_include_tag :defaults %&gt;</code> renders script tags for all files in <code>app/public/javascripts/</code></li>
<li>`&lt;%= csrf_meta_tag %> adds some stuff to prevent cross-site-meta-request-forgery hacking (people injecting their own HTML into comments etc)</li>
<li><code>&lt;%= link_to thing.name, thing_path(thing) %&gt;</code> (first param is link text, second URL). Can use the entity itself instead of <code>thing_path(thing)</code></li>
</ul>
</li>
</ul>


<p>Sample <code>index.html.erb</code> (create a link to this with <code>things_path</code>):</p>

<figure class='code'><figcaption><span>An example &#8216;things&#8217; view template</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='erb'><span class='line'><span class="x">&lt;ul&gt;</span>
</span><span class='line'><span class="x">&lt;!-- @things set up in controller --&gt;</span>
</span><span class='line'><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">&quot;Home&quot;</span><span class="p">,</span> <span class="n">root_path</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="cp">&lt;%</span> <span class="k">if</span> <span class="vi">@things</span><span class="o">.</span><span class="n">empty?</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="x">   No things yet</span>
</span><span class='line'><span class="cp">&lt;%</span> <span class="k">else</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="x">   </span><span class="cp">&lt;%</span> <span class="vi">@things</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">thing</span><span class="o">|</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="x">      &lt;li&gt;</span>
</span><span class='line'><span class="x">         </span><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="n">thing</span><span class="o">.</span><span class="n">status</span><span class="p">,</span> <span class="n">thing</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="x">         </span><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">&quot;Edit&quot;</span><span class="p">,</span> <span class="n">edit_thing_path</span><span class="p">(</span><span class="n">thing</span><span class="p">)</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="x">         </span><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">&quot;Delete&quot;</span><span class="p">,</span> <span class="n">thing</span><span class="p">,</span> <span class="ss">:method</span> <span class="o">=&gt;</span> <span class="ss">:delete</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="x">      &lt;/li&gt;</span>
</span><span class='line'><span class="x">   </span><span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">&quot;+&quot;</span><span class="p">,</span> <span class="n">new_thing_path</span> <span class="cp">%&gt;</span><span class="x"></span>
</span><span class='line'><span class="x">&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<h4>Controllers</h4>

<ul>
<li><code>thing</code> controller definition goes in <code>app/controllers/things_controller.rb</code>_</li>
</ul>


<figure class='code'><figcaption><span>A &#8216;things&#8217; controller, responsible for setting view state</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">ThingsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
</span><span class='line'>   <span class="c1"># common code, called by all actions</span>
</span><span class='line'>   <span class="n">before_filter</span> <span class="ss">:get_thing</span><span class="p">,</span> <span class="ss">:only</span> <span class="o">=&gt;</span> <span class="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">,</span> <span class="ss">:destroy</span><span class="o">]</span>
</span><span class='line'>   <span class="n">before_filter</span> <span class="ss">:check_auth</span><span class="p">,</span> <span class="ss">:only</span> <span class="o">=&gt;</span> <span class="o">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">,</span> <span class="ss">:destroy</span><span class="o">]</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">get_thing</span> <span class="c1"># called by before_filter</span>
</span><span class='line'>      <span class="vi">@thing</span> <span class="o">=</span> <span class="no">Thing</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:id</span><span class="o">]</span><span class="p">)</span> <span class="c1"># all URL query params are available</span>
</span><span class='line'>   <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">check_auth</span> <span class="c1"># called by before_filter</span>
</span><span class='line'>      <span class="c1"># do auth verification (check &#39;if flash[:notice]&#39; in rendering page)</span>
</span><span class='line'>      <span class="k">if</span> <span class="n">session</span><span class="o">[</span><span class="ss">:user_id</span><span class="o">]</span> <span class="o">!=</span> <span class="vi">@thing</span><span class="o">.</span><span class="n">user_id</span>
</span><span class='line'>         <span class="c1"># flash[:notice] = &quot;Not authorized!&quot; </span>
</span><span class='line'>         <span class="n">redirect_to</span><span class="p">(</span><span class="n">things_path</span><span class="p">,</span> <span class="ss">:notice</span> <span class="o">=&gt;</span> <span class="s2">&quot;Not authorized!&quot;</span><span class="p">)</span>
</span><span class='line'>      <span class="k">end</span>
</span><span class='line'>   <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">show</span>         <span class="c1"># show single </span>
</span><span class='line'>      <span class="c1"># set view state before rendering view</span>
</span><span class='line'>
</span><span class='line'>      <span class="n">render</span> <span class="ss">:action</span> <span class="o">=&gt;</span> <span class="s1">&#39;myaction&#39;</span> <span class="c1"># to render different view (default &#39;show&#39;)</span>
</span><span class='line'>
</span><span class='line'>      <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="nb">format</span><span class="o">|</span> <span class="c1"># optional</span>
</span><span class='line'>         <span class="nb">format</span><span class="o">.</span><span class="n">html</span> <span class="c1"># myaction.html.erb</span>
</span><span class='line'>         <span class="nb">format</span><span class="o">.</span><span class="n">xml</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">:xml</span> <span class="o">=&gt;</span> <span class="vi">@thing</span> <span class="p">}</span>
</span><span class='line'>         <span class="nb">format</span><span class="o">.</span><span class="n">json</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">:json</span> <span class="o">=&gt;</span> <span class="vi">@thing</span> <span class="p">}</span>
</span><span class='line'>      <span class="k">end</span>
</span><span class='line'>   <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">edit</span><span class="p">;</span> <span class="k">end</span>    <span class="c1"># show &#39;edit&#39; form</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">index</span>        <span class="c1"># list all</span>
</span><span class='line'>      <span class="k">if</span> <span class="n">params</span><span class="o">[</span><span class="ss">:status</span><span class="o">]</span>
</span><span class='line'>         <span class="vi">@things</span> <span class="o">=</span> <span class="no">Thing</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="ss">:status</span> <span class="o">=&gt;</span> <span class="n">params</span><span class="o">[</span><span class="ss">:status</span><span class="o">]</span><span class="p">)</span>
</span><span class='line'>      <span class="k">else</span>
</span><span class='line'>         <span class="vi">@things</span> <span class="o">=</span> <span class="no">Thing</span><span class="o">.</span><span class="n">all</span>
</span><span class='line'>      <span class="k">end</span>
</span><span class='line'>   <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">new</span><span class="p">;</span> <span class="k">end</span>     <span class="c1"># show &#39;new&#39; form</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">create</span>       <span class="c1"># create new</span>
</span><span class='line'>      <span class="c1"># expects params of the form { thing: {status: &#39;good&#39;, name: &#39;xxx&#39;} }</span>
</span><span class='line'>      <span class="vi">@thing</span> <span class="o">=</span> <span class="no">Thing</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">params</span><span class="o">[</span><span class="ss">:thing</span><span class="o">]</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>      <span class="n">redirect_to</span><span class="p">(</span><span class="vi">@thing</span><span class="p">)</span>
</span><span class='line'>   <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">update</span><span class="p">;</span> <span class="k">end</span>  <span class="c1"># update</span>
</span><span class='line'>
</span><span class='line'>   <span class="k">def</span> <span class="nf">destroy</span><span class="p">;</span> <span class="k">end</span> <span class="c1"># delete</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<h4>Routes</h4>

<ul>
<li>application routes defined in <code>app/config/routes.rb</code></li>
<li><code>resources</code> directive creates a full RESTful resource. This means that it will automatically create the following helpers and routes:

<ul>
<li><code>things_path</code> (/things &lsquo;index&rsquo; action)</li>
<li><code>thing</code> (/thing/id &lsquo;show&rsquo; action)</li>
<li><code>new_thing_path</code> (/things/new &lsquo;new&rsquo; action)</li>
<li><code>edit_thing_path(thing)</code> (/things/[id]/edit &lsquo;edit&rsquo; action)</li>
<li>&hellip; plus more</li>
</ul>
</li>
</ul>


<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="ss">MyApp</span><span class="p">:</span><span class="ss">:Application</span><span class="o">.</span><span class="n">routes</span><span class="o">.</span><span class="n">draw</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">resources</span> <span class="ss">:things</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">match</span> <span class="s1">&#39;new_thing&#39;</span> <span class="o">=&gt;</span> <span class="s2">&quot;Things#new&quot;</span> <span class="c1"># path =&gt; ControllerName=&gt;actionName</span>
</span><span class='line'>   <span class="n">match</span> <span class="s1">&#39;all&#39;</span> <span class="o">=&gt;</span> <span class="s2">&quot;Things#index&quot;</span><span class="p">,</span> <span class="ss">:as</span> <span class="s2">&quot;all_things&quot;</span> <span class="c1"># create all_things_path helper for link_to etc</span>
</span><span class='line'>   <span class="c1"># alternative:</span>
</span><span class='line'>   <span class="n">match</span> <span class="s1">&#39;all&#39;</span> <span class="o">=&gt;</span> <span class="n">redirect</span><span class="p">(</span><span class="s1">&#39;/things&#39;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>   <span class="c1"># TODO: case sensitive? the tutorial seems confused on this</span>
</span><span class='line'>   <span class="n">root</span> <span class="ss">:to</span> <span class="o">=&gt;</span> <span class="s2">&quot;Things#index&quot;</span> <span class="c1"># sets up &#39;/&#39; route to &#39;/things&#39;</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">match</span> <span class="s1">&#39;status_things/:status&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;Things#index&#39;</span> <span class="c1"># add :status controller params</span>
</span><span class='line'>   <span class="n">match</span> <span class="s1">&#39;:username&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;Things#index&#39;</span><span class="p">,</span> <span class="ss">:as</span> <span class="o">=&gt;</span> <span class="s1">&#39;user_things&#39;</span>
</span><span class='line'>   <span class="c1"># in view: &lt;%= link_to &#39;seshbot things&#39;, user_things_path(&#39;seshbot&#39;) %&gt;</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[This week in review: my game table web app]]></title>
    <link href="http://seshbot.com/blog/2014/01/11/this-week-in-review-the-game-table-web-app/"/>
    <updated>2014-01-11T02:19:08+00:00</updated>
    <id>http://seshbot.com/blog/2014/01/11/this-week-in-review-the-game-table-web-app</id>
    <content type="html"><![CDATA[<p>First here&rsquo;s a quick summary of what I got up to:</p>

<ol>
<li>trying to build a simple &lsquo;gaming table&rsquo; application in Ember.js,</li>
<li>styling with Twitter bootstrap,</li>
<li>messing with plugins in my blog (trying unsuccessfully to fix code highlighting, and adding a UML tool &ndash; see below)</li>
</ol>


<center><img src='http://seshbot.com/images/plantuml/7f148dfb8d968e365103d42622a30b55.png'></center>


<p>I spent most of my time learning about Ember. <a href="http://emberjs.com">Ember.js</a> is a very nice looking front-end MVC framework that has a very appealing <a href="http://emberjs.com/guides/">getting started guide</a> that make it look <em>super simple</em> to create a reactive application. Three things that people will not tell you however:</p>

<ul>
<li>demo videos only ever show the main usage scenario of that framework</li>
<li>most new frameworks change so often that they&rsquo;re either unstable or very little up-to-date documentation exists, and</li>
<li>many of the benefits they offer you probably won&rsquo;t end up using anyway, for various reasons</li>
</ul>


<p>For now though I&rsquo;ll go ahead with it because I feel that I&rsquo;m just about to start doing cool stuff in it (it kinda always feels like this though.)</p>

<p><strong>Next week</strong> I&rsquo;m thinking of switching back to some C++ stuff so I can dabble in a realm I&rsquo;m more comfortable with for a while&hellip; Monday is a public holiday in Japan though so I&rsquo;ll probably be wandering around and not programming much.</p>

<!-- more -->


<h3>Problem 1: binding non-nested components was difficult</h3>

<p>I figured I would devote my first day last week to creating the framework for a small Gaming Table application. Perhaps just start off with a quick chat client or sketching app. I was not accounting however for the vagaries of modern web application development, and I ended up messing around with stupid little problems for most of the week. Looking back I feel it was quite frustrating overall &ndash; it seems that many of these new techs do not quite work as advertised, if at all.</p>

<p>Most tutorials and documentation will usually only tell you about one way to make an ember app &ndash; showing the details of a single entity or collection of entities of the same type at a time. Perhaps it might be some blogging application that lets you dig down into various blog entries, or perhaps it will involve showing all the tweets from a particular tweeter. Whatever the demo, I&rsquo;m sure it will show you how to explore <em>a single concept</em>.</p>

<p>The first thing I wanted to do was to show your online friends on the left side and allow you to create or enter an existing chat room. I immediately got stuck on a stupid little problem however that I stubbornly refused to get past, leading to several wasted days.</p>

<p>My specific problem was <em>how can I make the nav bar show the name of the current gaming table (kind of like a chat room), but show some placeholder message if I&rsquo;m not in a room</em>. The problem being that the region dedicated to showing information about the current table (players, cards etc) is not a descendent hierarchically of the nav bar.</p>

<center><img src='http://seshbot.com/images/plantuml/3bdacfc29fd9e7e730d15e02ab13157c.png'></center>


<p>Long story short, the correct way seems to involve: 1) modifying the &lsquo;Nav Bar&rsquo; controller to add a dependency to the &lsquo;Game Table&rsquo; controller; 2) add to the Nav Bar controller an alias or dynamic property pointing to the Game Table controller (this is conceptually the last table loaded); and 3) creating another dynamic property in the Nav Bar controller that is updated whenever <code>currentPath</code> is updated, and returns <code>null</code> if the route (<code>currentRouteName</code>) is no longer a table.</p>

<p>This might make sense, but it was a pain in the ass to discover. (Side note: I&rsquo;m working on a general &lsquo;getting to know Ember.js&rsquo; post that goes into a lot more detail on this so others tackling the same problem might not have to spend as long as I spent on it.)</p>

<p><span class='pullquote-right' data-pullquote='all of the Ember help I found is out of date, and none of the code samples I found worked.'>
I&rsquo;m not saying the framework is terrible, but all of the Ember help I found is out of date, and none of the code samples I found worked. Ember only reached v1.0 4 months ago (Sept 2013) so any advice from before that period is probably out of date. Code samples will not work, and jsfiddle/jsbin apps will probably not run, which is a huge problem because that is how people communicate working code samples with each other in this community.
</span></p>

<p>I&rsquo;m concerned that the Ember docs might not cover enough real world scenarios that &lsquo;proper&rsquo; applications might encounter (e.g., several regions dedicated to different information.)</p>

<h3>Live Help in IRC! 1980&rsquo;s tech to the rescue</h3>

<p>The IRC channel is pretty awesome &ndash; the #emberjs channel of freenode.org is one of the most populated channels on the server, and I&rsquo;ve saved a lot of time by asking for help there.</p>

<p>I spent a long time digging through documentation on how to solve this problem before I turned to IRC. Then within 10 minutes I had someone giving me meaningful advice that I ended up using. The secret was that I went in there with a minimalistic example of my problem that they could mark up and fix for me. <a href="http://jsbin.com/UzaFUZE/1/edit?html,js,output">Here&rsquo;s</a> the code I gave them and <a href="http://jsbin.com/UzaFUZE/4/edit?html,js,output">here&rsquo;s</a> what they gave me.</p>

<h3>Hosting a backend</h3>

<p>I have been mainly concentrating on the front end functionality so far, so didn&rsquo;t want to spend too long messing around with the server side. I had originally decided that I&rsquo;d learn some rails, but decided to try out a &lsquo;no backend&rsquo; solution &ndash; in this case <a href="http://deployd.com">deployd</a>. The two criteria I was after were a simple REST API and some kind of authentication, both of which deployd ostensibly offers. There were a few hiccups though.</p>

<p>The first was that deployd is still actively being developed, so the web UI isn&rsquo;t totally intuative. I won&rsquo;t go too far into it but it has been a hassle.</p>

<p>The next problem is that although both Ember and Deployd declare that they speak standard REST JSON language, it turns out they don&rsquo;t agree on how that language should look. I had to mess around a fair amount and ask around on IRC before discovering that you need to apply your own serializer, that intercepts all remote data transfers and allows you to &lsquo;munge&rsquo; it a little into a format that Ember is happy with.</p>

<p>Again, I&rsquo;ll include the details of all this in a post dedicated to Ember later.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What's so hard about programming?]]></title>
    <link href="http://seshbot.com/blog/2014/01/06/whats-so-hard-about-programming/"/>
    <updated>2014-01-06T11:19:49+00:00</updated>
    <id>http://seshbot.com/blog/2014/01/06/whats-so-hard-about-programming</id>
    <content type="html"><![CDATA[<p>It is a fact that every programmer is the star of their peer group, and would spin out the most awesome cleanly-built apps if only he or she didn&rsquo;t have to work under these circumstances. It is also a fact that every programmer understands that they were terribly misguided just a few years prior.</p>

<p>Given these two facts, I would have to think a whole lot of myself to give advice on programming to other programmers. I happen to know however that I am in fact a better programmer than most, and am therefore uniquely qualified to offer such advice.</p>

<p>So here&rsquo;s some of the things I feel I&rsquo;ve learned the hard way &ndash; at least enough that every time I work on a project they jump to mind and guide my actions.</p>

<!-- more -->


<h3>Which are the best technologies?</h3>

<p>Programming languages are tricky to learn, and programmers have a vested interest in believing that the technologies they know best are the most appropriate technologies to use for every task. For the purposes of this article, those people will be known as <em>curmudgeons</em>.</p>

<p>Curmudgeons often avoid learning more than their one favourite language. I spent about 8 years programming exclusively in C++ before I finally took the jump to another language, and that point represented a refreshingly great learning curve for me. I love C++ but there&rsquo;s features that it simply does not have, so I&rsquo;ll demonstrate by talking about C++ from a curmudgeonly perspective.</p>

<p>C++ does not have reflection, and I used to (and still do) think that reflection can make code hard to understand and follow. However reflection is valuable during application bootstrapping for stringing together components at the highest level using dependency injection containers, for example.</p>

<p>C++ does not have garbage collection. I believe languages that use GC tend to make managing resources other than memory (locks, databases, etc) difficult, which in turn makes a lot of code difficult to deal with. However dealing with certain problems <em>without</em> GC can be very tricky or even impossible &ndash; typically anything where the lifetime of an entity cannot be easily identified at coding time, such as lambdas with closures, or <a href="http://en.wikipedia.org/wiki/Persistent_data_structure">&lsquo;persistent&rsquo; data structures</a> (a la <a href="http://clojure.org/data_structures">clojure&rsquo;s data structures</a>), or often many other situations in multi-threaded applications.</p>

<p>C++&rsquo;s standard libraries are incredibly low-level (you&rsquo;d look long and never find the word &lsquo;web&rsquo;, &lsquo;service&rsquo; or &lsquo;actor&rsquo;) and the standard is <em>incredibly</em> slow moving (only recently got threading support, lambdas or regular expressions!) However this is a side-effect of the fact that the language is intended to be long-lived, clearly something it&rsquo;s been very successful at.</p>

<p><span class='pullquote-right' data-pullquote='there are no crappy technologies - only situations where technologies are perhaps not applicable'>
So while I believe the functionality of these &lsquo;friendlier&rsquo; languages are often misused or are considered to solve problems they do not in fact solve well, I also know first-hand how awesome they can be in certain specific scenarios. I now believe that there are no crappy technologies &ndash; only situations where technologies are perhaps not applicable.
</span></p>

<p>Need super high performance? C or C++ is great if you know it really well, as an explicit goal of the language is that all features should come at no hidden cost, which is often a detriment to the language&rsquo;s simplicity. If you or the majority of your team is not familiar with the language however, it will probably not go well. If you are writing a large application, or need to quickly pump out a web service or componentised application, it simply might not be the right tool for the job.</p>

<p>It might be surprising but there are an equal number of curmudgeons using newer languages such as Java, JavaScript and Scala as well. While C++ curmudgeons will tell you that high-level facilities offered by new generation languages (GC etc) are not truly useful, higher-level language curmudgeons will tell you that the performance of their tools are equal, or somehow better than, lower-level languages. Actually, from the perspective that a well-maintained application tends to run smoother this is sometimes true. However from the truest apples-to-apples sense this is rarely the case.</p>

<p>As an example, an often-cited comparison is that between garbage collecting heap allocated memory and the typical semi-manual approach taken by C++. The argument comes down to the observation that scheduled mass-collection of heap memory is generally more efficient than many individual object heap de-allocations. But many programmers that rely on garbage collection would not be aware of stack-based allocation (the default in C++, unavailable in Java) which offers effectively free memory allcation and de-allocation. Or custom allocators, which are a kind of ad-hoc custom garbage collection which can also offer similar benefits in specific circumstances.</p>

<p>A smart programmer would believe that if a language was created, still exists and has a large user base, it probably has a good reason to be around. A programmer that understands more languages is almost by definition more well equipped to effectively tackle more varied problems.</p>

<h3>What&rsquo;s the difference between Analysis and Design?</h3>

<p>Many programmers don&rsquo;t separate the notion of analysis from design. In fact, it would be less charitable but more realistic to say that most programmers don&rsquo;t fully know what analysis is for.</p>

<p>The first step in any project is to understand the requirements &ndash; a process that requires a very thorough analysis phase. A thorough analysis will capture all requirements in a language comfortable to the client, create a domain model that the client agrees captures all of the concepts (entities, events, roles, etc) in the system, and give a good representation of the scope that is being tackled (a complete list of actors interacting and their useage scenarios the application will satisfy.) If you tackle a problem without this knowledge, you don&rsquo;t fully understand the problem and therefore are not yet qualified to fix it.</p>

<p><span class='pullquote-left' data-pullquote='Every requirement accurately captured represents a significant amount of effort saved'>
The agile principle of avoiding &lsquo;big design up-front&rsquo; leads people to avoid performing full analysis up front, which is very misguided. Every requirement accurately captured represents a significant amount of effort saved in large refactorings, or worse yet continual effort working around poorly designed systems.
</span></p>

<p>Analysis is important and should be done as completely as possible, lest the wrong application get built. Design is incremental but continual. While analysis documents tend to be fairly static and only change if the actual requirements change, design documents are often not useful much past the development of the code they relate to. For this reason they&rsquo;re usually only used for reasoning about and communicating a plan of attack for an upcoming component being created or worked on.</p>

<h3>Have we estimated enough time?</h3>

<p>Estimation is said to be the hardest part of programming. It <em>is</em> fricken hard. But usually it becomes much more approachable once the complete scope has been explored &ndash; if every piece of functionality to be delivered is decomposed into the smallest deliverable increments that the client can verify (often known as user stories in agile terminology), and these dozens or sometimes hundreds of stories can be individually and honestly estimated, a rough estimate may be reached.</p>

<p>More importantly however, when you find yourself part-way through stories of a project, you have the ability to re-evaluate your estimate of the remaining portion based on how long the first bit took. This process should replace all these &lsquo;double and add your grandmothers age&rsquo; type estimates, though they require some bravery both on behalf of the developers and the business people.</p>

<p>As a bonus, if the stories were separated into must-, should-, and might-haves, a certain amount of flexibility is built into the system where the portion to be delivered becomes negotiable based on revised estimates.</p>

<h3>Have we completed our design?</h3>

<p>Every time I design a new component I go through a few steps. I find that these are often not considered when estimating the time required to implement new functionality.</p>

<ul>
<li>most importantly, for every entity in the system <strong>consider how the entity will change over time</strong> &ndash; it&rsquo;s simple to represent an order in an online shopping system, but what if it gets cancelled or amended? What if the user account is deleted? What if an item is recalled by the manufacturer?</li>
<li><strong>how will the new component be administered and configured?</strong> This means APIs and user interfaces, which are not glamorous but need to be made.</li>
<li>when modeling the major entities, <strong>model all incoming commands and events</strong> as well &ndash; a good way to tell if there&rsquo;s an event missing is if two entities are relating directly to each other. This also yields heaps of other benefits (see <a href="http://martinfowler.com/eaaDev/EventSourcing.html">event sourcing</a> for example).</li>
<li><strong>separate each entity from the value data associated with that entity.</strong> Entities have identity and usually a long lifetime, and are changed many times throughout their life. Values can be compared trivially, serialised and deserialised and are thread-safe by virtue of being immutable facts.</li>
</ul>


<p>These topics are actually huge but these most readily to mind, expressed as minimalistically as I thought possible.</p>

<h3>Is UML necessary?</h3>

<p>This concept might be a little anachronystic these days as I don&rsquo;t see many people jumping on the UML bandwagon anymore &ndash; if anything it&rsquo;s swung the other way, which is no better really. But it can seem sometimes that UML is some kind of all-or-none proposition.</p>

<p>Many treat UML as a kind of <em>process</em>, when in fact it is a collection of <em>languages</em>. And like any language, it is there to be used primarily for communication. It makes little sense to have a process that revolves around UML per se, but I find that certain diagrams are arguably the best way to express certain ideas.</p>

<p><u><em>During analysis</em></u>: <strong>use-case diagrams</strong> are great for outlining scope; <strong>domain models</strong> are fantastic for discovering the main concepts in a system and are great to carry to early client meetings; and <strong>state diagrams</strong> can <em>really</em> save a lot of time later on down the line (entity states are deceptively tricky to discover.)</p>

<p><u><em>During design</em></u>: these are totally situational, but <strong>component diagrams</strong> show how all the services and applications hang together, where message busses are and how high-availability and how other such architectural concerns are handled; I often find myself sketching out <strong>class diagrams</strong> aplenty to provoke discussions on my immediate plans; and I email tons of <strong>sequence diagrams</strong> around indicating the intricate details on how components coordinate their interactions.</p>

<p>In all, UML is neither good nor bad, it is a set of tools you may decide to use when communicating about software. Objecting to them on principle is like objecting to the written language on principle.</p>

<h3>Will Design Patterns save us?</h3>

<p>There are a lot of good books out there detailing a lot of good design patterns. These patterns take many forms but there is a common unifying factor of all of them &ndash; they don&rsquo;t actually do anything by themselves (otherwise they&rsquo;d be applications or services.) They can be very useful for two purposes &ndash; describing the design of a system to others, or reason about how a part of a problem might decompose into a set of entities, values and relationships.</p>

<p>The problem comes in when the design patterns book comes out as the first step in creating a new application. No matter the problem, the first step should always be to understand the problem through <em>analysis</em>, and then the first step of design should be something like figuring out the major components in the system or the data in/out and transforms, depending on the situation. The design patterns emerge from this process, and the books are useful for recognising them, not guiding the design process.</p>

<p>Interestingly, design patterns are more important to imperative languages than declarative ones &ndash; imperative languages are by their nature higher level and the abstractions that design pattern books enumerate tend to fall out much more naturally without a lot of effort. Functional language curmudgeons are oft quoted as saying that design patterns are missing language features. I&rsquo;m not entirely convinced of this perspective, but it does show how genuinely powerful those languages are at expressing high level concepts simply.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[JavaScript in Modern Web Apps]]></title>
    <link href="http://seshbot.com/blog/2014/01/03/javascript-in-modern-web-apps/"/>
    <updated>2014-01-03T14:20:08+00:00</updated>
    <id>http://seshbot.com/blog/2014/01/03/javascript-in-modern-web-apps</id>
    <content type="html"><![CDATA[<p>The web development scene has moved dramatically since my own minor experience at an Internet business company 14 years ago. Back then we created <em>web pages</em> in ColdFusion/PHP/ASP marked-up HTML. Our main tools were frames and tables and a lot of homegrown convention to ensure headers/footers looked right. We spent most of our efforts on effectively using CSS to make our lives easier &ndash; not separating views from data or dynamically updating HTML elements.</p>

<p>People now create <em>web applications</em> instead of individual pages. Web apps look a lot like native applications, are responsive and dynamic, and have very high-level frameworks that provide application-wide abstractions for business models and the abstraction of the view logic.</p>

<p>This article describes my current understanding of the technologies used in constructing <em>modern</em> web applications, largely based on a few years&#8217; lurking on <a href="http://ycombinator.com">Hacker News</a> and a couple weeks&#8217; not-so-intense investigations.</p>

<!-- more -->


<h3>The importance of JavaScript</h3>

<p>Javascript is said to be the assembly language of the internet. It was created circa 1995 for Netscape Navigator 2.0 as part of a much grander vision for a global web platform. It is supported by all web browsers, and <a href="https://www.dartlang.org/">until recently</a> was the only language broadly enough available to do so.</p>

<p>Modern web applications are built many layers of abstraction on top of this. An extreme and relevant example of this is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> (hereafter XHR) function. Prior to HTML5 WebSockets, all <a href="http://en.wikipedia.org/wiki/Single-page_application">single-page</a> web applications used this single function to receive dynamic updates from a remote server, through a technique commonly known as <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29">AJAX</a>. Likely few web apps actually use the function directly however &ndash; most these days use high-level <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC frameworks</a> (more on these below) to connect the visual elements the user sees in their browser (the view) to entity abstractions updated from a remote server (the model).</p>

<p>It makes sense to me that any understanding of modern web applications would need to be partly underpinned by a solid understanding of JavaScript. It seems like a pretty icky language however, with a lot of weird behaviour ready to trip those unaware of its stupid idiosyncracies. Perhaps because it was <a href="http://www.computer.org/csdl/mags/co/2012/02/mco2012020007.html">rushed out in 10 days</a>.</p>

<p>Here&rsquo;s a few reading recommendations I would like to read one day:</p>

<ul>
<li><a href="http://eloquentjavascript.net/contents.html">Eloquent JavaScript</a> &ndash; basically an ebook that starts from the basics</li>
<li><a href="http://ejohn.org/apps/learn/">Learning Advanced JavaScript</a> &ndash; similar to above only presented as a slide deck with code samples</li>
<li><a href="http://news.ycombinator.com/item?id=3550998">Ask HN &ndash; JavaScript Dev Tools</a> &ndash; debugging in JavaScript</li>
<li><a href="http://michaux.ca/articles/mvc-architecture-for-javascript-applications">MVC Architecture for JS</a> &ndash; building an MVC framework in JS from scratch</li>
<li><a href="http://addyosmani.com/largescalejavascript/">Large-Scale JS Application Architecture</a> &ndash; a guy who knows his stuff on various approaches to building &lsquo;large&rsquo; web apps</li>
<li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript">Mozilla Developer Network &ndash; Intro to OO JS</a> &ndash; everything you need to know on how <code>prototype</code> and <code>new</code> provide OO on top of simple JS function</li>
<li><a href="http://bonsaiden.github.com/JavaScript-Garden/#intro">JavaScript Garden</a> &ndash; a kind of FAQ on all the idiosyncracies of JS (how <code>this</code> works, for example)</li>
<li><a href="http://shichuan.github.io/javascript-patterns/">JavaScript Patterns</a> &ndash; a very nice looking reference on all facets of modern JS (including frameworks)</li>
<li><a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/">Learning JavaScript Design Patterns</a> &ndash; not sure if this is really useful yet, especially compared to the one directly above</li>
</ul>


<h3>JavaScript in the browser</h3>

<p>It&rsquo;s very difficult to figure out which of the myriad JS frameworks are worth investing in, as they come and go and are easily replacable. However some toolsets and frameworks have become totally indispensable timesavers to anyone making a web application.</p>

<ul>
<li><a href="http://jquery.com/">jQuery</a> &ndash; a low-level toolset that vastly simplifies common JS tasks such as manipulating the DOM and using XHR</li>
<li><a href="http://requirejs.org/">RequireJS</a> &ndash; a library that makes including third party modules simple</li>
<li><a href="http://handlebarsjs.com/">Handlebars</a> &ndash; a very popular template parser that uses <code>{{this}}</code> syntax</li>
<li><a href="http://backbonejs.org/">Backbone.js</a> &ndash; allows user-defined model objects to be dynamically linked up to HTML elements for automatic updates</li>
<li><a href="http://emberjs.com/">Ember.js</a> &ndash; an exciting MVC framework that I think is built on top of Handlebars and Backbone, or something like it. More below</li>
<li><a href="http://angularjs.org/">Angular.js</a> &ndash; a Google library that promises to deliver similar functionality as Ember.js, but with a syntax that is meant to look more like a natural extension of HTML</li>
</ul>


<h3>JavaScript on the server</h3>

<p>For some reason JavaScript has become a very popular language for performing server-side tasks as well. I think this has something to do with the recent popularity of the <a href="http://nodejs.org/">Node.js</a> JavaScript web application platform. Node was simplistic enough for people to write small but highly capable tools in a language with which they were already familiar. Regardless of the purpose, it is important to note that the fact that its use on the server side is largely unrelated to its
use in the browser.</p>

<p>I think I&rsquo;ll likely want to look into at least these frameworks:</p>

<ul>
<li><a href="https://npmjs.org/">npm</a> for javascript package installation</li>
<li><a href="http://yeoman.io/">Yeoman</a> provides a set of tools for creating and manipulating a web app on a workflow level</li>
<li><a href="http://bower.io/">Bower</a> for application dependency management. It automatically downloads and configures dependent frameworks for an app</li>
<li><a href="http://gruntjs.com/">Grunt</a> for running preconfigured tasks from a Gruntfile. For example running, testing and previewing web apps</li>
</ul>


<p>As an example of these technologies, here&rsquo;s what it takes to create a basic Ember.js application (a more in-depth starter can be found <a href="http://blog.embed.ly/post/46586649344/introduction-to-ember-development">here</a>):</p>

<figure class='code'><figcaption><span>Creating a new Ember.js application from scratch</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="c"># install pre-requisite apps to your machine</span>
</span><span class='line'>apt-get install npm
</span><span class='line'>npm install -g yo grunt-cli bower
</span><span class='line'>npm install -g grunt-contrib-compass
</span><span class='line'>npm install -g generator-ember
</span><span class='line'>npm install -g grunt-mocha
</span><span class='line'>
</span><span class='line'>mkdir myapp <span class="o">&amp;&amp;</span> <span class="nb">cd </span>myapp
</span><span class='line'>yo ember       <span class="c"># create the application framework</span>
</span><span class='line'>bower install  <span class="c"># download pre-requisite libraries</span>
</span><span class='line'>grunt server   <span class="c"># start app on localhost:8000</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Serving and hosting web apps</h3>

<p>I&rsquo;ve been concentrating mostly on the browser end of the web application architecture equation. So far my thoughts on the matter of hosting haven&rsquo;t really gone too far. Two obvious options come to mind however.</p>

<p><strong>A Yeoman-generated Application</strong> that I think by default uses a simple web server like <a href="http://unicorn.bogomips.org/">Unicorn</a>, started from a Grunt script. There are plenty of instructions on the web for deploying these applications to Heroku or other hosting services.</p>

<p><strong>A Rails RESTful Application</strong> hosted on something like <abbr title="Amazon Web Services">AWS</abbr>. Ruby on Rails is a hefty web framework that also follows the MVC framework. I think it&rsquo;s a full-stack framework in its own right and prefers its own HTML templating engine. I intend to use it to expose a REST API instead of HTML however so I can totally separate the server logic from the UI framework, and perhaps write separate front-ends altogether.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Grand Experiment]]></title>
    <link href="http://seshbot.com/blog/2013/12/20/the-grand-experiment/"/>
    <updated>2013-12-20T01:07:06+00:00</updated>
    <id>http://seshbot.com/blog/2013/12/20/the-grand-experiment</id>
    <content type="html"><![CDATA[<p>A few months ago I decided to hand in my notice and live off my savings for a while. In 13 years of software development this is the first proper hiatus I&rsquo;ve taken so I have no idea what to expect.</p>

<p>I intend to spend the next six to twelve months attempting to see what happens when I have time to myself.</p>

<!-- more -->


<h3>So far&hellip;.</h3>

<p>This is only the first week of my grand experiment. So far I have spent most of it gaming with my other unemployed friends (Pathfinder card game is awesome.) I did set up this blog however, and register seshbot.com, so I suppose it&rsquo;s not a complete loss work-wise.</p>

<h3>Blogging</h3>

<p>I&rsquo;m excited about following an open development process. Source code is only a part of an application however, the analysis and design are integral pieces that I would like to make visible. I am concerned that setting up this blog before I have anything to show is setting the cart before the horse, but it seemed like the smallest most approachable project I could scope out for the first week.</p>

<p>The Octopress platform seems very developer-friendly. I can trivially embed syntax highlighted source code snippets and extend the framework through a simple plugin mechanism (I think.) There is no fancy web UI for composing posts &ndash; its all authoring markup on your local machine then pushing the generated code to github and letting github pages take care of the rest. Writing a new blog post is a matter of:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>&gt; <span class="nb">cd </span>seshbot
</span><span class='line'>&gt; rake new_post<span class="o">[</span><span class="s1">&#39;My New Post!&#39;</span><span class="o">]</span>
</span><span class='line'><span class="c"># Creating new post: source/_posts/2013-12-20-my-new-post.markdown</span>
</span><span class='line'>&gt; vim <span class="nb">source</span>/_posts/2013-12-20-my-new-post.markdown
</span><span class='line'>&gt; rake generate
</span><span class='line'><span class="c"># Successfully generated site: source -&gt; public</span>
</span><span class='line'>&gt; rake deploy
</span><span class='line'><span class="c"># Generating Site with Jekyll</span>
</span><span class='line'><span class="c"># Copying public to _deploy</span>
</span><span class='line'><span class="c"># Pushing generated _deploy website</span>
</span><span class='line'><span class="c"># Github Pages deploy complete</span>
</span></code></pre></td></tr></table></div></figure>


<p>There&rsquo;s of course so much more you can do (preview it locally before uploading for example) but that&rsquo;s the basic workflow.</p>

<h3>Project</h3>

<p>I have a bunch of stuff I want to mess with, but I intend to start writing a few simple web applications. I have in mind some kind of Ruby-on-Rails stack using <a href="http://emberjs.com/">Ember.js</a> for the browser&rsquo;s UI modeling. A shared drawing application perhaps?</p>

<p>Also, I would love to mess around more with C++11/C++14, I have played a little so far and have been very impressed with the productivity and conciseness it affords (it&rsquo;s about time!) A little network game perhaps? I really would love to make a little modular adventure game at some stage. Who knows, perhaps I will be the one to finally make a nice graphical <a href="http://www.bay12games.com/dwarves/">Dwarf Fortress</a> clone? That seems to be the indy gaming unicorn.</p>

<h3>Japan Lifestyle</h3>

<p>So far I have been fortunate but it can be frustrating at times. Living in Japan without a job is a little challenging, though I suspect that would be true in most countries. The immediate challenges are keeping my house (I must renew my lease and they weren&rsquo;t too impressed with the blank &lsquo;employment&rsquo; section of the document) and preparing to pay the various taxes &ndash; most notably residential tax and health insurance, both of which are means-based on the previous years income.</p>

<p>I was very happy to discover that just around the corner from my house is a little cafe run by a very friendly independent game-developer &ndash; <a href="http://picopicocafe.com">PicoPico cafe</a>. Once a month they hold &lsquo;PicoTachi&rsquo;, an event for independent developers (and anyone else really) to show off stuff they&rsquo;ve been working on. That seems almost too fortuitous! I am also looking forward to working in the cafe by myself, it has a very nice ambiance.</p>
]]></content>
  </entry>
  
</feed>
