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

<channel>
	<title>Jayway Team Blog &#187; tutorial</title>
	<atom:link href="http://blog.jayway.com/tag/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Getting Started with Spring Data &#8211; MongoDB in Scala</title>
		<link>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/</link>
		<comments>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 15:11:14 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[spring data]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10621</guid>
		<description><![CDATA[I used MongoDB for a project in 2010 and I had great experience with it. Unfortunately I didn't get the chance to work with this agile and scalable document-oriented database again until now. But my current assignment has brought the opportunity to use it in production In this post I want to show you a [...]]]></description>
			<content:encoded><![CDATA[<p>I used <a title="MongoDB" href="http://www.mongodb.org/">MongoDB</a> for a project in 2010 and I had great experience with it. Unfortunately I didn't get the chance to work with this agile and scalable document-oriented database again until now. But my current assignment has brought the opportunity to use it in production <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In this post I want to show you a step by step guide on how you can start your Scala project with <a title="Spring Data" href="http://www.springsource.org/spring-data/mongodb">Spring Data</a> for MongoDB.</p>
<p>You should have <a title="SBT" href="https://github.com/harrah/xsbt">SBT</a> 0.11 installed on your system since I am going to use it as the building tool through out this post.</p>
<h3>1. Creating Project</h3>
<p>Create the project like below:</p>
<pre>$ mkdir springDataMongo
$ cd springDataMongo/
$ sbt
[info] Loading global plugins from /home/amir/.sbt/plugins
[info] Set current project to default-71a5a0 (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set name := "SpringMongo"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set version := "1.0"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set scalaVersion := "2.9.1"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; session save
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)</pre>
<p>Open file build.sbt and add the dependencies:</p>
<p><script src="https://gist.github.com/1309234.js?file=build.sbt"></script></p>
<p>Save the file and run the following in SBT console:</p>
<pre>&gt; reload
[info] Loading global plugins from /home/amir/.sbt/plugins
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; update
[info] Updating {file:/data/3-Projects/scala-projects/springDataMongo/}default-71a5a0...
[info] Done updating.</pre>
<p>And generate the IDE related files. I am using IntelliJ:</p>
<pre>&gt; gen-idea</pre>
<p>or if you use Eclipse:</p>
<pre>&gt; eclipse create-src</pre>
<p>Now you have configured your project and you can start coding!</p>
<h3>2. Configuring Spring</h3>
<p>There are two ways to configure Spring Data for MongoDB: Annotations and XML. I explain annotations here. You have to extend <span style="text-decoration: underline;">AbstractMongoConfiguration</span> class as follows to define your database settings:</p>
<p><script src="https://gist.github.com/1309234.js?file=MongoConfig.scala"></script></p>
<p>As you see there are two methods to implement. <span style="text-decoration: underline;">mongo</span> method should return an instance of Mongo class. If you are using a mongo instance in a network, you should then specify the address and possibly port (if not the default).</p>
<h3>3. Data Model</h3>
<p>Consider we have the following class for keeping accounts in a system. This class will be mapped to a mongo document by Spring:</p>
<p><script src="https://gist.github.com/1309234.js?file=Account.scala"></script></p>
<h3>4. Interacting with MongoDB</h3>
<p>Now let's write a simple program to interact with MongoDB:</p>
<p><script src="https://gist.github.com/1309234.js?file=App.scala"></script></p>
<p><span style="text-decoration: underline;">mongoTemplate</span> is an implementation of <span style="text-decoration: underline;">MongoOperation</span> interface. With <span style="text-decoration: underline;">MongoOperation</span> you can do all CRUD operations. E.g. inserting/saving a document:</p>
<p><script src="https://gist.github.com/1309234.js?file=SaveAccount.scala"></script></p>
<p>"accounts" is the name of collection. Or if you want to query:</p>
<p><script src="https://gist.github.com/1309234.js?file=Query.scala"></script></p>
<p>Note that <span style="text-decoration: underline;">JavaConversions</span> is required here since the result of <span style="text-decoration: underline;">find</span> is a <span style="text-decoration: underline;">java.util.List[Account]</span> and we need to convert it to Scala list.</p>
<p>Please refer to <a title="documentation" href="http://www.springsource.org/spring-data/mongodb#documentation">documentation</a> of Spring Data for MongoDB for more info about what you can do more <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with Android NDK</title>
		<link>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/</link>
		<comments>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 20:15:48 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[ndk]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10385</guid>
		<description><![CDATA[You want to try out the Android NDK? I have gotten a lot of questions about how to setup and work with the NDK and I decided to write down how I do it. My goal with this entry is to gather all the information you need to get started with the Android NDK. I [...]]]></description>
			<content:encoded><![CDATA[<p>You want to try out the Android NDK? I have gotten a lot of questions about how to setup and work with the NDK and I decided to write down how I do it. My goal with this entry is to gather all the information you need to get started with the Android NDK. I will not get into details about installing the basic components but will focus on setting up the environment. So you will need some knowledge about working with Android.</p>
<p>You will need to download and install a couple of things. </p>
<h2>Eclipse</h2>
<p>I usually go with the Eclipse Classic version. It is available from <a href="http://www.eclipse.org/downloads/" title="eclipse.org" target="_blank">eclipse.org</a>. Installing Eclipse is simply just unpacking the downloaded file.</p>
<h2>Android SDK</h2>
<p>The SDK is located at <a href="http://developer.android.com/sdk/index.html" title="developer.android.com" target="_blank">developer.android.com</a> There is a really good installation guide at <a href="http://developer.android.com/sdk/installing.html" title="developer.android.com" target="_blank">developer.android.com</a></p>
<h2>Android NDK</h2>
<p>The NDK is located at <a href="http://developer.android.com/sdk/ndk/index.html" title="developer.android.com" target="_blank">developer.android.com</a> with an installation guide.</p>
<h2>Eclipse C/C++ Development Tools</h2>
<p>To make it a bit easier we also install the C/C++ Development Tools to get C/C++ support in Eclipse. From the 'Help' menu choose 'Install New Software...'<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_00.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_00-300x233.png" alt="" title="cdt_00" width="300" height="233" class="aligncenter size-medium wp-image-10467" /></a></center></p>
<p>From the drop down select the update site for your eclipse version, in my case Indigo.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_01.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_01-283x300.png" alt="" title="cdt_01" width="283" height="300" class="aligncenter size-medium wp-image-10468" /></a></center></p>
<p>Under 'Programming Languages' you will find 'C/C++ Development Tools'. Select it and click 'next' and follow the install instructions.</p>
<p><center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_02b.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/cdt_02b-283x300.png" alt="" title="cdt_02b" width="283" height="300" class="aligncenter size-medium wp-image-10509" /></a></center></p>
<h2>Getting started</h2>
<p>I will show you how to get started by making a small application called NDKSetup.</p>
<p>Create a new android project for this example I will call it NDKSetup.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Screen-shot-2011-10-13-at-4.44.09-PM-copy.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/Screen-shot-2011-10-13-at-4.44.09-PM-copy-194x300.png" alt="Project Wizard" title="Project Wizard" width="194" height="300" class="size-medium wp-image-10423" /></a></center></p>
<p>First thing we need to do is to create a new folder called 'jni'<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/jni-folder.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/jni-folder.png" alt="" title="jni-folder" width="258" height="266" class="aligncenter size-full wp-image-10431" /></a></center></p>
<p>The next thing we need to do is to setup Eclipse so we can build the JNI code. Click on the small down arrow on the external tool button and choose the 'External Tools Configuration...'.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_00.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_00-300x161.png" alt="" title="etc_00" width="300" height="161" class="aligncenter size-medium wp-image-10433" /></a></center></p>
<p>Mark the 'Program' and click on the 'new'-icon.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_01.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_01-272x300.png" alt="" title="etc_01" width="272" height="300" class="aligncenter size-medium wp-image-10435" /></a></center></p>
<p>Select a proper name.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_02.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_02-272x300.png" alt="" title="etc_02" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>Location is the location of the external tool you want to run, in our case the ndk-build file. Click on 'Browse file system...' and locate the ndk-build file located under your NDK folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_03.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_03-272x300.png" alt="" title="etc_03" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>The working directory is the jni folder we created in our project. Click on 'Browse Workspace...' ...<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04-272x300.png" alt="" title="etc_04" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>... and choose the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04b1.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_04b1-228x300.png" alt="" title="etc_04b" width="228" height="300" class="aligncenter size-medium wp-image-10443" /></a></center></p>
<p>You should now have something looking like this:<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_05.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/etc_05-272x300.png" alt="" title="etc_05" width="272" height="300" class="aligncenter size-medium wp-image-10437" /></a></center></p>
<p>Press run and you will get this error:</p>
<pre>/Users/uncle/ndk-setup/android-ndk-r6b/build/core/add-application.mk:118: *** Android NDK: Aborting...    .  Stop.
Android NDK: Your APP_BUILD_SCRIPT points to an unknown file: /Users/uncle/Workspaces/ndk-setup/NDKSetup/jni/Android.mk</pre>
<p>This means two things. Your setup to the ndk-build works and you are missing the Android.mk file.</p>
<p>Create a new file called Android.mk in the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/android-mk.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/android-mk.png" alt="" title="android-mk" width="260" height="268" class="aligncenter size-full wp-image-10451" /></a></center></p>
<p>In the Android.mk file write this:</p>
<pre class="c">LOCAL_PATH := $<span style="color: #66cc66;">&#40;</span>call my-dir<span style="color: #66cc66;">&#41;</span>
&nbsp;
include $<span style="color: #66cc66;">&#40;</span>CLEAR_VARS<span style="color: #66cc66;">&#41;</span>
&nbsp;
LOCAL_LDLIBS := -llog
&nbsp;
LOCAL_MODULE    := ndksetup
LOCAL_SRC_FILES := native.<span style="color: #202020;">c</span>
&nbsp;
include $<span style="color: #66cc66;">&#40;</span>BUILD_SHARED_LIBRARY<span style="color: #66cc66;">&#41;</span></pre>
<p>LOCAL_PATH := $(call my-dir)<br />
An Android.mk file must begin defining the LOCAL_PATH variable, this is where the source files are. The macro 'my-dir' is the path where the Android.mk file is located.</p>
<p>include $(CLEAR_VARS)<br />
Since all the building and parsing is done in the same context the variables called LOCAL_XXX is globals and need to be cleared.</p>
<p>LOCAL_MODULE := ndksetup<br />
This is where you set the name used as the identifier for each module. Later used in java when loading the module. The system will add 'lib' before the module name when compiling into the .so file. So ndksetup will become libndksetup.so. The only exception is if you add 'lib' first in your module name then the system will not add it.</p>
<p>LOCAL_SRC_FILES := native.c<br />
Here you add a list of the files you need to compile your module. You do not need to add headers or include files the system will take care of that for you.</p>
<p>include $(BUILD_SHARED_LIBRARY)<br />
The NDK provides you with two make files that parse and build everything accordingly to your Android.mk file. The two once are BUILD_STATIC_LIBRARY for building static library and BUILD_SHARED_LIBRARY for building shared library. </p>
<p>For the example project here we use the BUILD_SHARED_LIBRARY.</p>
<p>If you run the external tool "NDK Build" we get a new error:</p>
<pre>make: *** No rule to make target `/Users/uncle/Workspaces/ndk-setup/NDKSetup/jni/native.c', needed by `/Users/uncle/Workspaces/ndk-setup/NDKSetup/obj/local/armeabi/objs/ndksetup/native.o'.  Stop.</pre>
<p>So lets att the missing native.c file into the jni folder.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/native-c.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/native-c-221x300.png" alt="" title="native-c" width="221" height="300" class="aligncenter size-medium wp-image-10486" /></a></center></p>
<p>Before we start adding code to the native.c file I think it is easier to write the API starting from java. We start by adding the loading of the library.</p>
<pre java="java">static {
    System.loadLibrary("ndksetup"); // ndksetup is the LOCAL_MODULE string.
}</pre>
<p>We also need to define the function we are going to implement. By adding the keyword 'native' the system will know it is a function located in the native code.</p>
<pre java="java">private native void printLog(String logThis);</pre>
<p>Putting in all together give us this:</p>
<pre java="java">package com.jayway.ndksetup;

import android.app.Activity;
import android.os.Bundle;

public class NDKSetupActivity extends Activity {

    static {
        System.loadLibrary("ndksetup");
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        printLog("Hello!!!");
    }

    private native void printLog(String logThis);
}</pre>
<p>Back to the native.c file.</p>
<p>The name structure of the function is important. It is build from the java starting with a java identifier followed by the package name, followed by the class name, followed by the function name. This is one way of converting our java function into the native function. I usually do it by right clicking on the function name ( printLog ) and select 'Copy Qualified Name' paste it in the native.c file:</p>
<pre class="c">com.<span style="color: #202020;">jayway</span>.<span style="color: #202020;">ndksetup</span>.<span style="color: #202020;">NDKSetupActivity</span>.<span style="color: #202020;">printLog</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>Start by changing all dots (.) to underscores (_).</p>
<pre class="c">com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>Add the return value and a Java_ identifier to the function:</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">String</span><span style="color: #66cc66;">&#41;</span></pre>
<p>The input variable is a String in java so lets make it a java string in native as well.</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>jstring logString<span style="color: #66cc66;">&#41;</span></pre>
<p>The last thing we need to add is a reference to the JNI enviroment and a reference to java object that this function belongs to.</p>
<pre class="c"><span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jstring logString<span style="color: #66cc66;">&#41;</span></pre>
<p>Finally our first native function will look like this:</p>
<pre class="c"><span style="color: #339933;">#include &lt;jni.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
<span style="color: #339933;">#include &lt;android/log.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define DEBUG_TAG &quot;NDKSetupActivity&quot;</span>
&nbsp;
<span style="color: #993333;">void</span> Java_com_jayway_ndksetup_NDKSetupActivity_printLog<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jstring logString<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
    jboolean isCopy;
    <span style="color: #993333;">const</span> <span style="color: #993333;">char</span> * szLogString = <span style="color: #66cc66;">&#40;</span>*env<span style="color: #66cc66;">&#41;</span>-&gt;GetStringUTFChars<span style="color: #66cc66;">&#40;</span>env, logString, &amp;isCopy<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    __android_log_print<span style="color: #66cc66;">&#40;</span>ANDROID_LOG_DEBUG, DEBUG_TAG, <span style="color: #ff0000;">&quot;NDK: %s&quot;</span>, szLogString<span style="color: #66cc66;">&#41;</span>;
&nbsp;
    <span style="color: #66cc66;">&#40;</span>*env<span style="color: #66cc66;">&#41;</span>-&gt;ReleaseStringUTFChars<span style="color: #66cc66;">&#40;</span>env, logString, szLogString<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Just for fun we add another function, a fibonacci function.</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">int</span> fibonacci<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> value<span style="color: #66cc66;">&#41;</span>;</pre>
<pre class="c">jint Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>JNIEnv * env, jobject this, jint value<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>value &lt;= <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">return</span> value;
	<span style="color: #b1b100;">return</span> Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>env, this, value<span style="color: #cc66cc;">-1</span><span style="color: #66cc66;">&#41;</span>
            + Java_com_jayway_ndksetup_NDKSetupActivity_fibonacci<span style="color: #66cc66;">&#40;</span>env, this, value<span style="color: #cc66cc;">-2</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Now you are up and running with your NDK development for Android.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/13/getting-started-with-android-ndk/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Invoke any Method on any Thread</title>
		<link>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/</link>
		<comments>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 08:03:16 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9143</guid>
		<description><![CDATA[I previously wrote a blog post titled Performing any Selector on the Main Thread detailing a convenience category on NSInvoication for easily creating invocation objects that could be invoked on any thread. This category has served me well, and even got traction in the iOS developer community, so I never bothered to stop and think [...]]]></description>
			<content:encoded><![CDATA[<p>I previously wrote a blog post titled <a href="http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/">Performing any Selector on the Main Thread</a> detailing a convenience category on <code>NSInvoication</code> for easily creating invocation objects that could be invoked on any thread.</p>
<p>This category has served me well, and even got traction in the <a href="http://iphonedevelopment.blogspot.com/2010/08/nsoperation-file-template-notes.html">iOS developer community</a>, so I never bothered to stop and think if there exist an even better solution.</p>
<p>Especially now that GDC exists, and doing an inline block to invoke on the main thread or a background queue is easier than ever before.</p>
<h3>Until Today</h3>
<p>Traveling home by bus as usual I got a flash of genius; <i>Why not use proxy objects?</i> Calling a method on the main thread should be no harder then this;</p>
<pre class="brush:objc">[[self.slider mainThreadProxy] setValue:0.5f animated:YES];</pre>
<p>The old <code>NSInvocation</code> solutions have a few drawbacks. First of all there is no code completion for the arguments, secondly there is not even basic type checking, and lastly the implementation is quite ABI specific.</p>
<p>The <code>NSObject</code> class already has support for method forwarding, and wrapping method calls up into <code>NSInvocation</code> instances. Why not use seriously battle proven code that Apple provides.</p>
<h3>The Skeleton</h3>
<p>The implementation for <code>-[NSObject mainThreadProxy]</code> will be childishly simple:</p>
<pre class="brush:objc">-(id)mainThreadProxy;
{
    // Return self directly if already on main thread.
    if ([NSThread isMainThread]) {
        return self;
    } else {
        return [CWMainProxy proxyWithTarget:self];
    }
}</pre>
<p>The <code>CWMainProxy</code> class is a simple private helper, that will perform all of the heavy lifting. The interface and life time code is very small:</p>
<pre class="brush:objc">@interface CWMainProxy : NSObject {
    id _target;
}
+(id)proxyWithTarget:(id)target;
@end

@implementation CWMainProxy

+(id)proxyWithTarget:(id)target;
{
    CWMainProxy* proxy = [[[self alloc] init] autorelease];
    proxy->_target = [target retain];
    return proxy;
}

-(void)dealloc;
{
    [_target release];
    [super dealloc];
}
@end
</pre>
<h3>The Meaty Parts</h3>
<p>Now comes the tricky parts; actually act like a proxy. The proxy is a simple <code>NSObject</code> subclass, first it needs to be able to fake to any caller that it can respond to everything that the proxies target responds to.</p>
<pre class="brush:objc">-(BOOL)respondsToSelector:(SEL)sel;
{
    return [super respondsToSelector:sel] ||
           [_target respondsToSelector:sel];
}</pre>
<p>Next up if the object claims it responds to a selector but do not have an actual implementation, then we must provide a <code>NSMethodSignature</code> so the run-time can create a proper <code>NSInvocation</code> for us.</p>
<pre class="brush:objc">-(NSMethodSignature*)methodSignatureForSelector:(SEL)sel;
{
    if ([_target respondsToSelector:self) {
        return [_target methodSignatureForSelector:sel];
    } else {
        return [super methodSignatureForSelector:sel];
    }
}</pre>
<p>And finally we need to actually forward the <code>NSInvocation</code> call to the main thread, as per the callers request:</p>
<pre class="brush:objc">-(void)forwardInvocation:(NSInvocation*)invocation;
{
    [invocation performSelectorOnMainThread:@selector(invokeWithTarget:)
                                 withObject:_target
                              waitUntilDone:YES];
}</pre>
<h3>Conclusions</h3>
<p>Given some thought I regard this solution to be much more elegant than my old solution. And it even yields less and more readable code than using GCD on iOS 4 and later:</p>
<pre class="brush:objc">[[self.slider mainThreadProxy] setValue:0.5f animated:YES];
    // vs
dispatch_async(dispatch_get_main_queue(),
               ^{
                   [self.slider setValue:0.5f animated:YES];
               });</pre>
<ul>
<li>The implementation is much smaller, and relies on the Foundation framework functionality, not my own Objective-C ABI hacks.</li>
<li>It is less code to write to use the functionality.</li>
<li>Xcode can do proper code completion and basic type checking.</li>
<li>It is compatible all the way back to iPhone OS 2, or Mac OS X 10.0, <a href="http://www.cocoanetics.com/2011/08/ios-versions-in-the-wild/">if you should care</a>.
 </ul>
<p>The <a href="https://github.com/Jayway/CWFoundation">CWFoundation project on Github</a> has a more complete implementation. With more support for optional blocking, delays, and more proxies not only for the main thread but also for background threads and operations queue.</p>
<p>You are seldom alone with great ideas, so a nod to <a href="http://twitter.com/#!/nevyn">Joachim Bengtsson</a> who has written about an <a href="http://overooped.com/post/913725384/nsinvocation">invocation grabber</a> before.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Auto-incrementing Build Numbers in Xcode</title>
		<link>http://blog.jayway.com/2011/05/31/auto-incrementing-build-numbers-in-xcode/</link>
		<comments>http://blog.jayway.com/2011/05/31/auto-incrementing-build-numbers-in-xcode/#comments</comments>
		<pubDate>Tue, 31 May 2011 13:20:53 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8586</guid>
		<description><![CDATA[Users and testers will find bugs you are sure you have already fixed. Sometimes they use the wrong version, sometimes your fix is not as good as you thought. Either way a tiny unique version number visible in the app can save you hours of work. Incrementing the version number of your project for every [...]]]></description>
			<content:encoded><![CDATA[<p>Users and testers will find bugs you are sure you have already fixed. Sometimes they use the wrong version, sometimes your fix is not as good as you thought. Either way a tiny unique version number visible in the app can save you hours of work.</p>
<p>Incrementing the version number of your project for every small update is often not feasible, if it involves manual labor it just does not get done. Would it not be nice if Xcode just autoincremented a build number for you every time you build? </p>
<h3> This can be done</h3>
<p>There are dozens of solution to the problem available by Google. Unfortunately most do not work in both Xcode 3.2 and Xcode 4, and many more require a lot of hacking, even running external Perl or Python scripts. Using avgtool seems to be a major overkill for most use-cases. There must be an easier way, and there is.</p>
<p>What we want to do is to have the build number available in our Info.plist file, so that it can be read and displayed at run-time. And we also want Xcode to automatically increment this number for every build.</p>
<p>Add a key named <code>CWBuildNumber</code> to your Info.plist file, and set it to a sane start value, maybe "0". You can load it at run-time with a short statement like:</p>
<pre class="brush:objc">NSString* buildNumber = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CWBuildNumber"];</pre>
<p>Both Xcode 3.2 and Xcode 4 allows to add a <em>Run Script</em> phase to any target. Unfortunately Xcode 3.2 and 4 run these scripts with different paths. <code>PROJECT_DIR</code> environment variable to the rescue! Secondly we want to rewrite the target's source Info.plist file, not the file bundled with the application, so make sure to order the script phase before the <em>Copy Resources</em> phase. Then just add this tiny script phase to your target build:</p>
<pre class="brush:shell">buildNumber=$(/usr/libexec/PlistBuddy -c "Print CWBuildNumber" ${PROJECT_DIR}/MyApp-Info.plist)
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CWBuildNumber $buildNumber" ${PROJECT_DIR}/MyApp-Info.plist </pre>
<h3>Conclusions</h3>
<p>Happy developers, and happy tester. Maybe even happy users, if you choose to show the full version number including build number in the final product.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/31/auto-incrementing-build-numbers-in-xcode/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>A Not Very Short Introduction To Node.js</title>
		<link>http://blog.jayway.com/2011/05/15/a-not-very-short-introduction-to-node-js/</link>
		<comments>http://blog.jayway.com/2011/05/15/a-not-very-short-introduction-to-node-js/#comments</comments>
		<pubDate>Sun, 15 May 2011 08:04:15 +0000</pubDate>
		<dc:creator>Anders Janmyr</dc:creator>
				<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8393</guid>
		<description><![CDATA[Node.js is a set of asynchronous libraries, built on top of the Google V8 Javascript engine. Node is used for server side development in Javascript. Do you feel the rush of the 90's coming through your head. It is not the revival of LiveWire, Node is a different beast. Node is a single threaded process, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nodejs.org/">Node.js</a> is a set of asynchronous libraries, built on top of the <a href="http://code.google.com/p/v8/"> Google V8 Javascript engine</a>. Node is used for server side development in Javascript. Do you feel the rush of the 90's coming through your head. It is not the revival of <a href="http://docsrv.sco.com/INT_LiveWire/CONTENTS.html">LiveWire</a>, Node is a different beast. Node is a single threaded process, focused on doing networking right. Right, in this case, means without blocking I/O. </p>
<p>All the libraries built for Node use non-blocking I/O. This is a really cool feature, which allows the single thread in Node to serve thousands of request per second. It even lets you run multiple servers in the same thread. Check out the performance characteristics of Nginx and Apache that utilize the same technique.</p>
<p><img src="http://www.webfaction.com/blog/nginx-apache-reqs-sec.png" title="Concurrency x Requests" alt="Concurrency x Requests" /></p>
<p>The graph for memory usage is even better.</p>
<p><img src="http://www.webfaction.com/blog/nginx-apache-memory.png" title="Concurrency x Memory" alt="Concurrency x Memory" /></p>
<p>Read more about it at the <a href="http://blog.webfaction.com/a-little-holiday-present">Web Faction Blog</a></p>
<p>OK, so what's the catch? The catch is that all code that does I/O, or<br />
anything slow at all, has to be called in an asynchronous style.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// Synchronous</font></i>
<b><font color="#0000FF">var</font></b> result <font color="#990000">=</font> db<font color="#990000">.</font><b><font color="#000000">query</font></b><font color="#990000">(</font><font color="#FF0000">"select * from T"</font><font color="#990000">);</font>
<i><font color="#9A1900">// Use result</font></i> 

<i><font color="#9A1900">// Asynchronous</font></i>
db<font color="#990000">.</font><b><font color="#000000">query</font></b><font color="#990000">(</font><font color="#FF0000">"select * from T"</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b> <font color="#990000">(</font>result<font color="#990000">)</font> <font color="#FF0000">{</font>
    <i><font color="#9A1900">// Use result</font></i>
<font color="#FF0000">}</font><font color="#990000">);</font>
</tt></pre>
<p>So, all libraries that deal with IO has to be re-implemented with this<br />
style of programming. The good news is that even though Node has only<br />
been around for a couple of years, there are more than 1800 libraries<br />
available. The libraries are of varying quality but the popularity of<br />
Node shows good promise to deliver high-quality libraries for anything<br />
that you can imagine.</p>
<h2>History</h2>
<p>Node is definitely not the first of its kind. The non-blocking<br />
<code>select()</code> loop, that is at the heart of Node, dates back to 1983.</p>
<p><a href="http://twistedmatrix.com/trac/">Twisted</a> appeared in Python (2002) and <a href="http://rubyeventmachine.com/">EventMachine</a> in Ruby (2003).</p>
<p>This year a couple of newcomers appeared.</p>
<p><a href="http://postrank-labs.github.com/goliath/">Goliath</a>, which builds on EventMachine, and uses fibers to allow us to program in an synchronous style even though it is asynchronous under the hood.</p>
<p>And, the <a href="http://msdn.microsoft.com/en-us/vstudio/gg316360">Async Framework in<br />
.Net</a>, which enhances the compiler with the keywords <code>async</code> and <code>await</code> to allow for very elegant asynchronous programming.</p>
<h2>Get Started</h2>
<p>This example uses OSX as an example platform, if you use something else<br />
you will have to google for instructions.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900"># Install Node using Homebrew</font></i>
$ brew install node
<font color="#990000">==&gt;</font> Downloading http<font color="#990000">:</font>//nodejs<font color="#990000">.</font>org/dist/node-v<font color="#993399">0.4</font><font color="#990000">.</font><font color="#993399">7</font><font color="#990000">.</font>tar<font color="#990000">.</font>gz
<i><font color="#9A1900">######################################################################## 100.0%</font></i>
<font color="#990000">==&gt;</font> <font color="#990000">.</font>/configure --prefix<font color="#990000">=</font>/usr/local/Cellar/node<font color="#990000">/</font><font color="#993399">0.4</font><font color="#990000">.</font><font color="#993399">7</font>
<font color="#990000">==&gt;</font> make install
<font color="#990000">==&gt;</font> Caveats
Please add /usr/local/lib/node to your NODE_PATH environment variable to have node libraries picked up<font color="#990000">.</font>
<font color="#990000">==&gt;</font> Summary
/usr/local/Cellar/node<font color="#990000">/</font><font color="#993399">0.4</font><font color="#990000">.</font><font color="#993399">7</font><font color="#990000">:</font> <font color="#993399">72</font> files<font color="#990000">,</font> <font color="#993399">7</font><font color="#990000">.</font>5M<font color="#990000">,</font> built <b><font color="#0000FF">in</font></b> <font color="#993399">1.2</font> minutes
</tt></pre>
<p>When installed you have access to the <code>node</code> command-line command. When<br />
invoked without arguments, it start a REPL.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ node
<font color="#990000">&gt;</font> <b><font color="#000000">function hello</font></b><font color="#990000">(</font>name<font color="#990000">)</font> {
<font color="#990000">...</font> <b><font color="#0000FF">return</font></b> <font color="#FF0000">'hello '</font> <font color="#990000">+</font> name<font color="#990000">;</font>
<font color="#990000">...</font> }
<font color="#990000">&gt;</font> hello<font color="#990000">(</font><font color="#FF0000">'tapir'</font><font color="#990000">)</font>
<font color="#FF0000">'hello tapir'</font>
<font color="#990000">&gt;</font>
</tt></pre>
<p>When invoked with a script it runs the script.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// hello.js</font></i>
<b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
    console<font color="#990000">.</font><b><font color="#000000">log</font></b><font color="#990000">(</font><font color="#FF0000">'Tapir'</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">,</font> <font color="#993399">2000</font><font color="#990000">);</font>
console<font color="#990000">.</font><b><font color="#000000">log</font></b><font color="#990000">(</font><font color="#FF0000">'Hello'</font><font color="#990000">);</font> 

</tt></pre>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ node hello<font color="#990000">.</font>js
Hello
<font color="#990000">...</font>
Tapir
</tt></pre>
<h2>Networking</h2>
<p>As I mentioned above, Node is focused on networking. That means it<br />
should be easy to write networking code. Here is a simple echo server.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// Echo Server</font></i>
<b><font color="#0000FF">var</font></b> net <font color="#990000">=</font> <b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'net'</font><font color="#990000">);</font> 

<b><font color="#0000FF">var</font></b> server <font color="#990000">=</font> net<font color="#990000">.</font><b><font color="#000000">createServer</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">(</font>socket<font color="#990000">)</font> <font color="#FF0000">{</font>
    socket<font color="#990000">.</font><b><font color="#000000">on</font></b><font color="#990000">(</font><font color="#FF0000">'data'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>data<font color="#990000">)</font> <font color="#FF0000">{</font>
        console<font color="#990000">.</font><b><font color="#000000">log</font></b><font color="#990000">(</font>data<font color="#990000">.</font><b><font color="#000000">toString</font></b><font color="#990000">());</font>
        socket<font color="#990000">.</font><b><font color="#000000">write</font></b><font color="#990000">(</font>data<font color="#990000">);</font>
    <font color="#FF0000">}</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">);</font>
server<font color="#990000">.</font><b><font color="#000000">listen</font></b><font color="#990000">(</font><font color="#993399">4000</font><font color="#990000">);</font> 

</tt></pre>
<p>And here is a simple HTTP server.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// HTTP Server</font></i>
<b><font color="#0000FF">var</font></b> http <font color="#990000">=</font> <b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'http'</font><font color="#990000">);</font>
<b><font color="#0000FF">var</font></b> web <font color="#990000">=</font> http<font color="#990000">.</font><b><font color="#000000">createServer</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">(</font>request<font color="#990000">,</font> response<font color="#990000">)</font> <font color="#FF0000">{</font>
  response<font color="#990000">.</font><b><font color="#000000">writeHead</font></b><font color="#990000">(</font><font color="#993399">200</font><font color="#990000">,</font> <font color="#FF0000">{</font>
    <font color="#FF0000">'Content-Type'</font><font color="#990000">:</font> <font color="#FF0000">'text/plain'</font>
  <font color="#FF0000">}</font><font color="#990000">);</font>
  response<font color="#990000">.</font><b><font color="#000000">end</font></b><font color="#990000">(</font><font color="#FF0000">'Tapirs are beautiful!</font><font color="#CC33CC">\n</font><font color="#FF0000">'</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">);</font>
web<font color="#990000">.</font><b><font color="#000000">listen</font></b><font color="#990000">(</font><font color="#993399">4001</font><font color="#990000">);</font> 

</tt></pre>
<p>Quite similar. A cool thing is that the servers can be started from the<br />
same file and node will, happily, serve both HTTP and echo requests from<br />
the same thread without any problems. Let's try them out!</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900"># curl the http service</font></i>
$ curl localhost<font color="#990000">:</font><font color="#993399">4001</font>
Tapirs are beautiful<font color="#990000">!</font> 

<i><font color="#9A1900"># use netcat to send the string to the echo server</font></i>
$ echo <font color="#FF0000">'Hello beautiful tapir'</font> <font color="#990000">|</font> nc localhost <font color="#993399">4000</font>
Hello beautiful tapir

</tt></pre>
<h2>Modules</h2>
<p>Node comes with a selection of built in modules. Ryan Dahl says that<br />
they try to keep the core small, but even so the built-in modules cover<br />
a lot of useful functionality.</p>
<ul>
<li>net - contains tcp/ip related networking functionality.</li>
<li>http - contains functionality for dealing with the HTTP protocol.</li>
<li>util - holds common utility functions, such as log, inherits, pump,<br />
...</li>
<li>fs - contains filesystem related functionality, remember that<br />
everything should be asynchronous.</li>
<li>events - contains the EventEmitter that is used for dealing with<br />
events in a consistent way. It is used internally but it can be used<br />
externally too.</li>
</ul>
<h3>An example</h3>
<p>Here is an example of a simple module.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// module tapir.js</font></i> 

<i><font color="#9A1900">// require another module</font></i>
<b><font color="#0000FF">var</font></b> util <font color="#990000">=</font> <b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'util'</font><font color="#990000">);</font> 

<b><font color="#0000FF">function</font></b> <b><font color="#000000">eat</font></b><font color="#990000">(</font>food<font color="#990000">)</font> <font color="#FF0000">{</font>
  util<font color="#990000">.</font><b><font color="#000000">log</font></b><font color="#990000">(</font><font color="#FF0000">'eating '</font><font color="#990000">+</font> food<font color="#990000">);</font>
<font color="#FF0000">}</font> 

<i><font color="#9A1900">// export a function</font></i>
exports<font color="#990000">.</font>eat <font color="#990000">=</font> eat<font color="#990000">;</font> 

</tt></pre>
<p>As you can see it looks like a normal Javascript file and it even looks<br />
like it has global variables. It doesn't. When a module is loaded it is<br />
wrapped in code, similar to this.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><b><font color="#0000FF">var</font></b> module <font color="#990000">=</font> <font color="#FF0000">{</font> exports<font color="#990000">:</font> <font color="#FF0000">{}}</font><font color="#990000">;</font>
<font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">(</font>module<font color="#990000">,</font> exports<font color="#990000">)</font><font color="#FF0000">{</font>
  <i><font color="#9A1900">// module code from file</font></i>
  <font color="#990000">...</font>
<font color="#FF0000">}</font><font color="#990000">)(</font>module<font color="#990000">,</font> module<font color="#990000">.</font>exports<font color="#990000">);</font> 

</tt></pre>
<p>As you can see the code is wrapped in a function and an empty object<br />
with an <code>export</code> property is sent into it. This is used by the file to<br />
export only the functions that it want to publish.</p>
<p>The <code>require</code> function works in symphony with the module and it returns<br />
the exported functions to the caller.</p>
<h3>Node Package Manager, npm</h3>
<p>To allow simple handling of third-party packages, Node uses <code>npm</code>. It<br />
can be installed like this:</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ curl http<font color="#990000">:</font>//npmjs<font color="#990000">.</font>org/install<font color="#990000">.</font>sh <font color="#990000">|</font> sh
<font color="#990000">...</font> 

</tt></pre>
<p>And used like this:</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ npm install -g express
mime@<font color="#993399">1.2</font><font color="#990000">.</font><font color="#993399">1</font> /usr/local/lib/node_modules/express/node_modules/mime
connect@<font color="#993399">1.4</font><font color="#990000">.</font><font color="#993399">0</font> /usr/local/lib/node_modules/express/node_modules/connect
qs@<font color="#993399">0.1</font><font color="#990000">.</font><font color="#993399">0</font> /usr/local/lib/node_modules/express/node_modules/qs
/usr/local/bin/express -<font color="#990000">&gt;</font> /usr/local/lib/node_modules/express/bin/express
express@<font color="#993399">2.3</font><font color="#990000">.</font><font color="#993399">2</font> /usr/local/lib/node_modules/express

</tt></pre>
<p>As you can see, installing a module also installs its dependencies. This<br />
works because a module can be package with meta-data, like so:</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// express/package.json</font></i>
<font color="#FF0000">{</font>
  <font color="#FF0000">"name"</font><font color="#990000">:</font> <font color="#FF0000">"express"</font><font color="#990000">,</font>
  <font color="#FF0000">"description"</font><font color="#990000">:</font> <font color="#FF0000">"Sinatra inspired web development framework"</font><font color="#990000">,</font>
  <font color="#FF0000">"version"</font><font color="#990000">:</font> <font color="#FF0000">"2.3.2"</font><font color="#990000">,</font>
  <font color="#FF0000">"author"</font><font color="#990000">:</font> <font color="#FF0000">"TJ Holowaychuk &lt;tj@vision-media.ca&gt;"</font><font color="#990000">,</font>
  <font color="#FF0000">"contributors"</font><font color="#990000">:</font> <font color="#990000">[</font>
    <font color="#FF0000">{</font> <font color="#FF0000">"name"</font><font color="#990000">:</font> <font color="#FF0000">"TJ Holowaychuk"</font><font color="#990000">,</font> <font color="#FF0000">"email"</font><font color="#990000">:</font> <font color="#FF0000">"tj@vision-media.ca"</font> <font color="#FF0000">}</font><font color="#990000">,</font>
    <font color="#FF0000">{</font> <font color="#FF0000">"name"</font><font color="#990000">:</font> <font color="#FF0000">"Guillermo Rauch"</font><font color="#990000">,</font> <font color="#FF0000">"email"</font><font color="#990000">:</font> <font color="#FF0000">"rauchg@gmail.com"</font> <font color="#FF0000">}</font>
  <font color="#990000">],</font>
  <font color="#FF0000">"dependencies"</font><font color="#990000">:</font> <font color="#FF0000">{</font>
    <font color="#FF0000">"connect"</font><font color="#990000">:</font> <font color="#FF0000">"&gt;= 1.4.0 &lt; 2.0.0"</font><font color="#990000">,</font>
    <font color="#FF0000">"mime"</font><font color="#990000">:</font> <font color="#FF0000">"&gt;= 0.0.1"</font><font color="#990000">,</font>
    <font color="#FF0000">"qs"</font><font color="#990000">:</font> <font color="#FF0000">"&gt;= 0.0.6"</font>
  <font color="#FF0000">}</font><font color="#990000">,</font>
  <font color="#FF0000">"keywords"</font><font color="#990000">:</font> <font color="#990000">[</font><font color="#FF0000">"framework"</font><font color="#990000">,</font> <font color="#FF0000">"sinatra"</font><font color="#990000">,</font> <font color="#FF0000">"web"</font><font color="#990000">,</font> <font color="#FF0000">"rest"</font><font color="#990000">,</font> <font color="#FF0000">"restful"</font><font color="#990000">],</font>
  <font color="#FF0000">"repository"</font><font color="#990000">:</font> <font color="#FF0000">"git://github.com/visionmedia/express"</font><font color="#990000">,</font>
  <font color="#FF0000">"main"</font><font color="#990000">:</font> <font color="#FF0000">"index"</font><font color="#990000">,</font>
  <font color="#FF0000">"bin"</font><font color="#990000">:</font> <font color="#FF0000">{</font> <font color="#FF0000">"express"</font><font color="#990000">:</font> <font color="#FF0000">"./bin/express"</font> <font color="#FF0000">}</font><font color="#990000">,</font>
  <font color="#FF0000">"engines"</font><font color="#990000">:</font> <font color="#FF0000">{</font> <font color="#FF0000">"node"</font><font color="#990000">:</font> <font color="#FF0000">"&gt;= 0.4.1 &lt; 0.5.0"</font> <font color="#FF0000">}</font>
<font color="#FF0000">}</font> 

</tt></pre>
<p>The <code>package.json</code> contains information about who made the module, its<br />
dependencies, along with some additional information to enable better<br />
searching facilities.</p>
<p>Npm installs the modules from <a href="http://npm.mape.me/">a common<br />
respository</a>, which contains more than 1800<br />
modules.</p>
<h3>Noteworthy Modules</h3>
<p><em>Express</em> is probably the most used of all third-party modules. It is<br />
a Sinatra clone and it is very good, just like Sinatra.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// Create a server</font></i>
<b><font color="#0000FF">var</font></b> app <font color="#990000">=</font> express<font color="#990000">.</font><b><font color="#000000">createServer</font></b><font color="#990000">();</font>
app<font color="#990000">.</font><b><font color="#000000">listen</font></b><font color="#990000">(</font><font color="#993399">4000</font><font color="#990000">);</font> 

<i><font color="#9A1900">// Mount the root (/) and redirect to index</font></i>
app<font color="#990000">.</font><b><font color="#000000">get</font></b><font color="#990000">(</font><font color="#FF0000">'/'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>req<font color="#990000">,</font> res<font color="#990000">)</font> <font color="#FF0000">{</font>
  res<font color="#990000">.</font><b><font color="#000000">redirect</font></b><font color="#990000">(</font><font color="#FF0000">'/index.html'</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">);</font> 

<i><font color="#9A1900">// Handle a post to /quiz</font></i>
app<font color="#990000">.</font><b><font color="#000000">post</font></b><font color="#990000">(</font><font color="#FF0000">'/quiz'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>req<font color="#990000">,</font> res<font color="#990000">)</font> <font color="#FF0000">{</font>
  res<font color="#990000">.</font><b><font color="#000000">send</font></b><font color="#990000">(</font>quiz<font color="#990000">.</font><b><font color="#000000">create</font></b><font color="#990000">().</font>id<font color="#990000">.</font><b><font color="#000000">toString</font></b><font color="#990000">());</font>
<font color="#FF0000">}</font><font color="#990000">);</font>
</tt></pre>
<p>Express uses <em>Connect</em> to handle middleware. Middleware is like Rack<br />
but for Node (No wonder that Node is nice to work with when it borrows<br />
its ideas from Ruby <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><b><font color="#000000">connect</font></b><font color="#990000">(</font>
      <i><font color="#9A1900">// Add a logger</font></i>
      connect<font color="#990000">.</font><b><font color="#000000">logger</font></b><font color="#990000">()</font>
      <i><font color="#9A1900">// Serve static file from the current directory</font></i>
    <font color="#990000">,</font> connect<font color="#990000">.</font><b><font color="#0000FF">static</font></b><font color="#990000">(</font>__dirname<font color="#990000">)</font>
      <i><font color="#9A1900">// Compile Sass and Coffescript files, on the fly</font></i>
    <font color="#990000">,</font> connect<font color="#990000">.</font><b><font color="#000000">compiler</font></b><font color="#990000">(</font><font color="#FF0000">{</font>enable<font color="#990000">:</font> <font color="#990000">[</font><font color="#FF0000">'sass'</font><font color="#990000">,</font> <font color="#FF0000">'coffeescript'</font><font color="#990000">]</font><font color="#FF0000">}</font><font color="#990000">)</font>
      <i><font color="#9A1900">// Profile all requests</font></i>
    <font color="#990000">,</font> connect<font color="#990000">.</font><b><font color="#000000">profiler</font></b><font color="#990000">()</font>
  <font color="#990000">).</font><b><font color="#000000">listen</font></b><font color="#990000">(</font><font color="#993399">3000</font><font color="#990000">);</font>
</tt></pre>
<p>Another popular library is <em>Socket.IO</em>. It handles the usual socket<br />
variants, such as WebSocket, Comet, Flash Sockets, etc...</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><b><font color="#0000FF">var</font></b> http <font color="#990000">=</font> <b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'http'</font><font color="#990000">);</font>
<b><font color="#0000FF">var</font></b> io <font color="#990000">=</font> <b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'socket.io'</font><font color="#990000">);</font> 

server <font color="#990000">=</font> http<font color="#990000">.</font><b><font color="#000000">createServer</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">(</font>req<font color="#990000">,</font> res<font color="#990000">)</font><font color="#FF0000">{</font><font color="#990000">...</font><font color="#FF0000">}</font><font color="#990000">);</font>
server<font color="#990000">.</font><b><font color="#000000">listen</font></b><font color="#990000">(</font><font color="#993399">80</font><font color="#990000">);</font> 

<i><font color="#9A1900">// socket.io attaches to an existing server</font></i>
<b><font color="#0000FF">var</font></b> socket <font color="#990000">=</font> io<font color="#990000">.</font><b><font color="#000000">listen</font></b><font color="#990000">(</font>server<font color="#990000">);</font>
socket<font color="#990000">.</font><b><font color="#000000">on</font></b><font color="#990000">(</font><font color="#FF0000">'connection'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>client<font color="#990000">)</font><font color="#FF0000">{</font>
  <i><font color="#9A1900">// new client is here!</font></i>
  client<font color="#990000">.</font><b><font color="#000000">on</font></b><font color="#990000">(</font><font color="#FF0000">'message'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">()</font><font color="#FF0000">{</font> ... <font color="#FF0000">}</font><font color="#990000">)</font>
  client<font color="#990000">.</font><b><font color="#000000">on</font></b><font color="#990000">(</font><font color="#FF0000">'disconnect'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">()</font><font color="#FF0000">{</font> ... <font color="#FF0000">}</font><font color="#990000">)</font>
<font color="#FF0000">}</font><font color="#990000">);</font>
</tt></pre>
<p><em>MySql</em> has a library for Node.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>client<font color="#990000">.</font><b><font color="#000000">query</font></b><font color="#990000">(</font>
  <font color="#FF0000">'SELECT * FROM '</font> <font color="#990000">+</font> TEST_TABLE<font color="#990000">,</font>
  <i><font color="#9A1900">// Note the callback style</font></i>
  <b><font color="#0000FF">function</font></b><font color="#990000">(</font>err<font color="#990000">,</font> results<font color="#990000">,</font> fields<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>err<font color="#990000">)</font> <font color="#FF0000">{</font> <b><font color="#0000FF">throw</font></b> err<font color="#990000">;</font> <font color="#FF0000">}</font> 

    console<font color="#990000">.</font><b><font color="#000000">log</font></b><font color="#990000">(</font>results<font color="#990000">);</font>
    console<font color="#990000">.</font><b><font color="#000000">log</font></b><font color="#990000">(</font>fields<font color="#990000">);</font>
    client<font color="#990000">.</font><b><font color="#000000">end</font></b><font color="#990000">();</font>
  <font color="#FF0000">}</font>
<font color="#990000">);</font>
</tt></pre>
<p>And <em>Mongoose</em> can be used for accessing MongoDB.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// Declare the schema</font></i>
<b><font color="#0000FF">var</font></b> Schema <font color="#990000">=</font> mongoose<font color="#990000">.</font>Schema
  <font color="#990000">,</font> ObjectId <font color="#990000">=</font> Schema<font color="#990000">.</font>ObjectId<font color="#990000">;</font> 

<b><font color="#0000FF">var</font></b> BlogPost <font color="#990000">=</font> <b><font color="#0000FF">new</font></b> <b><font color="#000000">Schema</font></b><font color="#990000">(</font><font color="#FF0000">{</font>
    author    <font color="#990000">:</font> ObjectId
  <font color="#990000">,</font> title     <font color="#990000">:</font> String
  <font color="#990000">,</font> body      <font color="#990000">:</font> String
  <font color="#990000">,</font> date      <font color="#990000">:</font> Date
<font color="#FF0000">}</font><font color="#990000">);</font> 

<i><font color="#9A1900">// Use it</font></i>
<b><font color="#0000FF">var</font></b> BlogPost <font color="#990000">=</font> mongoose<font color="#990000">.</font><b><font color="#000000">model</font></b><font color="#990000">(</font><font color="#FF0000">'BlogPost'</font><font color="#990000">);</font> 

<i><font color="#9A1900">// Save</font></i>
<b><font color="#0000FF">var</font></b> post <font color="#990000">=</font> <b><font color="#0000FF">new</font></b> <b><font color="#000000">BlogPost</font></b><font color="#990000">();</font>
post<font color="#990000">.</font>author <font color="#990000">=</font> <font color="#FF0000">'Stravinsky'</font><font color="#990000">;</font>
instance<font color="#990000">.</font><b><font color="#000000">save</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b> <font color="#990000">(</font>err<font color="#990000">)</font> <font color="#FF0000">{</font>
  <i><font color="#9A1900">//</font></i>
<font color="#FF0000">}</font><font color="#990000">);</font> 

<i><font color="#9A1900">// Find</font></i>
BlogPost<font color="#990000">.</font><b><font color="#000000">find</font></b><font color="#990000">(</font><font color="#FF0000">{}</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b> <font color="#990000">(</font>err<font color="#990000">,</font> docs<font color="#990000">)</font> <font color="#FF0000">{</font>
  <i><font color="#9A1900">// docs.forEach</font></i>
<font color="#FF0000">}</font><font color="#990000">);</font>
</tt></pre>
<h3>Templating Engines</h3>
<p>Everytime a new platform makes its presence, it brings along a couple of<br />
new templating languages and Node is no different. Along with the<br />
popular ones from the Ruby world, like Haml and Erb (EJS in Node),<br />
comes some new ones like Jade and some browser templating languages like<br />
Mustache and jQuery templates. I'll show examples of Jade and Mu<br />
(Mustache for Node).</p>
<p>I like <em>Jade</em>, because it is a Javascript dialect of Haml and it seems<br />
appropriate to use if I'm using Javascript on the server side.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><font color="#990000">!!!</font> <font color="#993399">5</font>
<b><font color="#000000">html</font></b><font color="#990000">(</font>lang<font color="#990000">=</font><font color="#FF0000">"en"</font><font color="#990000">)</font>
  head
    title<font color="#990000">=</font> pageTitle
    <b><font color="#000000">script</font></b><font color="#990000">(</font>type<font color="#990000">=</font><font color="#FF0000">'text/javascript'</font><font color="#990000">)</font>
      <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>foo<font color="#990000">)</font> <font color="#990000">{</font>
        <b><font color="#000000">bar</font></b><font color="#990000">()</font>
      <font color="#990000">}</font>
  body
    h1 Jade <font color="#990000">-</font> node template engine
    <i><font color="#9A1900">#container</font></i>
      <font color="#990000">-</font> <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>youAreUsingJade<font color="#990000">)</font>
        p You are amazing
      <font color="#990000">-</font> <b><font color="#0000FF">else</font></b>
        p Get on it<font color="#990000">!</font>
</tt></pre>
<p>I'm not really sure if I like Mustache or not, but I can surely see the<br />
value of having a templating language which works both on the server side<br />
and in the browser.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><b><font color="#0000FF">&lt;h1&gt;</font></b>{{header}}<b><font color="#0000FF">&lt;/h1&gt;</font></b>
{{#bug}}
{{/bug}}

{{#items}}
  {{#first}}
    <b><font color="#0000FF">&lt;li&gt;&lt;strong&gt;</font></b>{{name}}<b><font color="#0000FF">&lt;/strong&gt;&lt;/li&gt;</font></b>
  {{/first}}
  {{#link}}
    <b><font color="#0000FF">&lt;li&gt;&lt;a</font></b> <font color="#009900">href</font><font color="#990000">=</font><font color="#FF0000">"{{url}}"</font><b><font color="#0000FF">&gt;</font></b>{{name}}<b><font color="#0000FF">&lt;/a&gt;&lt;/li&gt;</font></b>
  {{/link}}
{{/items}}

{{#empty}}
  <b><font color="#0000FF">&lt;p&gt;</font></b>The list is empty.<b><font color="#0000FF">&lt;/p&gt;</font></b>
{{/empty}}
</tt></pre>
<h2>Testing</h2>
<p>Node comes with assertions built in, and all testing frameworks build on<br />
the Assert module, so it is good to know.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>assert<font color="#990000">.</font><b><font color="#000000">ok</font></b><font color="#990000">(</font>value<font color="#990000">,</font> <font color="#990000">[</font>message<font color="#990000">]);</font>
assert<font color="#990000">.</font><b><font color="#000000">equal</font></b><font color="#990000">(</font>actual<font color="#990000">,</font> expected<font color="#990000">,</font> <font color="#990000">[</font>message<font color="#990000">])</font>
assert<font color="#990000">.</font><b><font color="#000000">notEqual</font></b><font color="#990000">(</font>actual<font color="#990000">,</font> expected<font color="#990000">,</font> <font color="#990000">[</font>message<font color="#990000">])</font>
assert<font color="#990000">.</font><b><font color="#000000">deepEqual</font></b><font color="#990000">(</font>actual<font color="#990000">,</font> expected<font color="#990000">,</font> <font color="#990000">[</font>message<font color="#990000">])</font>
assert<font color="#990000">.</font><b><font color="#000000">strictEqual</font></b><font color="#990000">(</font>actual<font color="#990000">,</font> expected<font color="#990000">,</font> <font color="#990000">[</font>message<font color="#990000">])</font>
assert<font color="#990000">.</font><b><font color="#0000FF">throws</font></b><font color="#990000">(</font>block<font color="#990000">,</font> <font color="#990000">[</font>error<font color="#990000">],</font> <font color="#990000">[</font>message<font color="#990000">])</font>
assert<font color="#990000">.</font><b><font color="#000000">doesNotThrow</font></b><font color="#990000">(</font>block<font color="#990000">,</font> <font color="#990000">[</font>error<font color="#990000">],</font> <font color="#990000">[</font>message<font color="#990000">])</font>
assert<font color="#990000">.</font><b><font color="#000000">ifError</font></b><font color="#990000">(</font>value<font color="#990000">)</font>
assert<font color="#990000">.</font><b><font color="#000000">fail</font></b><font color="#990000">(</font>actual<font color="#990000">,</font> expected<font color="#990000">,</font> message<font color="#990000">,</font> operator<font color="#990000">)</font> 

<i><font color="#9A1900">// Example</font></i>
<i><font color="#9A1900">// assert.throws(function, regexp)</font></i>
assert<font color="#990000">.</font><b><font color="#0000FF">throws</font></b><font color="#990000">(</font>
  <b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font> <b><font color="#0000FF">throw</font></b> <b><font color="#0000FF">new</font></b> <b><font color="#000000">Error</font></b><font color="#990000">(</font><font color="#FF0000">"Wrong value"</font><font color="#990000">);</font> <font color="#FF0000">}</font><font color="#990000">,</font>
  <font color="#FF6600">/value/</font>
<font color="#990000">);</font>
</tt></pre>
<p>Apart from that there are at least 30 different testing frameworks to<br />
use. I have chosen to use NodeUnit since I find that it handles<br />
asynchronous testing well, and it has a nice UTF-8 output that looks<br />
good in the terminal,</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// ./test/test-doubled.js</font></i>
<b><font color="#0000FF">var</font></b> doubled <font color="#990000">=</font> <b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'../lib/doubled'</font><font color="#990000">);</font> 

<i><font color="#9A1900">// Exported functions are run by the test runner</font></i>
exports<font color="#990000">[</font><font color="#FF0000">'calculate'</font><font color="#990000">]</font> <font color="#990000">=</font> <b><font color="#0000FF">function</font></b> <font color="#990000">(</font>test<font color="#990000">)</font> <font color="#FF0000">{</font>
    test<font color="#990000">.</font><b><font color="#000000">equal</font></b><font color="#990000">(</font>doubled<font color="#990000">.</font><b><font color="#000000">calculate</font></b><font color="#990000">(</font><font color="#993399">2</font><font color="#990000">),</font> <font color="#993399">4</font><font color="#990000">);</font>
    test<font color="#990000">.</font><b><font color="#000000">done</font></b><font color="#990000">();</font>
<font color="#FF0000">}</font><font color="#990000">;</font> 

<i><font color="#9A1900">// An asynchronous test</font></i>
exports<font color="#990000">[</font><font color="#FF0000">'read a number'</font><font color="#990000">]</font> <font color="#990000">=</font> <b><font color="#0000FF">function</font></b> <font color="#990000">(</font>test<font color="#990000">)</font> <font color="#FF0000">{</font>
    test<font color="#990000">.</font><b><font color="#000000">expect</font></b><font color="#990000">(</font><font color="#993399">1</font><font color="#990000">);</font> <i><font color="#9A1900">// Make sure the assertion is run</font></i> 

    <b><font color="#0000FF">var</font></b> ev <font color="#990000">=</font> <b><font color="#0000FF">new</font></b> events<font color="#990000">.</font><b><font color="#000000">EventEmitter</font></b><font color="#990000">();</font>
    process<font color="#990000">.</font>openStdin <font color="#990000">=</font> <b><font color="#0000FF">function</font></b> <font color="#990000">()</font> <font color="#FF0000">{</font> <b><font color="#0000FF">return</font></b> ev<font color="#990000">;</font> <font color="#FF0000">}</font><font color="#990000">;</font>
    process<font color="#990000">.</font>exit <font color="#990000">=</font> test<font color="#990000">.</font>done<font color="#990000">;</font> 

    console<font color="#990000">.</font>log <font color="#990000">=</font> <b><font color="#0000FF">function</font></b> <font color="#990000">(</font>str<font color="#990000">)</font> <font color="#FF0000">{</font>
        test<font color="#990000">.</font><b><font color="#000000">equal</font></b><font color="#990000">(</font>str<font color="#990000">,</font> <font color="#FF0000">'Doubled: 24'</font><font color="#990000">);</font>
    <font color="#FF0000">}</font><font color="#990000">;</font> 

    doubled<font color="#990000">.</font><b><font color="#000000">read</font></b><font color="#990000">();</font>
    ev<font color="#990000">.</font><b><font color="#000000">emit</font></b><font color="#990000">(</font><font color="#FF0000">'data'</font><font color="#990000">,</font> <font color="#FF0000">'12'</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">;</font> 

</tt></pre>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/nodeunit.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/nodeunit.png" alt="" title="nodeunit" width="245" height="156" class="aligncenter size-full wp-image-8395" /></a></p>
<h2>Deployment</h2>
<p>There are already a lot of platforms providing Node as a service (PaaS<br />
, Platform as a Service). Most of them are using<br />
<a href="http://heroku.com">Heroku</a> style deployment by pushing to a Git remote.<br />
I'll show three alternatives that all provide free Node hosting.</p>
<h3>Joyent (no.de)</h3>
<p>Joyent, the employers of Ryan Dahl, give you <code>ssh</code> access so that you<br />
can install the modules you need. Deployment is done by pushing to<br />
a Git remote.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ ssh node@my-machine<font color="#990000">.</font>no<font color="#990000">.</font>de
$ nmp install express
$ git remote add node node@andersjanmyr<font color="#990000">.</font>no<font color="#990000">.</font>de<font color="#990000">:</font>repo
$ git push node master
Counting objects<font color="#990000">:</font> <font color="#993399">5</font><font color="#990000">,</font> <b><font color="#0000FF">done</font></b><font color="#990000">.</font>
Delta compression using up to <font color="#993399">2</font> threads<font color="#990000">.</font>
Compressing objects<font color="#990000">:</font> <font color="#993399">100</font><font color="#990000">%</font> <font color="#990000">(</font><font color="#993399">3</font><font color="#990000">/</font><font color="#993399">3</font><font color="#990000">),</font> <b><font color="#0000FF">done</font></b><font color="#990000">.</font>
Writing objects<font color="#990000">:</font> <font color="#993399">100</font><font color="#990000">%</font> <font color="#990000">(</font><font color="#993399">3</font><font color="#990000">/</font><font color="#993399">3</font><font color="#990000">),</font> <font color="#993399">321</font> bytes<font color="#990000">,</font> <b><font color="#0000FF">done</font></b><font color="#990000">.</font>
Total <font color="#993399">3</font> <font color="#990000">(</font>delta <font color="#993399">2</font><font color="#990000">),</font> reused <font color="#993399">0</font> <font color="#990000">(</font>delta <font color="#993399">0</font><font color="#990000">)</font>
remote<font color="#990000">:</font> Starting node v0<font color="#990000">.</font><font color="#993399">4.7</font><font color="#990000">...</font>
remote<font color="#990000">:</font> Successful
To node@andersjanmyr<font color="#990000">.</font>no<font color="#990000">.</font>de<font color="#990000">:</font>repo
  8f59169<font color="#990000">..</font>c1177b0  master -<font color="#990000">&gt;</font> master
</tt></pre>
<h3>Nodester</h3>
<p>Nodester, gives you a command line tool, <code>nodester</code>, that you use to<br />
install modules. Deployment by pushing to a Git remote.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ nodester npm install express
$ git push nodester master
Counting objects<font color="#990000">:</font> <font color="#993399">5</font><font color="#990000">,</font> <b><font color="#0000FF">done</font></b><font color="#990000">.</font>
Delta compression using up to <font color="#993399">2</font> threads<font color="#990000">.</font>
Compressing objects<font color="#990000">:</font> <font color="#993399">100</font><font color="#990000">%</font> <font color="#990000">(</font><font color="#993399">3</font><font color="#990000">/</font><font color="#993399">3</font><font color="#990000">),</font> <b><font color="#0000FF">done</font></b><font color="#990000">.</font>
Writing objects<font color="#990000">:</font> <font color="#993399">100</font><font color="#990000">%</font> <font color="#990000">(</font><font color="#993399">3</font><font color="#990000">/</font><font color="#993399">3</font><font color="#990000">),</font> <font color="#993399">341</font> bytes<font color="#990000">,</font> <b><font color="#0000FF">done</font></b><font color="#990000">.</font>
Total <font color="#993399">3</font> <font color="#990000">(</font>delta <font color="#993399">2</font><font color="#990000">),</font> reused <font color="#993399">0</font> <font color="#990000">(</font>delta <font color="#993399">0</font><font color="#990000">)</font>
remote<font color="#990000">:</font> Syncing repo with chroot
remote<font color="#990000">:</font> From /node/hosted_apps/andersjanmyr<font color="#990000">/</font><font color="#993399">1346</font>-7856c14e6a5d92a6b5374ec4772a6da0<font color="#990000">.</font>git<font color="#990000">/.</font>
remote<font color="#990000">:</font>    38f4e6e<font color="#990000">..</font>8f59169  master     -<font color="#990000">&gt;</font> origin/master
remote<font color="#990000">:</font> Updating 38f4e6e<font color="#990000">..</font>8f59169
remote<font color="#990000">:</font> Fast-forward
remote<font color="#990000">:</font>  Gemfile<font color="#990000">.</font>lock <font color="#990000">|</font>   <font color="#993399">10</font> <font color="#990000">++++</font>------
remote<font color="#990000">:</font>  <font color="#993399">1</font> files changed<font color="#990000">,</font> <font color="#993399">4</font> insertions<font color="#990000">(+),</font> <font color="#993399">6</font> deletions<font color="#990000">(</font>-<font color="#990000">)</font>
remote<font color="#990000">:</font> Checking <font color="#990000">./.</font>git/hooks/post-receive
remote<font color="#990000">:</font> Attempting to restart your app<font color="#990000">:</font> <font color="#993399">1346</font>-7856c14e6a5d92a6b5374ec4772a6da0
remote<font color="#990000">:</font> App restarted<font color="#990000">..</font>
remote<font color="#990000">:</font>
remote<font color="#990000">:</font>
remote<font color="#990000">:</font>     <font color="#990000">\</font>m<font color="#990000">/</font> Nodester out <font color="#990000">\</font>m<font color="#990000">/</font>
remote<font color="#990000">:</font>
remote<font color="#990000">:</font>
To ec2-user@nodester<font color="#990000">.</font>com<font color="#990000">:</font>/node/hosted_apps/andersjanmyr<font color="#990000">/</font><font color="#993399">1346</font>-7856c14e6a5d92a6b5374ec4772a6da0<font color="#990000">.</font>git
   38f4e6e<font color="#990000">..</font>8f59169  master -<font color="#990000">&gt;</font> master
</tt></pre>
<h3>Cloud Foundry</h3>
<p>Cloud Foundry is one of the most interesting platforms in the cloud.  It<br />
was genius by VM Ware to open source the platform, allowing anyone to<br />
set up their own cloud if they wish. If you don't want to setup your own<br />
Cloud Foundry Cloud, you can use the service hosted at<br />
cloundfoundry.com.</p>
<p>With Cloud Foundry, you install the modules locally and then they are<br />
automatically deployed as part of the <code>vmc push</code>. Push in this case does<br />
not mean <code>git push</code>, but instead, copy all the files from my local machine<br />
to the server.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ npm install express  <i><font color="#9A1900"># Install locally</font></i>
mime@<font color="#993399">1.2</font><font color="#990000">.</font><font color="#993399">1</font> <font color="#990000">.</font>/node_modules/express/node_modules/mime
connect@<font color="#993399">1.4</font><font color="#990000">.</font><font color="#993399">0</font> <font color="#990000">.</font>/node_modules/express/node_modules/connect
qs@<font color="#993399">0.1</font><font color="#990000">.</font><font color="#993399">0</font> <font color="#990000">.</font>/node_modules/express/node_modules/qs
express@<font color="#993399">2.3</font><font color="#990000">.</font><font color="#993399">0</font> <font color="#990000">.</font>/node_modules/express

$ vmc push
Would you like to deploy from the current directory<font color="#990000">?</font> <font color="#990000">[</font>Yn<font color="#990000">]:</font> Y
Application Name<font color="#990000">:</font> snake
Application Deployed URL<font color="#990000">:</font> <font color="#FF0000">'snake.cloudfoundry.com'</font><font color="#990000">?</font>
Detected a Node<font color="#990000">.</font>js Application<font color="#990000">,</font> is this correct<font color="#990000">?</font> <font color="#990000">[</font>Yn<font color="#990000">]:</font>
Memory Reservation <font color="#990000">[</font>Default<font color="#990000">:</font>64M<font color="#990000">]</font> <font color="#990000">(</font>64M<font color="#990000">,</font> 128M<font color="#990000">,</font> 256M<font color="#990000">,</font> 512M<font color="#990000">,</font> 1G or 2G<font color="#990000">)</font>
Creating Application<font color="#990000">:</font> OK
Would you like to <b><font color="#0000FF">bind</font></b> any services to <font color="#FF0000">'snake'</font><font color="#990000">?</font> <font color="#990000">[</font>yN<font color="#990000">]:</font>
Uploading Application<font color="#990000">:</font>
  Checking <b><font color="#0000FF">for</font></b> available resources<font color="#990000">:</font> OK
  Packing application<font color="#990000">:</font> OK
  Uploading <font color="#990000">(</font>1K<font color="#990000">):</font> OK
Push Status<font color="#990000">:</font> OK
Staging Application<font color="#990000">:</font> OK
Starting Application<font color="#990000">:</font> <font color="#990000">........</font>OK
</tt></pre>
<h2>Tools</h2>
<p>There are of course a bunch of tools that come with a new platform,<br />
Jake, is a Javascript version of Rake, but I am happy with Rake and<br />
I don't see the need to switch. But, there are some tools that I cannot<br />
live without when using Node.</p>
<h3>Reloaders</h3>
<p>If you use the vanilla <code>node</code> command then you have to restart it<br />
every time you make a change to a file. That is awfully annoying and<br />
there are already a number of solutions to the problem.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900"># Nodemon watches the files in your directory and reloads them if necessary</font></i>
$ npm install nodemon
nodemon@<font color="#993399">0.3</font><font color="#990000">.</font><font color="#993399">2</font> <font color="#990000">..</font>/node_modules/nodemon

$ nodemon server<font color="#990000">.</font>js
<font color="#993399">30</font> Apr <font color="#993399">08</font><font color="#990000">:</font><font color="#993399">21</font><font color="#990000">:</font><font color="#993399">23</font> - <font color="#990000">[</font>nodemon<font color="#990000">]</font> running server<font color="#990000">.</font>js
<font color="#990000">...</font>
<i><font color="#9A1900"># Saving the file</font></i>
<font color="#993399">30</font> Apr <font color="#993399">08</font><font color="#990000">:</font><font color="#993399">22</font><font color="#990000">:</font><font color="#993399">01</font> - <font color="#990000">[</font>nodemon<font color="#990000">]</font> restarting due to changes<font color="#990000">...</font> 

<i><font color="#9A1900"># Alternative</font></i>
$ npm install supervisor
$ supervisor server<font color="#990000">.</font>js
DEBUG<font color="#990000">:</font> Watching directory <font color="#FF0000">'/evented-programming-with-nodejs/. </font>
</tt></pre>
<h3>Debuggers</h3>
<p>Another tool that it is hard to live without is a debugger. Node comes<br />
with one built in. It has a <code>gdb</code> flavor to it and it is kind of rough.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ node debug server<font color="#990000">.</font>js
debug<font color="#990000">&gt;</font> run
debugger listening on port <font color="#993399">5858</font>
connecting<font color="#990000">...</font>ok
<b><font color="#0000FF">break</font></b> <b><font color="#0000FF">in</font></b> <i><font color="#9A1900">#&lt;Socket&gt; ./server.js:9</font></i>
    debugger<font color="#990000">;</font> 

debug<font color="#990000">&gt;</font> p data<font color="#990000">.</font><b><font color="#000000">toString()</font></b><font color="#990000">;</font>
tapir

</tt></pre>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// Javascript</font></i>
<b><font color="#0000FF">var</font></b> echo <font color="#990000">=</font> net<font color="#990000">.</font><b><font color="#000000">createServer</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">(</font>socket<font color="#990000">)</font> <font color="#FF0000">{</font>
  socket<font color="#990000">.</font><b><font color="#000000">on</font></b><font color="#990000">(</font><font color="#FF0000">'data'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>data<font color="#990000">)</font> <font color="#FF0000">{</font>
      <b><font color="#0000FF">debugger</font></b><font color="#990000">;</font> <i><font color="#9A1900">// &lt;= break into debugger</font></i>
      socket<font color="#990000">.</font><b><font color="#000000">write</font></b><font color="#990000">(</font>data<font color="#990000">);</font>
  <font color="#FF0000">}</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">);</font>
</tt></pre>
<p>If you want a GUI debugger, it is possible to use the one that comes with<br />
Chrome by installing the <code>node-inspector</code>. It is started similarly to<br />
the built in debugger, but the <code>--debug</code> is an option instead of<br />
a subcommand.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>$ node-inspector <font color="#990000">&amp;</font>
visit http<font color="#990000">://</font><font color="#993399">0.0</font><font color="#990000">.</font><font color="#993399">0.0</font><font color="#990000">:</font><font color="#993399">8080</font>/debug<font color="#990000">?</font><font color="#009900">port</font><font color="#990000">=</font><font color="#993399">5858</font> to start debugging

$ node --debug server<font color="#990000">.</font>js debugger listening on port <font color="#993399">5858</font>
</tt></pre>
<p>After that you can just fire up Chrome on the URL,<br />
<a href="http://0.0.0.0:8080/debug?port=5858"> http://0.0.0.0:8080/debug?port=5858</a> and you can debug the node process<br />
just as if it was running in the browser.</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/nodeJS-Inspector.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/05/nodeJS-Inspector-300x207.png" alt="" title="nodeJS-Inspector" width="300" height="207" class="aligncenter size-medium wp-image-8397" /></a></p>
<h2>Idioms</h2>
<p>Idioms, patterns, techniques, call it what you like. Javascript code is<br />
littered with callbacks, and event more so with Node. Here are some tips<br />
on how to write good asynchronous code with Node.</p>
<h3>Return on Callbacks</h3>
<p>It is easy to forget to escape from the function after a callback has<br />
been called. An easy way to remedy this problem is to call return before<br />
every call to a callback. Even though the value is never used by the<br />
caller, it is an easy pattern to recognize and it prevents bugs.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>
<b><font color="#0000FF">function</font></b> <b><font color="#000000">doSomething</font></b><font color="#990000">(</font>response<font color="#990000">,</font> callback<font color="#990000">)</font> <font color="#FF0000">{</font>
  <b><font color="#000000">doAsyncCall</font></b><font color="#990000">(</font><font color="#FF0000">'tapir'</font><font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>err<font color="#990000">,</font> result<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>err<font color="#990000">)</font> <font color="#FF0000">{</font>
      <i><font color="#9A1900">// return on the callback</font></i>
      <b><font color="#0000FF">return</font></b> <b><font color="#000000">callback</font></b><font color="#990000">(</font>err<font color="#990000">);</font>
    <font color="#FF0000">}</font>
    <i><font color="#9A1900">// return on the callback</font></i>
    <b><font color="#0000FF">return</font></b> <b><font color="#000000">callback</font></b><font color="#990000">(</font><b><font color="#0000FF">null</font></b><font color="#990000">,</font> result<font color="#990000">);</font>
  <font color="#FF0000">}</font><font color="#990000">);</font>
<font color="#FF0000">}</font>
</tt></pre>
<h3>Exceptions in Callbacks</h3>
<p>Exceptions that occur in callbacks cannot be handled the way we are used<br />
to, since the context is different. The solution to this is to pass<br />
along the exception as a parameter to the callback. In Node the<br />
convetion is to pass the error as the first parameter into the callback.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><b><font color="#0000FF">function</font></b> <b><font color="#000000">insertIntoTable</font></b><font color="#990000">(</font>row<font color="#990000">,</font> <b><font color="#000000">function</font></b><font color="#990000">(</font>err<font color="#990000">,</font> data<font color="#990000">)</font> <font color="#FF0000">{</font>
  <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>err<font color="#990000">)</font> <b><font color="#0000FF">return</font></b> <b><font color="#000000">callback</font></b><font color="#990000">(</font>err<font color="#990000">);</font>
  <font color="#990000">...</font> 

  <i><font color="#9A1900">// Everything is OK</font></i>
  <b><font color="#0000FF">return</font></b> <b><font color="#000000">callback</font></b><font color="#990000">(</font><b><font color="#0000FF">null</font></b><font color="#990000">,</font> <font color="#FF0000">'row inserted'</font><font color="#990000">);</font>
<font color="#FF0000">}</font>
</tt></pre>
<h3>Parallel Execution</h3>
<p>If you have multiple tasks that need to be finished before you take some<br />
new action, this can be handled with a simple counter. Here is an<br />
example of a simple function that starts up a bunch of functions in<br />
parallel and waits for all of them to finish before calling the<br />
callback.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><i><font color="#9A1900">// Do all in parallel</font></i>
<b><font color="#0000FF">function</font></b> <b><font color="#000000">doAll</font></b><font color="#990000">(</font>collection<font color="#990000">,</font> callback<font color="#990000">)</font> <font color="#FF0000">{</font>
  <b><font color="#0000FF">var</font></b> left <font color="#990000">=</font> collection<font color="#990000">.</font>length<font color="#990000">;</font>
  collection<font color="#990000">.</font><b><font color="#000000">forEach</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">(</font>fun<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#000000">fun</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
      <b><font color="#0000FF">if</font></b> <font color="#990000">(--</font>left <font color="#990000">==</font> <font color="#993399">0</font><font color="#990000">)</font> <b><font color="#000000">callback</font></b><font color="#990000">();</font>
    <font color="#FF0000">}</font><font color="#990000">);</font>
  <font color="#FF0000">}</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">;</font> 

<i><font color="#9A1900">// Use it</font></i>
<b><font color="#0000FF">var</font></b> result <font color="#990000">=</font> <font color="#990000">[];</font>
<b><font color="#000000">doAll</font></b><font color="#990000">([</font>
  <b><font color="#0000FF">function</font></b><font color="#990000">(</font>callback<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>result<font color="#990000">.</font><b><font color="#000000">push</font></b><font color="#990000">(</font><font color="#993399">1</font><font color="#990000">);</font> <b><font color="#000000">callback</font></b><font color="#990000">();</font><font color="#FF0000">}</font><font color="#990000">,</font> <font color="#993399">2000</font> <font color="#990000">)</font><font color="#FF0000">}</font><font color="#990000">,</font>
  <b><font color="#0000FF">function</font></b><font color="#990000">(</font>callback<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>result<font color="#990000">.</font><b><font color="#000000">push</font></b><font color="#990000">(</font><font color="#993399">2</font><font color="#990000">);</font> <b><font color="#000000">callback</font></b><font color="#990000">();</font><font color="#FF0000">}</font><font color="#990000">,</font> <font color="#993399">3000</font> <font color="#990000">)</font><font color="#FF0000">}</font><font color="#990000">,</font>
  <b><font color="#0000FF">function</font></b><font color="#990000">(</font>callback<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>result<font color="#990000">.</font><b><font color="#000000">push</font></b><font color="#990000">(</font><font color="#993399">3</font><font color="#990000">);</font> <b><font color="#000000">callback</font></b><font color="#990000">();</font><font color="#FF0000">}</font><font color="#990000">,</font> <font color="#993399">1000</font> <font color="#990000">)</font><font color="#FF0000">}</font>
  <font color="#990000">],</font> <b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font> <b><font color="#0000FF">return</font></b> result<font color="#990000">;</font> <font color="#FF0000">}</font> 

<i><font color="#9A1900">// returns [3, 1, 2]</font></i>
</tt></pre>
<h3>Sequential Execution</h3>
<p>Sometimes the ordering is important. Here is a simple function that<br />
makes sure that the calls are executed in sequence. It uses recursion to<br />
to make sure that the calls are handled in the correct order. It also<br />
uses the Node function <code>process.nextTick()</code> to prevent the stack from<br />
getting to large for large collections. Similar results can be obtained<br />
with <code>setTimeout()</code> in browser Javascript. It can be seen as a simple<br />
trick to achieve <em>tail recursion</em>.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><b><font color="#0000FF">function</font></b> <b><font color="#000000">doInSequence</font></b><font color="#990000">(</font>collection<font color="#990000">,</font> callback<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">var</font></b> queue <font color="#990000">=</font> collection<font color="#990000">.</font><b><font color="#000000">slice</font></b><font color="#990000">(</font><font color="#993399">0</font><font color="#990000">);</font> <i><font color="#9A1900">// Duplicate</font></i> 

    <b><font color="#0000FF">function</font></b> <b><font color="#000000">iterate</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
      <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>queue<font color="#990000">.</font>length <font color="#990000">===</font> <font color="#993399">0</font><font color="#990000">)</font> <b><font color="#0000FF">return</font></b> <b><font color="#000000">callback</font></b><font color="#990000">();</font>
      <i><font color="#9A1900">// Take the first element</font></i>
      <b><font color="#0000FF">var</font></b> fun <font color="#990000">=</font> queue<font color="#990000">.</font><b><font color="#000000">splice</font></b><font color="#990000">(</font><font color="#993399">0</font><font color="#990000">,</font> <font color="#993399">1</font><font color="#990000">)[</font><font color="#993399">0</font><font color="#990000">];</font>
      <b><font color="#000000">fun</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">(</font>err<font color="#990000">)</font> <font color="#FF0000">{</font>
        <b><font color="#0000FF">if</font></b> <font color="#990000">(</font>err<font color="#990000">)</font> <b><font color="#0000FF">throw</font></b> err<font color="#990000">;</font>
        <i><font color="#9A1900">// Call it without building up the stack</font></i>
        process<font color="#990000">.</font><b><font color="#000000">nextTick</font></b><font color="#990000">(</font><b><font color="#000000">iterate</font></b><font color="#990000">);</font>
      <font color="#FF0000">}</font><font color="#990000">);</font>
    <font color="#FF0000">}</font>
    <b><font color="#000000">iterate</font></b><font color="#990000">();</font>
<font color="#FF0000">}</font> 

<b><font color="#0000FF">var</font></b> result <font color="#990000">=</font> <font color="#990000">[];</font>
<b><font color="#000000">doInSequence</font></b><font color="#990000">([</font>
  <b><font color="#0000FF">function</font></b><font color="#990000">(</font>callback<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>result<font color="#990000">.</font><b><font color="#000000">push</font></b><font color="#990000">(</font><font color="#993399">1</font><font color="#990000">);</font> <b><font color="#000000">callback</font></b><font color="#990000">();</font><font color="#FF0000">}</font><font color="#990000">,</font> <font color="#993399">2000</font> <font color="#990000">)</font><font color="#FF0000">}</font><font color="#990000">,</font>
  <b><font color="#0000FF">function</font></b><font color="#990000">(</font>callback<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>result<font color="#990000">.</font><b><font color="#000000">push</font></b><font color="#990000">(</font><font color="#993399">2</font><font color="#990000">);</font> <b><font color="#000000">callback</font></b><font color="#990000">();</font><font color="#FF0000">}</font><font color="#990000">,</font> <font color="#993399">3000</font> <font color="#990000">)</font><font color="#FF0000">}</font><font color="#990000">,</font>
  <b><font color="#0000FF">function</font></b><font color="#990000">(</font>callback<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>result<font color="#990000">.</font><b><font color="#000000">push</font></b><font color="#990000">(</font><font color="#993399">3</font><font color="#990000">);</font> <b><font color="#000000">callback</font></b><font color="#990000">();</font><font color="#FF0000">}</font><font color="#990000">,</font> <font color="#993399">1000</font> <font color="#990000">)</font><font color="#FF0000">}</font>
  <font color="#990000">],</font> <b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font> <b><font color="#0000FF">return</font></b> result<font color="#990000">;</font> <font color="#FF0000">}</font><font color="#990000">);</font> 

<i><font color="#9A1900">// Returns [1, 2, 3]</font></i>
</tt></pre>
<h2>Library Support for Asynchronous Programming</h2>
<p>If you don't want to write these functions yourself, there are a few<br />
libraries that can help you out. I'll show two version that I like.</p>
<h3>Fibers</h3>
<p>Fibers are also called co-routines. Fibers provide two functions,<br />
<em>suspend</em> and <em>resume</em>, which allows us to write code in a synchronous<br />
looking style. In the Node version of fibers,<br />
<a href="https://github.com/laverdet/node-fibers">node-fibers</a>, suspend and<br />
resume are called <code>yield()</code> and <code>run()</code> instead.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt><b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'fibers'</font><font color="#990000">);</font>
<b><font color="#0000FF">var</font></b> print <font color="#990000">=</font> <b><font color="#000000">require</font></b><font color="#990000">(</font><font color="#FF0000">'util'</font><font color="#990000">).</font>print<font color="#990000">;</font> 

<b><font color="#0000FF">function</font></b> <b><font color="#000000">sleep</font></b><font color="#990000">(</font>ms<font color="#990000">)</font> <font color="#FF0000">{</font>
    <b><font color="#0000FF">var</font></b> fiber <font color="#990000">=</font> Fiber<font color="#990000">.</font>current<font color="#990000">;</font>
    <b><font color="#000000">setTimeout</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font> fiber<font color="#990000">.</font><b><font color="#000000">run</font></b><font color="#990000">();</font> <font color="#FF0000">}</font><font color="#990000">,</font> ms<font color="#990000">);</font>
    <b><font color="#000000">yield</font></b><font color="#990000">();</font>
<font color="#FF0000">}</font> 

<b><font color="#000000">Fiber</font></b><font color="#990000">(</font><b><font color="#0000FF">function</font></b><font color="#990000">()</font> <font color="#FF0000">{</font>
    <b><font color="#000000">print</font></b><font color="#990000">(</font><font color="#FF0000">'wait... '</font> <font color="#990000">+</font> <b><font color="#0000FF">new</font></b> Date <font color="#990000">+</font> <font color="#FF0000">'</font><font color="#CC33CC">\n</font><font color="#FF0000">'</font><font color="#990000">);</font>
    <b><font color="#000000">sleep</font></b><font color="#990000">(</font><font color="#993399">1000</font><font color="#990000">);</font>
    <b><font color="#000000">print</font></b><font color="#990000">(</font><font color="#FF0000">'ok... '</font> <font color="#990000">+</font> <b><font color="#0000FF">new</font></b> Date <font color="#990000">+</font> <font color="#FF0000">'</font><font color="#CC33CC">\n</font><font color="#FF0000">'</font><font color="#990000">);</font>
<font color="#FF0000">}</font><font color="#990000">).</font><b><font color="#000000">run</font></b><font color="#990000">();</font>
<b><font color="#000000">print</font></b><font color="#990000">(</font><font color="#FF0000">'back in main</font><font color="#CC33CC">\n</font><font color="#FF0000">'</font><font color="#990000">);</font>
</tt></pre>
<p>Fibers are a very nice way of writing asynchronous code but, in Node,<br />
they have one drawback. They are not supported without patching the V8<br />
virtual machine. The patching is done when you install <code>node-fibers</code> and<br />
you have to run the command <code>node-fibers</code> instead of <code>node</code> to use it.</p>
<h3>The <code>async</code> Library</h3>
<p>If you don't want to use the patched version of V8, I can recommend the<br />
<a href="https://github.com/caolan/async">async</a> library.  Async provides<br />
around 20 functions that include the usual 'functional' suspects (map,<br />
reduce, filter, forEach...) as well as some common patterns for<br />
asynchronous flow control (parallel, series, waterfall...). All these<br />
functions assume you follow the Node convention of providing a single<br />
callback as the last argument of your async function.</p>
<p><!-- Generator: GNU source-highlight 3.1.4<br />
by Lorenzo Bettini</p>
<p>http://www.lorenzobettini.it</p>
<p>http://www.gnu.org/software/src-highlite --> </p>
<pre><tt>async<font color="#990000">.</font><b><font color="#000000">map</font></b><font color="#990000">([</font><font color="#FF0000">'file1'</font><font color="#990000">,</font><font color="#FF0000">'file2'</font><font color="#990000">,</font><font color="#FF0000">'file3'</font><font color="#990000">],</font> fs<font color="#990000">.</font>stat<font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>err<font color="#990000">,</font> results<font color="#990000">)</font><font color="#FF0000">{</font>
    <i><font color="#9A1900">// results is now an array of stats for each file</font></i>
<font color="#FF0000">}</font><font color="#990000">);</font> 

async<font color="#990000">.</font><b><font color="#000000">filter</font></b><font color="#990000">([</font><font color="#FF0000">'file1'</font><font color="#990000">,</font><font color="#FF0000">'file2'</font><font color="#990000">,</font><font color="#FF0000">'file3'</font><font color="#990000">],</font> path<font color="#990000">.</font>exists<font color="#990000">,</font> <b><font color="#0000FF">function</font></b><font color="#990000">(</font>results<font color="#990000">)</font><font color="#FF0000">{</font>
    <i><font color="#9A1900">// results now equals an array of the existing files</font></i>
<font color="#FF0000">}</font><font color="#990000">);</font> 

async<font color="#990000">.</font><b><font color="#000000">parallel</font></b><font color="#990000">([</font>
    <b><font color="#0000FF">function</font></b><font color="#990000">()</font><font color="#FF0000">{</font> <font color="#990000">...</font> <font color="#FF0000">}</font><font color="#990000">,</font>
    <b><font color="#0000FF">function</font></b><font color="#990000">()</font><font color="#FF0000">{</font> <font color="#990000">...</font> <font color="#FF0000">}</font>
<font color="#990000">],</font> callback<font color="#990000">);</font> 

async<font color="#990000">.</font><b><font color="#000000">series</font></b><font color="#990000">([</font>
    <b><font color="#0000FF">function</font></b><font color="#990000">()</font><font color="#FF0000">{</font> <font color="#990000">...</font> <font color="#FF0000">}</font><font color="#990000">,</font>
    <b><font color="#0000FF">function</font></b><font color="#990000">()</font><font color="#FF0000">{</font> <font color="#990000">...</font> <font color="#FF0000">}</font>
<font color="#990000">],</font> callback<font color="#990000">);</font>
</tt></pre>
<h2>Conclusion</h2>
<p>Node is definitely an interesting platform. The possibility to have<br />
Javascript running through the whole stack, from the browser all the way<br />
down into the database (if you use something like CouchDB or MongoDB)<br />
really appeals to me. The easy way to deploy code to multiple, different<br />
cloud providers is also a good argument for Node.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/15/a-not-very-short-introduction-to-node-js/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part VI – Textures</title>
		<link>http://blog.jayway.com/2010/12/30/opengl-es-tutorial-for-android-%e2%80%93-part-vi-textures/</link>
		<comments>http://blog.jayway.com/2010/12/30/opengl-es-tutorial-for-android-%e2%80%93-part-vi-textures/#comments</comments>
		<pubDate>Thu, 30 Dec 2010 17:46:10 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[opengl es]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2592</guid>
		<description><![CDATA[Last tutorial we worked a bit more on meshes and we have also talked about adding colors to our mesh. The most common way of adding colors to your mesh is to add a texture. There is a couple of different steps involved with adding a texture to the mesh I will try to go [...]]]></description>
			<content:encoded><![CDATA[<p>Last tutorial we worked a bit more on meshes and we have also talked about adding colors to our mesh. The most common way of adding colors to your mesh is to add a texture. There is a couple of different steps involved with adding a texture to the mesh I will try to go through them all and explain the basics about them.</p>
<h2>Loading bitmaps</h2>
<p>First step would be to get a bitmap to generate a texture from. You can get hold of a bitmap in many different ways from downloading, generating or simply just load one from the resources. I'm going with the simplest one for this example witch is loading from the resources.</p>
<pre class="java">Bitmap bitmap = BitmapFactory.<span style="color: #006600;">decodeResource</span><span style="color: #66cc66;">&#40;</span>contect.<span style="color: #006600;">getResources</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>,
                                             R.<span style="color: #006600;">drawable</span>.<span style="color: #006600;">icon</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>One other thing about textures is that some hardware requires that the height and width are in the power of 2 (1, 2, 4, 8, 16, 32, 64...). If you run a texture with a size of 30x30pixels on a hardware that don’t support it you will just get a white square (unless you change the default color). </p>
<h2>Generating a texture</h2>
<p>After we have loaded the bitmap we need to tell OpenGL to actually create the texture. </p>
<p>First thing we need to do is to let OpenGL generate some texture id's that we will use as handles to the textures later on. In this example we will only have one texture.</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// Create an int array with the number of textures we want,</span>
<span style="color: #808080; font-style: italic;">// in this case 1.</span>
<span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> textures = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>;
<span style="color: #808080; font-style: italic;">// Tell OpenGL to generate textures.</span>
gl.<span style="color: #006600;">glGenTextures</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, textures, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>With the same parameters you can delete the textures:</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// Delete a texture.</span>
gl.<span style="color: #006600;">glDeleteTextures</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, textures, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span></pre>
<p>Now when the texture id's are generated we need to just like everything else tell OpenGL what to work with. With textures we use the command glBindTexture:</p>
<pre class="java">gl.<span style="color: #006600;">glBindTexture</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, textures<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>From this point all commands we call on regarding textures will be applied on to your texture with the generated id.</p>
<h2>glTexParameter</h2>
<p>There is a couple of parameters we need to set on the texture, the first one is to tell OpenGL what to do if the texture need to be shrunk or magnified to match the rendered image.<br />
If the texture is smaller it needs to be magnified that is done with the magnification function:</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// Scale up if the texture if smaller.</span>
gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>,
                   GL10.<span style="color: #006600;">GL_TEXTURE_MAG_FILTER</span>,
                   GL10.<span style="color: #006600;">GL_LINEAR</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>And how to scale if the texture needs to be scaled down using the minification function.</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// scale linearly when image smalled than texture</span>
gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>,
                   GL10.<span style="color: #006600;">GL_TEXTURE_MIN_FILTER</span>,
                   GL10.<span style="color: #006600;">GL_LINEAR</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>You need to pass an argument to these functions. I'm only going to show you two of them the rest you can investigate your self <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>If you want a crisp and clean rendering like this image you need to use the GL10.GL_NEAREST parameter.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/gl_nearest.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/gl_nearest.png" alt="" title="gl_nearest" width="200" height="200" class="alignright size-full wp-image-6736" /></a></center></p>
<p>If you rather want a blurred image you should use the GL10.GL_LINEAR parameter.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/gl_linear.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/gl_linear.png" alt="" title="gl_linear" width="200" height="200" class="alignright size-full wp-image-6732" /></a></center></p>
<h2>UV Mapping</h2>
<p>We will also need to tell OpenGL how to map this image onto the mesh this is done in two steps, fist we need to assign UV coordinates</p>
<p>UV mapping is the way we map the pixels on the bitmap to the vertices in our mesh. The UV coordinates are 0,0 in the upper left and 1,1 is the bottom right, like the left image below. The right image below illustrates how our plane is built. To get the texture mapped correctly we need to map the lower left part of the texture (0,1) to the lower left vertex (0) in our plane and we need to map the the bottom right (1,1) in the texture to the bottom right (1) to the bottom right in our plane and... you get the idea.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/blog_uv.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/blog_uv.png" alt="" title="blog_uv" width="390" height="203" class="alignright size-full wp-image-6743" /></a></center></p>
<p>We put this mapping into a float array like this:</p>
<pre class="java"><span style="color: #993333;">float</span> textureCoordinates<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">1</span>.0f,
                              <span style="color: #cc66cc;">1</span>.0f, <span style="color: #cc66cc;">1</span>.0f,
                              <span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">0</span>.0f,
                              <span style="color: #cc66cc;">1</span>.0f, <span style="color: #cc66cc;">0</span>.0f <span style="color: #66cc66;">&#125;</span>;</pre>
<p><center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/blog_uv2.jpg" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/blog_uv2.jpg" alt="" title="blog_uv2" width="390" height="203" class="alignright size-full wp-image-6748" /></a></center></p>
<p>If we instead used 0.5 instead of 1.0 like this:</p>
<pre class="java"><span style="color: #993333;">float</span> textureCoordinates<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">0</span>.5f,
                              <span style="color: #cc66cc;">0</span>.5f, <span style="color: #cc66cc;">0</span>.5f,
                              <span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">0</span>.0f,
                              <span style="color: #cc66cc;">0</span>.5f, <span style="color: #cc66cc;">0</span>.0f <span style="color: #66cc66;">&#125;</span>;</pre>
<p><center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/blog_uv3.jpg" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/blog_uv3.jpg" alt="" title="Print" width="390" height="203" class="alignright size-full wp-image-6752" /></a></center><br />
The texture will be mapped so the plane will have the upper left part of it.</p>
<p>Back to the glTexParameterf, if we go the other way and uses values higher then 1.0 like this:</p>
<pre class="java"><span style="color: #993333;">float</span> textureCoordinates<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">2</span>.0f,
                              <span style="color: #cc66cc;">2</span>.0f, <span style="color: #cc66cc;">2</span>.0f,
                              <span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">0</span>.0f,
                              <span style="color: #cc66cc;">2</span>.0f, <span style="color: #cc66cc;">0</span>.0f <span style="color: #66cc66;">&#125;</span>;</pre>
<p>We actually tell OpenGL to use part of the texture that does not exist so we need to tell OpenGL what to do with the part that does not exist.</p>
<p>We use the glTexParameterf function to tell OpenGL what to do with the texture. By default OpenGL uses something called GL_REPEAT.</p>
<p><strong>GL_REPEAT</strong> means that OpenGL should repeat the texture beyond 1.0.<br />
<strong>GL_CLAMP_TO_EDGE</strong> means that OpenGL only will draw the image once and after that just repeat the last pixel line the rest of the image. </p>
<p>Since we are working with a 2D texture so we need to tell OpenGL what to do in two directions: GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T.</p>
<p>Below you see a chart with the 4 combinations of GL_REPEAT and GL_CLAMP_TO_EDGE.</p>
<p><center></p>
<table>
<td>
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_REPEAT_GL_REPEAT.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_REPEAT_GL_REPEAT.png" alt="" title="GL_REPEAT_GL_REPEAT" width="200" height="200" class="alignright size-full wp-image-6771" /></a>
</td>
<td>
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_REPEAT_GL_CLAMP_TO_EDGE.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_REPEAT_GL_CLAMP_TO_EDGE.png" alt="" title="GL_REPEAT_GL_CLAMP_TO_EDGE" width="200" height="200" class="alignright size-full wp-image-6772" /></a>
</td>
</tr>
<tr>
<td width="300">
<h6>WRAP_S: GL_REPEAT<br />
WRAP_T: GL_REPEAT</h6>
</td>
<td width="300">
<h6>WRAP_S: GL_REPEAT<br />
WRAP_T: GL_CLAMP_TO_EDGE</h6>
</td>
</tr>
<tr>
<tr>
<td><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_CLAMP_TO_EDGE_GL_REPEAT.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_CLAMP_TO_EDGE_GL_REPEAT.png" alt="" title="GL_CLAMP_TO_EDGE_GL_REPEAT" width="200" height="200" class="alignright size-full wp-image-6774" /></a>
</td>
<td><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_CLAMP_TO_EDGE_GL_CLAMP_TO_EDGE.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/GL_CLAMP_TO_EDGE_GL_CLAMP_TO_EDGE.png" alt="" title="GL_CLAMP_TO_EDGE_GL_CLAMP_TO_EDGE" width="200" height="200" class="alignright size-full wp-image-6773" /></a></td>
</tr>
<tr>
<td>
<h6>WRAP_S: GL_REPEAT<br />
WRAP_T: GL_CLAMP_TO_EDGE</h6>
</td>
<td>
<h6>WRAP_S: GL_CLAMP_TO_EDGE<br />
WRAP_T: GL_CLAMP_TO_EDGE</h6>
</td>
</tr>
</table>
<p></center></p>
<p>This is how we use the glTexParameterf function:</p>
<pre class="java">gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>,
                   GL10.<span style="color: #006600;">GL_TEXTURE_WRAP_S</span>,
                   GL10.<span style="color: #006600;">GL_REPEAT</span><span style="color: #66cc66;">&#41;</span>;
gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>,
                   GL10.<span style="color: #006600;">GL_TEXTURE_WRAP_T</span>,
                   GL10.<span style="color: #006600;">GL_REPEAT</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>The last thing we need to do is to bind the bitmap we loaded to the texture id we created. </p>
<pre class="java">GLUtils.<span style="color: #006600;">texImage2D</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, <span style="color: #cc66cc;">0</span>, bitmap, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;</pre>
<h2>Using the texture</h2>
<p>To be able to use the texture we need just like with everything else create a byte buffer with the UV coordinates:</p>
<pre class="java">FloatBuffer byteBuf = ByteBuffer.<span style="color: #006600;">allocateDirect</span><span style="color: #66cc66;">&#40;</span>texture.<span style="color: #006600;">length</span> * <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span>;
byteBuf.<span style="color: #006600;">order</span><span style="color: #66cc66;">&#40;</span>ByteOrder.<span style="color: #006600;">nativeOrder</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
textureBuffer = byteBuf.<span style="color: #006600;">asFloatBuffer</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
textureBuffer.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>textureCoordinates<span style="color: #66cc66;">&#41;</span>;
textureBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;</pre>
<h3>Rendering</h3>
<pre class="java"><span style="color: #808080; font-style: italic;">// Telling OpenGL to enable textures.</span>
gl.<span style="color: #006600;">glEnable</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Tell OpenGL where our texture is located.</span>
gl.<span style="color: #006600;">glBindTexture</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, textures<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Tell OpenGL to enable the use of UV coordinates.</span>
gl.<span style="color: #006600;">glEnableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_COORD_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Telling OpenGL where our UV coordinates are.</span>
gl.<span style="color: #006600;">glTexCoordPointer</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, GL10.<span style="color: #006600;">GL_FLOAT</span>, <span style="color: #cc66cc;">0</span>, textureBuffer<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// ... here goes the rendering of the mesh ...</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// Disable the use of UV coordinates.</span>
gl.<span style="color: #006600;">glDisableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_COORD_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Disable the use of textures.</span>
gl.<span style="color: #006600;">glDisable</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span><span style="color: #66cc66;">&#41;</span>;</pre>
<h2>Putting it all together</h2>
<p>I'm using a modified version of the code from the previous tutorial. The different is mostly that I renamed some variables and functions and added more comments and all code is now under Apache License. To make the code easier to understand I removed the previous plane and added a new easier one called SimplePlane.</p>
<h3>Updating the Mesh class</h3>
<p>The first thing we need to do is to update the Mesh class (se.jayway.opengl.tutorial.mesh.Mesh). We need to add the functionality to load and render a texture.</p>
<p>We need to be able to set and store the UV coordinates.</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// Our UV texture buffer.</span>
<span style="color: #000000; font-weight: bold;">private</span> FloatBuffer mTextureBuffer;
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Set the texture coordinates.
 *
 * @param textureCoords
 */</span>
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setTextureCoordinates<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> textureCoords<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// float is 4 bytes, therefore we multiply the number if</span>
        <span style="color: #808080; font-style: italic;">// vertices with 4.</span>
	ByteBuffer byteBuf = ByteBuffer.<span style="color: #006600;">allocateDirect</span><span style="color: #66cc66;">&#40;</span>
                                           textureCoords.<span style="color: #006600;">length</span> * <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span>;
	byteBuf.<span style="color: #006600;">order</span><span style="color: #66cc66;">&#40;</span>ByteOrder.<span style="color: #006600;">nativeOrder</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	mTextureBuffer = byteBuf.<span style="color: #006600;">asFloatBuffer</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	mTextureBuffer.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>textureCoords<span style="color: #66cc66;">&#41;</span>;
	mTextureBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>We also need to add functions to set the bitmap and create the texture.</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// Our texture id.</span>
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">int</span> mTextureId = <span style="color: #cc66cc;">-1</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// The bitmap we want to load as a texture.</span>
<span style="color: #000000; font-weight: bold;">private</span> Bitmap mBitmap;
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Set the bitmap to load into a texture.
 *
 * @param bitmap
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> loadBitmap<span style="color: #66cc66;">&#40;</span>Bitmap bitmap<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">mBitmap</span> = bitmap;
	mShouldLoadTexture = <span style="color: #000000; font-weight: bold;">true</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Loads the texture.
 *
 * @param gl
 */</span>
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">void</span> loadGLTexture<span style="color: #66cc66;">&#40;</span>GL10 gl<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// Generate one texture pointer...</span>
	<span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> textures = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>;
	gl.<span style="color: #006600;">glGenTextures</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, textures, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
	mTextureId = textures<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// ...and bind it to our array</span>
	gl.<span style="color: #006600;">glBindTexture</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, mTextureId<span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Create Nearest Filtered Texture</span>
	gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, GL10.<span style="color: #006600;">GL_TEXTURE_MIN_FILTER</span>,
			GL10.<span style="color: #006600;">GL_LINEAR</span><span style="color: #66cc66;">&#41;</span>;
	gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, GL10.<span style="color: #006600;">GL_TEXTURE_MAG_FILTER</span>,
			GL10.<span style="color: #006600;">GL_LINEAR</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE</span>
	gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, GL10.<span style="color: #006600;">GL_TEXTURE_WRAP_S</span>,
			GL10.<span style="color: #006600;">GL_CLAMP_TO_EDGE</span><span style="color: #66cc66;">&#41;</span>;
	gl.<span style="color: #006600;">glTexParameterf</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, GL10.<span style="color: #006600;">GL_TEXTURE_WRAP_T</span>,
			GL10.<span style="color: #006600;">GL_REPEAT</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Use the Android GLUtils to specify a two-dimensional texture image</span>
	<span style="color: #808080; font-style: italic;">// from our bitmap</span>
	GLUtils.<span style="color: #006600;">texImage2D</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, <span style="color: #cc66cc;">0</span>, mBitmap, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>And finally we need to add the call to the texture loading and to actually tell OpenGL to render with this texture. I removed some code so the page would not be so long but you will find the code complete in the attached zip file.</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// Indicates if we need to load the texture.</span>
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">boolean</span> mShouldLoadTexture = <span style="color: #000000; font-weight: bold;">false</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Render the mesh.
 *
 * @param gl
 *            the OpenGL context to render to.
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> draw<span style="color: #66cc66;">&#40;</span>GL10 gl<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	...
&nbsp;
	<span style="color: #808080; font-style: italic;">// Smooth color</span>
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>mColorBuffer != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">// Enable the color array buffer to be used during rendering.</span>
		gl.<span style="color: #006600;">glEnableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_COLOR_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
		gl.<span style="color: #006600;">glColorPointer</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">4</span>, GL10.<span style="color: #006600;">GL_FLOAT</span>, <span style="color: #cc66cc;">0</span>, mColorBuffer<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>mShouldLoadTexture<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		loadGLTexture<span style="color: #66cc66;">&#40;</span>gl<span style="color: #66cc66;">&#41;</span>;
		mShouldLoadTexture = <span style="color: #000000; font-weight: bold;">false</span>;
	<span style="color: #66cc66;">&#125;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>mTextureId != <span style="color: #cc66cc;">-1</span> &amp;&amp; mTextureBuffer != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		gl.<span style="color: #006600;">glEnable</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #808080; font-style: italic;">// Enable the texture state</span>
		gl.<span style="color: #006600;">glEnableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_COORD_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Point to our buffers</span>
		gl.<span style="color: #006600;">glTexCoordPointer</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, GL10.<span style="color: #006600;">GL_FLOAT</span>, <span style="color: #cc66cc;">0</span>, mTextureBuffer<span style="color: #66cc66;">&#41;</span>;
		gl.<span style="color: #006600;">glBindTexture</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_2D</span>, mTextureId<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	gl.<span style="color: #006600;">glTranslatef</span><span style="color: #66cc66;">&#40;</span>x, y, z<span style="color: #66cc66;">&#41;</span>;
&nbsp;
	...
&nbsp;
	<span style="color: #808080; font-style: italic;">// Point out the where the color buffer is.</span>
	gl.<span style="color: #006600;">glDrawElements</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TRIANGLES</span>, mNumOfIndices,
			GL10.<span style="color: #006600;">GL_UNSIGNED_SHORT</span>, mIndicesBuffer<span style="color: #66cc66;">&#41;</span>;
&nbsp;
	...
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>mTextureId != <span style="color: #cc66cc;">-1</span> &amp;&amp; mTextureBuffer != <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		gl.<span style="color: #006600;">glDisableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TEXTURE_COORD_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	...
&nbsp;
<span style="color: #66cc66;">&#125;</span></pre>
<h3>Creating the SimplePlane class</h3>
<p>We also need to create the SimplePlane.java. The code is pretty simple and self-explaining if you have read my previous tutorials. The new element is the textureCoordinates variable.</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">opengl</span>.<span style="color: #006600;">tutorial</span>.<span style="color: #006600;">mesh</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * SimplePlane is a setup class for Mesh that creates a plane mesh.
 *
 * @author Per-Erik Bergman (per-erik.bergman@jayway.com)
 *
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SimplePlane <span style="color: #000000; font-weight: bold;">extends</span> Mesh <span style="color: #66cc66;">&#123;</span>
	<span style="color: #808080; font-style: italic;">/**
	 * Create a plane with a default with and height of 1 unit.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> SimplePlane<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">/**
	 * Create a plane.
	 *
	 * @param width
	 *            the width of the plane.
	 * @param height
	 *            the height of the plane.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> SimplePlane<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">// Mapping coordinates for the vertices</span>
		<span style="color: #993333;">float</span> textureCoordinates<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#123;</span> <span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">2</span>.0f, <span style="color: #808080; font-style: italic;">//</span>
				<span style="color: #cc66cc;">2</span>.0f, <span style="color: #cc66cc;">2</span>.0f, <span style="color: #808080; font-style: italic;">//</span>
				<span style="color: #cc66cc;">0</span>.0f, <span style="color: #cc66cc;">0</span>.0f, <span style="color: #808080; font-style: italic;">//</span>
				<span style="color: #cc66cc;">2</span>.0f, <span style="color: #cc66cc;">0</span>.0f, <span style="color: #808080; font-style: italic;">//</span>
		<span style="color: #66cc66;">&#125;</span>;
&nbsp;
		<span style="color: #993333;">short</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> indices = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">short</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">2</span> <span style="color: #66cc66;">&#125;</span>;
&nbsp;
                <span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> vertices = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #cc66cc;">-0</span>.5f, <span style="color: #cc66cc;">-0</span>.5f, <span style="color: #cc66cc;">0</span>.0f,
                                                  <span style="color: #cc66cc;">0</span>.5f, <span style="color: #cc66cc;">-0</span>.5f, <span style="color: #cc66cc;">0</span>.0f,
                                                 <span style="color: #cc66cc;">-0</span>.5f,  <span style="color: #cc66cc;">0</span>.5f, <span style="color: #cc66cc;">0</span>.0f,
                                                  <span style="color: #cc66cc;">0</span>.5f, <span style="color: #cc66cc;">0</span>.5f, <span style="color: #cc66cc;">0</span>.0f <span style="color: #66cc66;">&#125;</span>;
&nbsp;
		setIndices<span style="color: #66cc66;">&#40;</span>indices<span style="color: #66cc66;">&#41;</span>;
		setVertices<span style="color: #66cc66;">&#40;</span>vertices<span style="color: #66cc66;">&#41;</span>;
		setTextureCoordinates<span style="color: #66cc66;">&#40;</span>textureCoordinates<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<h2>References</h2>
<p>The info used in this tutorial is collected from:<br />
<a href="http://developer.android.com/">Android Developers</a><br />
<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/">OpenGL ES 1.1 Reference Pages</a></p>
<p>You can download the source for this tutorial here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/Tutorial_Part_VI.zip'>Tutorial_Part_VI</a><br />
You can also checkout the code from: <a href='http://code.google.com/p/opengl-es-tutorial-for-android/source/checkout'>code.google.com</a></p>
<p>Previous tutorial: <a href="http://blog.jayway.com/2010/02/15/opengl-es-tutorial-for-android-%e2%80%93-part-v/">OpenGL ES Tutorial for Android – Part V – More on Meshes</a><br />
<!-- Next tutorial: <a href=""></a> --></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/12/30/opengl-es-tutorial-for-android-%e2%80%93-part-vi-textures/feed/</wfw:commentRss>
		<slash:comments>91</slash:comments>
		</item>
		<item>
		<title>Exceptions and Errors on iOS</title>
		<link>http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/</link>
		<comments>http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 12:03:16 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6430</guid>
		<description><![CDATA[Cocoa, and by inheritance Cocoa Touch on iOS makes a clear distinction between what is an exception, and what is an error in your application. This should be obvious since NSException and NSError both inherit from the NSObject root class with no relations at all. Programmer vs. User Exceptions are intended for signaling programming errors [...]]]></description>
			<content:encoded><![CDATA[<p>Cocoa, and by inheritance Cocoa Touch on iOS makes a clear distinction between what is an exception, and what is an error in your application. This should be obvious since <code>NSException</code> and <code>NSError</code> both inherit from the <code>NSObject</code> root class with no relations at all.</p>
<h3>Programmer vs. User</h3>
<p>Exceptions are intended for signaling programming errors and fatal errors that the application can never recover from. One such error is index out of bounds when accessing an array. There is little reason to catch any exception; if you for example could not calculate a legal array index the first time around your app is in an illegal state. Exceptions are for your own use as a developer, to catch all programming errors in testing before shipping to the end user. Only secondary to inform the user of fatal errors when possible.</p>
<p>Errors are intended for signaling user errors, and conditions that can not be predicted until the end user runs your application. One such error is network timeout. There are many reasons to catch these errors; e.g. the user could be asked to check the network connectivity, and try again. Errors should always be handled, and be properly presented to the user. A user is much more forgiving if your application fails with a clear reason, than if it simply crashes or refuses to work.</p>
<h3>Signal and Handle Exceptions</h3>
<p>Exceptions are thown in Objective-C, just as in most other programming languages. You can construct your <code>NSException</code> object manually, and throw it using the <code>@throw</code> compiler directive if you like. But the preferred way is to use the <code>NSException</code> convenience class methods.</p>
<pre class="brush: objc">[NSException raise:NSInvalidArgumentException
            format:@"Foo must not be nil"];
</pre>
<p>Here we see the first divergence from how for example Java and C# handles exceptions. In Objective-C different exceptions are not normally signaled by different subclasses, but instead the exception is given a name, in the form of a constant string. Exceptions are however handled quite traditionally.</p>
<pre class="brush: objc">@try {
    // Normal code flow, with potential exceptions
}
@catch (NSException* e) {
    // Handle exception or re-throw
}
@finally {
    // Mandatory cleanup
}</pre>
<h3>Signal and Handle Errors</h3>
<p>Errors do not use any special feature of the Objective-C run-time or programming language. Errors are instead treated as normal method arguments.</p>
<p>For synchronous tasks the error is returned as the last out argument of the method. A typical synchronous method signature with error handling looks like this:</p>
<pre class="brush: objc">- (id)initWithContentsOfURL:(NSURL *)url
                      error:(NSError **)outError</pre>
<p>The client of such a task can always pass <code>NULL</code> to explicitly ignore the details of the error, the method must therefor also signal the error by the return value. This is typically done by returning <code>nil</code>, or <code>NO</code> if no other return value should exist. Ignoring the error is never recommended.</p>
<p>For asynchronous tasks the error is returned as the last argument of a delegate method. A typical asynchronous method signature with error handling looks like this:</p>
<pre class="brush: objc">- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error</pre>
<p>The client of such a task can never opt out of receiving the error. It is still never recommended to ignore the error.</p>
<p>The information in an <code>NSError</code> is always localized and phrased in end-user friendly words. This is something you can trust of errors from system frameworks, and a hard requirement on you when you create your own errors. Therefor handling the error is never a burden, in the simplest case you can simply display the localized error message to the end user and call it a day.</p>
<pre class="brush: objc">- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
	[[[[UIAlertView alloc] initWithTitle:[error localizedDescription]
                                 message:[error localizedFailureReason]
                                delegate:nil
                       cancelButtonTitle:NSLocalizedString(@"OK", nil)
                       otherButtonTitles:nil] autorelease] show];
}</pre>
<h3>There is more to <code>NSError</code></h3>
<p>Cocoa and Cocoa Touch have much in common. Classes not brought straight over from Mac OS X to iOS often have a sibling anyway. One such class is <code>NSAlert</code> from Mac OS X and it's sibling <code>UIAlertView</code> on iOS. They serve the same purpose of displaying an alert message to the end user, optionally with a few choices in the form of buttons.</p>
<p>One convenience method for handling errors on Mac OS X is <code>-[NSAlert alertWithError:]</code>, it did not survive the transformation to <code>UIAlertView</code> on iOS. It is a pity, since it is a convenient way to quickly setup an alert with all the localized and human readable information. Basically turning the example code for handling an asynchronous error above from five lines of code, into a single line of code.</p>
<p>But that is not all. <code>NSAlert</code> and <code>NSError</code> on Mac OS X also have standardize facilities for handling recovery options. For example adding a <em>"Retry"</em> button to the alert, and calling the correct methods in response to this user selection.</p>
<p>On iOS <code>NSError</code> still have all the facilities to handle error recoveries, it is only <code>UIAlertView</code> that is lacking the final user facing bits. Fortunately this is easy to add. <code>NSError</code> manages error recovery with information held in it's userInfo dictionary. The following keys are used:
<ul>
<li><code>NSLocalizedRecoverySuggestionErrorKey</code> - A localized text with a general suggestion for how to recover from the error, for example <em>"Check the network connection"</em>.</li>
<li><code>NSLocalizedRecoveryOptionsErrorKey</code> - An array of localized button titles such as <em>"Retry"</em>.</li>
<li><code>NSRecoveryAttempterErrorKey</code> - An object conforming to the informal protocol <code>NSErrorRecoveryAttempting</code>.</li>
</ul>
<p>The informal protocol <code>NSErrorRecoveryAttempting</code> declares one method that is significant for iOS:</p>
<pre class="brush: objc">- (BOOL)attemptRecoveryFromError:(NSError *)error
                     optionIndex:(NSUInteger)recoveryOptionIndex</pre>
<p>The <code>recoveryOptionIndex</code> is the index into the array of button titles, and is the actual choice the user made for recovering from the error.</p>
<p>Adding a <code>-[UIAlertView alertWithError:]</code> convenience method to UIAlertView is made really easy since Objective-C has categories, and classes themselves are object instances so we can use the <code>UIAlertView</code> class as alert delegate for error recovery alerts.</p>
<pre class="brush: objc">@implementation UIAlertView (CWErrorHandler)

static NSMutableDictionary* cw_recoveryErrors = nil;

+(void)alertViewCancel:(UIAlertView *)alertView;
{
    NSValue* key = [NSValue valueWithPointer:(const void *)alertView];
    [cw_recoveryErrors removeObjectForKey:key];
}

+ (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    NSValue* key = [NSValue valueWithPointer:(const void *)alertView];
    NSError* error = [cw_recoveryErrors objectForKey:key];
	NSString* buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
    NSInteger recoveryIndex = [[error localizedRecoveryOptions]
                                   indexOfObject:buttonTitle];
    if (recoveryIndex != NSNotFound) {
	    [[error recoveryAttempter]
             attemptRecoveryFromError:error
                          optionIndex:recoveryIndex];
    }
    [cw_recoveryErrors removeObjectForKey:key];
}

+(UIAlertView*)alertViewWithError:(NSError*)error;
{
    UIAlertView* alert = [UIAlertView alloc];
    [[alert initWithTitle:[error localizedDescription]
                  message:[error localizedFailureReason]
                 delegate:nil
        cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
        otherButtonTitles:nil] autorelease];
    if ([error recoveryAttempter]) {
    	if (cw_recoveryErrors == nil) {
			cw_recoveryErrors = [[NSMutableDictionary alloc]
                                     initWithCapacity:4];
        }
        NSValue* key = [NSValue valueWithPointer:(const void *)alertView];

        [cw_recoveryErrors setObject:error
                              forKey:key];
        for (id recoveryOption in [error localizedRecoveryOptions]) {
        	[alert addButtonWithTitle:recoveryOption];
        }
        alert.delegate = (id)self;
    }
    return alert;
}

@end</pre>
<h3>Conclusion</h3>
<p>The clean separation of exceptions and errors help you as a developer to catch programming errors during development and with unit tests, and also handle errors of interest to the end users in a standardized and uniform way. The very nature of <code>NSError</code> encourages developers to write descriptive error messages that end users can understand and make informed discussions about. Errors are unavoidable in any application of non-neglectable complexity, gracefully handling these errors gives an aura of quality and ensures happy users. Happy users means better sales.</p>
<p>Full source code to the examples in this post, including some more convenience methods can be <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/10/UIAlertView+CWErrorHandler1.zip'>downloaded here</a>, and are released under the Apache 2 open source license. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Extending the JDT</title>
		<link>http://blog.jayway.com/2010/04/20/extending-the-jdt/</link>
		<comments>http://blog.jayway.com/2010/04/20/extending-the-jdt/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 21:01:43 +0000</pubDate>
		<dc:creator>Michael Kober</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5387</guid>
		<description><![CDATA[A couple of weeks ago I had a look at the Motodevstudio for Android developers and I think it has some quite nice features like code snippets or wizards for Android activities, services and more. Actually it's is quite easy to extend the eclipse JDT and provide such useful plugins. This blog post is about [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago I had a look at the <a href="http://developer.motorola.com/docstools/motodevstudio/">Motodevstudio</a> for Android developers and I think it has some quite nice features like code snippets or wizards for Android activities, services and more. Actually it's is quite easy to extend the eclipse JDT and provide such useful plugins. This blog post is about how to extend the NewElementWizard in JDT using eclipse Galileo.  </p>
<p>We start with creating a new eclipse plugin project and create our wizard class. The NewElementWizard we want to extend resides in the <code>org.eclipse.jdt.ui</code> bundle. So we add both <code>org.eclipse.jdt.ui</code> and <code>org.eclipse.jdt.core</code> to our plugin manifest:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/Screen-shot-2010-02-28-at-9.53.40-PM.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/Screen-shot-2010-02-28-at-9.53.40-PM-300x234.png" alt="Manifest" title="Manifest" width="300" height="234" class="alignnone size-medium wp-image-5388" /></a></p>
<p>Then we create a new class "NewActivityWizard":</p>
<pre class="brush:java">
package newwizard;

import org.eclipse.jdt.internal.ui.wizards.NewElementWizard;

public class NewActivityWizard extends NewElementWizard {

}
</pre>
<p>First thing we get is a warning<br />
"Discouraged access: The type NewElementWizard is not accessible due to restriction on required library /Applications/eclipse/plugins/org.eclipse.jdt.ui_3.5.1.r351_v20090821-0800.jar".</p>
<p>The NewElementWizard belongs to an internal package and is only exported (using the 'xfriends' directive) to some chosen bundles. So we have the choice to have a look at the code of NewElementWizard and implement our wizard by extending <code>org.eclipse.jface.wizard.Wizard</code> instead, or we could make our plugin a fragment. Fragments are part of the OSGi R4 release and according to the specification a fragment is “a bundle that is attached to a host bundle”, adding content to the target bundle. For now we choose the later alternative, just because it requires less work.</p>
<p>Next thing we have to do is to override some methods of the superclass and of course we want to add our own wizard page. Our wizardpage will extend the <code>org.eclipse.jdt.ui.wizards.NewTypeWizardPage</code>. The following code is pretty much the same as in the wizards used internally in JDT as for example <code>org.eclipse.jdt.internal.ui.wizards.NewClassCreationWizard</code>. </p>
<pre class="brush:java">
public class NewActivityWizard extends NewElementWizard {

	private NewActivityWizardPage newActivityPage = null;

	public NewActivityWizard() {
        setWindowTitle("My new Android Activity");
        newActivityPage = new NewActivityWizardPage();
    }

	@Override
	public void addPages() {
        addPage(newActivityPage);
    }

    @Override
	 public void init(IWorkbench workbench, IStructuredSelection selection) {
    	newActivityPage.init(selection);
    }

    @Override
	public boolean canFinish() {
       return super.canFinish() &&
                   getContainer().getCurrentPage() == newActivityPage;
    }

	@Override
	protected void finishPage(IProgressMonitor monitor)	throws InterruptedException, CoreException {
		newActivityPage.createType(monitor);
	}

	@Override
	public IJavaElement getCreatedElement() {
		return newActivityPage.getCreatedType();
	}
}
</pre>
<p>Next we have to define the extension in the fragment.xml:</p>
<pre class="brush:xml">
 <extension  point="org.eclipse.ui.newWizards">
      <wizard
            canFinishEarly="false"
            category="com.android.ide.eclipse.wizards.category"
            class="newwizard.NewActivityWizard"
            finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
            id="newwizard.NewActivityWizard"
            name="My Android Activity"
            preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
            project="false">
      </wizard>
   </extension>
</pre>
<p>The most interesting part of the wizard page is the code generation part. We want to generate a <code>onCreate</code> method that takes a <code>android.os.Bundle</code> as argument:</p>
<pre class="brush:java">
private void generateOnCreate(IType type, ImportsManager imports) throws CoreException, JavaModelException {
	StringBuilder buf = new StringBuilder();
	final String delim = "\n";
	buf.append("@Override");
	buf.append(lineDelim);
	buf.append("public void onCreate(");
	buf.append(imports.addImport("android.os.Bundle"));
	buf.append(" savedInstanceState) {");
	buf.append(lineDelim);
	buf.append("super.onCreate(savedInstanceState);");
	buf.append(lineDelim);
	final String content =
            CodeGeneration.getMethodBodyContent(type.getCompilationUnit(),
               type.getTypeQualifiedName('.'), "onCreate", false, "", delim);
	if (content != null && content.length() != 0)
		buf.append(content);
	buf.append(lineDelim);
	buf.append("}"); //$NON-NLS-1$
	type.createMethod(buf.toString(), null, false, null);
}
</pre>
<p>This is just the basic version of the new wizard, we also want to add intent actions and categories and update the Android manifest file. The complete source is available at <a href="http://github.com/kobmic/adt-extensions">http://github.com/kobmic/adt-extensions</a>. 	</p>
<p>So how do we update the android manifest? As a Java programmer <a href="http://www.dom4j.org">dom4j</a> and <a href="http://xstream.codehaus.org">XStream</a> are some of my favourite XML frameworks - but I'm quite enthusiastic about Scala and Scala provides XML support baked into the language. The XML generation code for a new Android activtiy with a given list of intent actions and categories in Scala looks like this:</p>
<pre class="brush:scala">
def createXML(activityName: String, intentActions: List[String], intentCategories: List[String]) : Node = {
  val xml =
    <activity android:name={activityName}
      <intent-filter>
         {for(action <- intentActions)
             yield {<action android:name={action} />}}
	 {for(category <- intentCategories)
             yield {<category android:name={category} />}}
      </intent-filter>
    </activity>
   xml
}
</pre>
<h2>Putting it all together</h2>
<p>I chose to do the XML manipulation (written in Scala) and the Wizard (written in Java) in different OSGi bundles. If you don't have the eclipse Scala IDE installed you even need the Scala library 2.7.7 as OSGi bundle. You can download the wizard with or without Scala dependencies from <a href="http://github.com/kobmic/adt-extensions/downloads">http://github.com/kobmic/adt-extensions/downloads</a>. </p>
<p>The complete wizard looks like this:<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/new-activity-wizard.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/new-activity-wizard-228x300.png" alt="" title="new-activity-wizard" width="228" height="300" class="aligncenter size-medium wp-image-5389" /></a></p>
<p>At time of writing there's a new version of MOTODEV studio available, now even as a set of plugins to eclipse:<br />
<a href="http://developer.motorola.com/docstools/library/Installing_MOTODEV_Studio_for_Android">http://developer.motorola.com/docstools/library/Installing_MOTODEV_Studio_for_Android/#installingStudioPlugins</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/20/extending-the-jdt/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Performing any Selector on the Main Thread</title>
		<link>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/</link>
		<comments>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 14:57:48 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5209</guid>
		<description><![CDATA[Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:] in Foundation. Making updating the text for a text field a snap: [someTextField [...]]]></description>
			<content:encoded><![CDATA[<p>Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example <code>-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]</code> in Foundation. Making updating the text for a text field a snap:</p>
<pre class="brush:objc">[someTextField performSelectorOnMainThread:@selector(setText:)
                              	withObject:@"A new text"
                             waitUntilDone:YES];</pre>
<h3>But not everything is an object</h3>
<p>Since Objective-C is a superset of C, there are still all the types from C available. Such as all the primitives, including enums, and more complex struct types. Cocoa Touch is pragmatic and will use the most proper type for the use-case, not forcing everything into a square OOP hole.</p>
<p>This makes it quite hard to call for example <code>-[UIView setHidden:]</code>, that takes a single <code>BOOL</code> argument. Same for <code>-[UIView setFrame:]</code>, that takes a single <code>CGRect</code> struct argument, that in turn consists of one <code>CGPoint</code> and one <code>CGSize</code> struct.</p>
<p>Every type imaginable in C can be bundled in an <code>NSValue</code> instance. So we could bundle up the <code>BOOL</code> primitive, or the <code>CGRect</code> struct in a <code>NSValue</code> object. Then pass that object to the main thread, where it is unbundled and passed to the desired method. Quite cumbersome as it requires us to bundle, and unbundle types manually, and implement at least one extra method.</p>
<h3>There must be an easier way</h3>
<p>It turns out that <code>NSInvocation</code> can also handle any imaginable C type, or else it would not be able to invoke any imaginable Objective-C method. Making a <code>NSInvocation</code> invoke its method on the main thread is easy enough. Just add a category to the <code>NSInvocation</code> class, with a new method like this:</p>
<pre class="brush:objc">-(void)invokeOnMainThreadWaitUntilDone:(BOOL)wait;
{
  [self performSelectorOnMainThread:@selector(invoke)
                         withObject:nil
                      waitUntilDone:wait];
}</pre>
<p>So now all you need to do is to create a <code>NSInvocation</code> object, fill it in with the primitive or struct types, and invoke it on the main thread. But creating and setting up a <code>NSInvocation</code> object is also a bit on the boring side...</p>
<h3>There must be an even easier way!</h3>
<p>We could use variable argument lists from plain old C. Too bad that they are untyped?<br />
No despair, we know the target object for our invocation, and we know what method to call. So we have what we need to fetch the <code>NSMethodSignature</code> object for the call, that contains all the type information we need to safely process the <code>va_list</code>.</p>
<p>Our target machine is a Mac running 32- or 64-bit Intel CPU, or an iPhone OS device with a 32 bit ARM CPU. Turns out that on both platforms <code>va_list</code> is simply a <code>void*</code> pointer, to the stack frame. Even better <code>va_start()</code> will always flush any argument passed into the register on the stack frame. So we can skip most of the boring argument handling, by treating the arguments like a byte buffer, only advancing and aligning the buffer according to the information in the <code>NSMethodSignature</code> object.</p>
<p>A convenience method for creating a <code>NSInvocation</code> object for a particular target, selector, and list of variable arguments, would turn out like this:</p>
<pre class="brush:objc">+(NSInvocation*)invocationWithTarget:(id)target
                            selector:(SEL)aSelector
                     retainArguments:(BOOL)retainArguments, ...;
{
  va_list ap;
  va_start(ap, retainArguments);
  char* args = (char*)ap;
  NSMethodSignature* signature = [target methodSignatureForSelector:aSelector];
  NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
  if (retainArguments) {
    [invocation retainArguments];
  }
  [invocation setTarget:target];
  [invocation setSelector:aSelector];
  for (int index = 2; index < [signature numberOfArguments]; index++) {
    const char *type = [signature getArgumentTypeAtIndex:index];
    NSUInteger size, align;
    NSGetSizeAndAlignment(type, &size, &align);
    NSUInteger mod = (NSUInteger)args % align;
    if (mod != 0) {
      args += (align - mod);
    }
    [invocation setArgument:args atIndex:index];
    args += size;
  }
  va_end(ap);
  return invocation;
}
</pre>
<h3>Conclusion</h3>
<p>And now we can easily call any method on the main UI thread. </p>
<p>An example where a <code>CGRect</code> struct is used to update the UI components frame;</p>
<pre class="brush:objc">// Set new frame of a label.
[[NSInvocation invocationWithTarget:someLabel
                           selector:@selector(setFrame:)
                    retainArguments:NO, CGRectMake(40, 40, 200, 100)]
 invokeOnMainThreadWaitUntilDone:NO];</pre>
<p>A slightly more complex example, where we send a primitive int, and also waits for and fetches the result from the main thread:</p>
<pre class="brush:objc">// Query a UITableView for the number of rows in section 2.
NSInvocation* i = [NSInvocation invocationWithTarget:tableView
                                            selector:@selector(numberOfRowsInSection:)
                                     retainArguments:NO, (NSUInteger)2];
// Block this thread until method has been invoked and result is available.
[i invokeOnMainThreadWaitUntilDone:YES];
NSInteger numberOfRows;
[i getReturnValue:&numberOfRows];</pre>
<p>Download full source code here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/NSInvocation+CWVariableArguments.zip'>NSInvocation+CWVariableArguments.zip</a></p>
<p><em>Update: Example 2 was not 64-bit compatible as <a href="http://twitter.com/chmod007">David Remahl</a> pointed out to me. Added type cast to fix the error.</em></p>
<p><em>Update 2: A new version with some more features and small bug-fixes to BOOL, float and uint16_t types, plus proper unit tests can be downloaded here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/CWFoundationAsyncAdditions.zip'>CWFoundationAsyncAdditions.zip</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part V &#8211; More on Meshes</title>
		<link>http://blog.jayway.com/2010/02/15/opengl-es-tutorial-for-android-%e2%80%93-part-v/</link>
		<comments>http://blog.jayway.com/2010/02/15/opengl-es-tutorial-for-android-%e2%80%93-part-v/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 21:12:20 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[opengl es]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2590</guid>
		<description><![CDATA[I have a feeling that some of you have tried my tutorials and then thought "This is a 3D tutorial, but why is everything in 2D?". So in this tutorial we will make some real 3D meshes. This is also necessary for the following tutorials. When I started I had problems with finding out how [...]]]></description>
			<content:encoded><![CDATA[<p>I have a feeling that some of you have tried my tutorials and then thought "This is a 3D tutorial, but why is everything in 2D?". So in this tutorial we will make some real 3D meshes. This is also necessary for the following tutorials. </p>
<p>When I started I had problems with finding out how to programmatic make different meshes like cubes, cones and so on. I needed this so I easy easy could put my scenes together. So this tutorial will show how to make some of the basic primitives. They might not be the most effective way of creating them but it is a way of doing them.</p>
<p>Starting point will be from the source of the second tutorial. I will show you plane and cube and then give you a couple of hint for additional primitives.</p>
<h2>Design</h2>
<p>A good place to start when designing an OpenGL framework is to use the composite pattern. This is a start of how I would proceed:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/composite.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/composite.png" alt="" title="composite" width="593" height="216" class="aligncenter size-full wp-image-4795" /></a></p>
<p>Let's start making out pattern.</p>
<h2>Mesh</h2>
<p>It's a good idea to have a common base for your meshes. So let us start by creating a class called Mesh.</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">opengl</span>.<span style="color: #006600;">tutorial</span>.<span style="color: #006600;">mesh</span>;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Mesh <span style="color: #66cc66;">&#123;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span></pre>
<p>We add the draw function from previous example, since I when over this function in a previous tutorial I just show it here:</p>
<pre class="java">    <span style="color: #808080; font-style: italic;">// Our vertex buffer.</span>
    <span style="color: #000000; font-weight: bold;">private</span> FloatBuffer verticesBuffer = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// Our index buffer.</span>
    <span style="color: #000000; font-weight: bold;">private</span> ShortBuffer indicesBuffer = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// The number of indices.</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">int</span> numOfIndices = <span style="color: #cc66cc;">-1</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// Flat Color</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> rgba = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#123;</span><span style="color: #cc66cc;">1</span>.0f, <span style="color: #cc66cc;">1</span>.0f, <span style="color: #cc66cc;">1</span>.0f, <span style="color: #cc66cc;">1</span>.0f<span style="color: #66cc66;">&#125;</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// Smooth Colors</span>
    <span style="color: #000000; font-weight: bold;">private</span> FloatBuffer colorBuffer = <span style="color: #000000; font-weight: bold;">null</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> draw<span style="color: #66cc66;">&#40;</span>GL10 gl<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #808080; font-style: italic;">// Counter-clockwise winding.</span>
	gl.<span style="color: #006600;">glFrontFace</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_CCW</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// Enable face culling.</span>
	gl.<span style="color: #006600;">glEnable</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_CULL_FACE</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// What faces to remove with the face culling.</span>
	gl.<span style="color: #006600;">glCullFace</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_BACK</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// Enabled the vertices buffer for writing and to be used during</span>
	<span style="color: #808080; font-style: italic;">// rendering.</span>
	gl.<span style="color: #006600;">glEnableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_VERTEX_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// Specifies the location and data format of an array of vertex</span>
	<span style="color: #808080; font-style: italic;">// coordinates to use when rendering.</span>
	gl.<span style="color: #006600;">glVertexPointer</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">3</span>, GL10.<span style="color: #006600;">GL_FLOAT</span>, <span style="color: #cc66cc;">0</span>, verticesBuffer<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #808080; font-style: italic;">// Set flat color</span>
        gl.<span style="color: #006600;">glColor4f</span><span style="color: #66cc66;">&#40;</span>rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>, rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>, rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#93;</span>, rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #808080; font-style: italic;">// Smooth color</span>
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> colorBuffer != <span style="color: #000000; font-weight: bold;">null</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #808080; font-style: italic;">// Enable the color array buffer to be used during rendering.</span>
            gl.<span style="color: #006600;">glEnableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_COLOR_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #808080; font-style: italic;">// Point out the where the color buffer is.</span>
            gl.<span style="color: #006600;">glColorPointer</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">4</span>, GL10.<span style="color: #006600;">GL_FLOAT</span>, <span style="color: #cc66cc;">0</span>, colorBuffer<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
	gl.<span style="color: #006600;">glDrawElements</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_TRIANGLES</span>, numOfIndices,
		GL10.<span style="color: #006600;">GL_UNSIGNED_SHORT</span>, indicesBuffer<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// Disable the vertices buffer.</span>
	gl.<span style="color: #006600;">glDisableClientState</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_VERTEX_ARRAY</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #808080; font-style: italic;">// Disable face culling.</span>
	gl.<span style="color: #006600;">glDisable</span><span style="color: #66cc66;">&#40;</span>GL10.<span style="color: #006600;">GL_CULL_FACE</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span></pre>
<p>We need functions where the subclasses can set the vertices and the indices. These function contains nothing new and are pretty much the same as you seen in earlier tutorials.</p>
<pre class="java">    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setVertices<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> vertices<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// a float is 4 bytes, therefore we multiply the number if</span>
	<span style="color: #808080; font-style: italic;">// vertices with 4.</span>
	ByteBuffer vbb = ByteBuffer.<span style="color: #006600;">allocateDirect</span><span style="color: #66cc66;">&#40;</span>vertices.<span style="color: #006600;">length</span> * <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span>;
	vbb.<span style="color: #006600;">order</span><span style="color: #66cc66;">&#40;</span>ByteOrder.<span style="color: #006600;">nativeOrder</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	verticesBuffer = vbb.<span style="color: #006600;">asFloatBuffer</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	verticesBuffer.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>vertices<span style="color: #66cc66;">&#41;</span>;
	verticesBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setIndices<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> indices<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// short is 2 bytes, therefore we multiply the number if</span>
	<span style="color: #808080; font-style: italic;">// vertices with 2.</span>
	ByteBuffer ibb = ByteBuffer.<span style="color: #006600;">allocateDirect</span><span style="color: #66cc66;">&#40;</span>indices.<span style="color: #006600;">length</span> * <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>;
	ibb.<span style="color: #006600;">order</span><span style="color: #66cc66;">&#40;</span>ByteOrder.<span style="color: #006600;">nativeOrder</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	indicesBuffer = ibb.<span style="color: #006600;">asShortBuffer</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	indicesBuffer.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>indices<span style="color: #66cc66;">&#41;</span>;
	indicesBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
	numOfIndices = indices.<span style="color: #006600;">length</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setColor<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> red, <span style="color: #993333;">float</span> green, <span style="color: #993333;">float</span> blue, <span style="color: #993333;">float</span> alpha<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #808080; font-style: italic;">// Setting the flat color.</span>
        rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span> = red;
        rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> = green;
        rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#93;</span> = blue;
        rgba<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#93;</span> = alpha;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setColors<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> colors<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// float has 4 bytes.</span>
	ByteBuffer cbb = ByteBuffer.<span style="color: #006600;">allocateDirect</span><span style="color: #66cc66;">&#40;</span>colors.<span style="color: #006600;">length</span> * <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span>;
	cbb.<span style="color: #006600;">order</span><span style="color: #66cc66;">&#40;</span>ByteOrder.<span style="color: #006600;">nativeOrder</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	colorBuffer = cbb.<span style="color: #006600;">asFloatBuffer</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	colorBuffer.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>colors<span style="color: #66cc66;">&#41;</span>;
	colorBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span></pre>
<p>We need to add a couple of things. When we start working with multiple meshes we need to be able to move and rotate them individual so let us add translation and rotation parameters:</p>
<pre class="java">    <span style="color: #808080; font-style: italic;">// Translate params.</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">float</span> x = <span style="color: #cc66cc;">0</span>;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">float</span> y = <span style="color: #cc66cc;">0</span>;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">float</span> z = <span style="color: #cc66cc;">0</span>;
&nbsp;
    <span style="color: #808080; font-style: italic;">// Rotate params.</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">float</span> rx = <span style="color: #cc66cc;">0</span>;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">float</span> ry = <span style="color: #cc66cc;">0</span>;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">float</span> rz = <span style="color: #cc66cc;">0</span>;</pre>
<p>And use them in the draw function add this lines just before the gl.glDrawElements call.</p>
<pre class="java">    gl.<span style="color: #006600;">glTranslatef</span><span style="color: #66cc66;">&#40;</span>x, y, z<span style="color: #66cc66;">&#41;</span>;
    gl.<span style="color: #006600;">glRotatef</span><span style="color: #66cc66;">&#40;</span>rx, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
    gl.<span style="color: #006600;">glRotatef</span><span style="color: #66cc66;">&#40;</span>ry, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
    gl.<span style="color: #006600;">glRotatef</span><span style="color: #66cc66;">&#40;</span>rz, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;</pre>
<h2>Plane</h2>
<p>Let us start making a plane an quite easy task you might think and it kinda is. But to make it more interesting and more useful we need to be able to create it with some different settings like: width, depth, how many width segments and how many depth segments. </p>
<p>Just so we have the same terminology, width is the length over the x-axis, depth is over the z-axis and height is over the y-axis. Look at the image below as a visual input.<br />
<div id="attachment_4695" class="wp-caption alignright" style="width: 270px"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/terminology_1.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/terminology_1.png" alt="Width, height and depth." title="Width, height and depth." width="260" height="252" class="size-full wp-image-4695" /></a><p class="wp-caption-text">Width, height and depth.</p></div></p>
<p>Segments is how many parts the length should be divided by. This is useful if you need to make a surface that is not total even. If you create a plane over x, y and make z not all be 0 say you give z a random span from -0.1 to 0.1 you will get something you could use as a ground plane in a game just put a nice texture on it.<br />
<div id="attachment_4696" class="wp-caption alignright" style="width: 270px"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/terminology_2.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/terminology_2.png" alt="Segments." title="Segments." width="260" height="252" class="size-full wp-image-4696" /></a><p class="wp-caption-text">Segments.</p></div></p>
<p>Looking at the image above you see that the different segments gives you squares. Since we like it to be triangles so just split them up into 2 triangles.</p>
<p>I hate frameworks and classes that don't have a default setup and easy class constructors I try to always have more then one constructor. The constructors I will put in this plane is:</p>
<p>For an easy and quick setup:</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// Gives you a plane that is 1 unit wide and 1 unit high with just one segment over width and height.</span>
<span style="color: #000000; font-weight: bold;">public</span> Plane<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span></pre>
<p>An easy one just to change the size:</p>
<pre class="java"> <span style="color: #808080; font-style: italic;">// Let you decide the size of the plane but still only one segment.</span>
<span style="color: #000000; font-weight: bold;">public</span> Plane<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height<span style="color: #66cc66;">&#41;</span></pre>
<p>And finally one for setting up the plane with different segments:</p>
<pre class="java"><span style="color: #808080; font-style: italic;">// For alla your settings.</span>
<span style="color: #000000; font-weight: bold;">public</span> Plane<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height, <span style="color: #993333;">int</span> widthSegments, <span style="color: #993333;">int</span> heightSegments<span style="color: #66cc66;">&#41;</span></pre>
<p>If I in theory would construct a plane that is 1 unit wide and 1 units high with 4 segments in both width and height direction it would look like this images:<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/plane.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/plane-300x133.png" alt="" title="plane" width="300" height="133" class="aligncenter size-medium wp-image-4755" /></a><br />
The one to the left shows the segments and the one to the right show us the faces we need to create.</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">opengl</span>.<span style="color: #006600;">tutorial</span>.<span style="color: #006600;">mesh</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Plane <span style="color: #000000; font-weight: bold;">extends</span> Mesh <span style="color: #66cc66;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Plane<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Plane<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">this</span><span style="color: #66cc66;">&#40;</span>width, height, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Plane<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height, <span style="color: #993333;">int</span> widthSegments,
		<span style="color: #993333;">int</span> heightSegments<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> vertices = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">float</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#40;</span>widthSegments + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> * <span style="color: #66cc66;">&#40;</span>heightSegments + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
			* <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#93;</span>;
	<span style="color: #993333;">short</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> indices = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">short</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#40;</span>widthSegments + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> * <span style="color: #66cc66;">&#40;</span>heightSegments + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
			* <span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#93;</span>;
&nbsp;
	<span style="color: #993333;">float</span> xOffset = width / <span style="color: #cc66cc;">-2</span>;
	<span style="color: #993333;">float</span> yOffset = height / <span style="color: #cc66cc;">-2</span>;
	<span style="color: #993333;">float</span> xWidth = width / <span style="color: #66cc66;">&#40;</span>widthSegments<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #993333;">float</span> yHeight = height / <span style="color: #66cc66;">&#40;</span>heightSegments<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #993333;">int</span> currentVertex = <span style="color: #cc66cc;">0</span>;
	<span style="color: #993333;">int</span> currentIndex = <span style="color: #cc66cc;">0</span>;
	<span style="color: #993333;">short</span> w = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>widthSegments + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> y = <span style="color: #cc66cc;">0</span>; y &lt; heightSegments + <span style="color: #cc66cc;">1</span>; y++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> x = <span style="color: #cc66cc;">0</span>; x &lt; widthSegments + <span style="color: #cc66cc;">1</span>; x++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	        vertices<span style="color: #66cc66;">&#91;</span>currentVertex<span style="color: #66cc66;">&#93;</span> = xOffset + x * xWidth;
		vertices<span style="color: #66cc66;">&#91;</span>currentVertex + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> = yOffset + y * yHeight;
		vertices<span style="color: #66cc66;">&#91;</span>currentVertex + <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #cc66cc;">0</span>;
		currentVertex += <span style="color: #cc66cc;">3</span>;
&nbsp;
		<span style="color: #993333;">int</span> n = y * <span style="color: #66cc66;">&#40;</span>widthSegments + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> + x;
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>y &lt; heightSegments &amp;&amp; x &lt; widthSegments<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		    <span style="color: #808080; font-style: italic;">// Face one</span>
		    indices<span style="color: #66cc66;">&#91;</span>currentIndex<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#41;</span> n;
		    indices<span style="color: #66cc66;">&#91;</span>currentIndex + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>n + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
		    indices<span style="color: #66cc66;">&#91;</span>currentIndex + <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>n + w<span style="color: #66cc66;">&#41;</span>;
		    <span style="color: #808080; font-style: italic;">// Face two</span>
		    indices<span style="color: #66cc66;">&#91;</span>currentIndex + <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>n + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
		    indices<span style="color: #66cc66;">&#91;</span>currentIndex + <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>n + <span style="color: #cc66cc;">1</span> + w<span style="color: #66cc66;">&#41;</span>;
		    indices<span style="color: #66cc66;">&#91;</span>currentIndex + <span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">short</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>n + <span style="color: #cc66cc;">1</span> + w - <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		    currentIndex += <span style="color: #cc66cc;">6</span>;
		<span style="color: #66cc66;">&#125;</span>
	    <span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	setIndices<span style="color: #66cc66;">&#40;</span>indices<span style="color: #66cc66;">&#41;</span>;
	setVertices<span style="color: #66cc66;">&#40;</span>vertices<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<h2>Cube</h2>
<p>The next step I think a cube will be nice. I will only make a cube that you can set: height, width and depth on but I suggest you as a practice make it with segments just as we did with the plane. </p>
<p>The constructor will look like this:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> Cube<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height, <span style="color: #993333;">float</span> depth<span style="color: #66cc66;">&#41;</span></pre>
<p>And since I'm not doing this with any segments the constructor will be quite easy.</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">opengl</span>.<span style="color: #006600;">tutorial</span>.<span style="color: #006600;">mesh</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Cube <span style="color: #000000; font-weight: bold;">extends</span> Mesh <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> Cube<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height, <span style="color: #993333;">float</span> depth<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        width  /= <span style="color: #cc66cc;">2</span>;
        height /= <span style="color: #cc66cc;">2</span>;
        depth  /= <span style="color: #cc66cc;">2</span>;
&nbsp;
        <span style="color: #993333;">float</span> vertices<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#123;</span> -width, -height, -depth, <span style="color: #808080; font-style: italic;">// 0</span>
                              width, -height, -depth, <span style="color: #808080; font-style: italic;">// 1</span>
                              width,  height, -depth, <span style="color: #808080; font-style: italic;">// 2</span>
                             -width,  height, -depth, <span style="color: #808080; font-style: italic;">// 3</span>
                             -width, -height,  depth, <span style="color: #808080; font-style: italic;">// 4</span>
                              width, -height,  depth, <span style="color: #808080; font-style: italic;">// 5</span>
                              width,  height,  depth, <span style="color: #808080; font-style: italic;">// 6</span>
                             -width,  height,  depth, <span style="color: #808080; font-style: italic;">// 7</span>
        <span style="color: #66cc66;">&#125;</span>;
&nbsp;
        <span style="color: #993333;">short</span> indices<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#123;</span> <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span>,
                            <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">5</span>, <span style="color: #cc66cc;">1</span>,
                            <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">5</span>, <span style="color: #cc66cc;">6</span>,
                            <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">2</span>,
                            <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">7</span>,
                            <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">7</span>, <span style="color: #cc66cc;">3</span>,
                            <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">7</span>, <span style="color: #cc66cc;">4</span>,
                            <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">0</span>,
                            <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">7</span>, <span style="color: #cc66cc;">6</span>,
                            <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">5</span>,
                            <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span>,
                            <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #66cc66;">&#125;</span>;
&nbsp;
        setIndices<span style="color: #66cc66;">&#40;</span>indices<span style="color: #66cc66;">&#41;</span>;
        setVertices<span style="color: #66cc66;">&#40;</span>vertices<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>If you like to make it with segments the constructor could look like this:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> Cube<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> width, <span style="color: #993333;">float</span> height, <span style="color: #993333;">float</span> depth,
                 <span style="color: #993333;">int</span> widthSegments, <span style="color: #993333;">int</span> heightSegments, <span style="color: #993333;">int</span> depthSegments<span style="color: #66cc66;">&#41;</span></pre>
<p>Since we now have a plane that replaces the Square class ( in the code from tutorial II ) I will just remove it and in OpenGLRenderer change the square to a cube...</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> OpenGLRenderer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">// Initialize our cube.</span>
    cube = <span style="color: #000000; font-weight: bold;">new</span> Cube<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
    cube.<span style="color: #006600;">rx</span> = <span style="color: #cc66cc;">45</span>;
    cube.<span style="color: #006600;">ry</span> = <span style="color: #cc66cc;">45</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>... and render it.</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> onDrawFrame<span style="color: #66cc66;">&#40;</span>GL10 gl<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    ...
    <span style="color: #808080; font-style: italic;">// Draw our cube.</span>
    cube.<span style="color: #006600;">draw</span><span style="color: #66cc66;">&#40;</span>gl<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<h2>Group</h2>
<p>A group is really good to have when setting up and controlling your 3D scene. What a group really do is to distribute all commands sent to the group to all it's children. You can see the implementation of a simple group here:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">package</span> se.<span style="color: #006600;">jayway</span>.<span style="color: #006600;">opengl</span>.<span style="color: #006600;">tutorial</span>.<span style="color: #006600;">mesh</span>;
&nbsp;
<span style="color: #a1a100;">import java.util.Vector;</span>
&nbsp;
<span style="color: #a1a100;">import javax.microedition.khronos.opengles.GL10;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AGroup+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Group</span></a> <span style="color: #000000; font-weight: bold;">extends</span> Mesh <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> Vector&lt;Mesh&gt; children = <span style="color: #000000; font-weight: bold;">new</span> Vector&lt;Mesh&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> draw<span style="color: #66cc66;">&#40;</span>GL10 gl<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #993333;">int</span> size = children.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #b1b100;">for</span><span style="color: #66cc66;">&#40;</span> <span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>; i &lt; size; i++<span style="color: #66cc66;">&#41;</span>
            children.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>i<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">draw</span><span style="color: #66cc66;">&#40;</span>gl<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> add<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> location, Mesh object<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        children.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span>location, object<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> add<span style="color: #66cc66;">&#40;</span>Mesh object<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> children.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span>object<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> clear<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        children.<span style="color: #006600;">clear</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Mesh get<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> location<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> children.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>location<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Mesh remove<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> location<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> children.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span>location<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> remove<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> object<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> children.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span>object<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">int</span> size<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> children.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<p>Make the renderer work with a group as a root node and add your cube to it.</p>
<pre class="java"><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AGroup+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Group</span></a> group = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AGroup+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Group</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
Cube cube = <span style="color: #000000; font-weight: bold;">new</span> Cube<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
cube.<span style="color: #006600;">rx</span> = <span style="color: #cc66cc;">45</span>;
cube.<span style="color: #006600;">ry</span> = <span style="color: #cc66cc;">45</span>;
group.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span>cube<span style="color: #66cc66;">&#41;</span>;
root = group;</pre>
<p>And draw our scene:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> onDrawFrame<span style="color: #66cc66;">&#40;</span>GL10 gl<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    ...
    <span style="color: #808080; font-style: italic;">// Draw our scene.</span>
    root.<span style="color: #006600;">draw</span><span style="color: #66cc66;">&#40;</span>gl<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<h2>Suggestions</h2>
<p>It's always a good idea to have different primitives ready to use when you starting up a new project. My experience tell me that in 9 times of 10 you won't have any meshes from the graphic people when you start coding so it's really good to have some meshes to work with as place holders. I'll give you a hint of the way to start with your own meshes library by giving you an idea of how I would do it.</p>
<p>Creating your own meshes is a really good way of getting to know vertices and indices really close up.</p>
<h3>Cone</h3>
<p>After you have gotten your cube up and ready to go my suggestion is that you move onto a cone. A cone with the right settings could be more then just a cone. if you give is 3-4 sides it will be a pyramid. If you give it the same base and top radius it becomes a cylinder. So you can see why it is so useful. Take a look at this image and see what the this cone can do.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/cpc.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/cpc-300x109.png" alt="" title="cpc" width="300" height="109" class="aligncenter size-medium wp-image-4759" /></a></p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> Cone<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> baseRadius, <span style="color: #993333;">float</span> topRadius, <span style="color: #993333;">float</span> height, <span style="color: #993333;">int</span> numberOfSides<span style="color: #66cc66;">&#41;</span></pre>
<h3>Pyramid</h3>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Pyramid <span style="color: #000000; font-weight: bold;">extends</span> Cone <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> Pyramid<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> baseRadius, <span style="color: #993333;">float</span> height<span style="color: #66cc66;">&#41;</span>  <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>baseRadius, <span style="color: #cc66cc;">0</span>, height, <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<h3>Cylinder</h3>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Cylinder <span style="color: #000000; font-weight: bold;">extends</span> Cone <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> Cylinder<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> radius, <span style="color: #993333;">float</span> height<span style="color: #66cc66;">&#41;</span>  <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #66cc66;">&#40;</span>radius, radius, height, <span style="color: #cc66cc;">16</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<h3>One more thing</h3>
<p>Dividing up surfaces is a good thing to know about and by now you know how to divide up a regular square. To divide up a triangle look at the images below. It is a bit different and it might be a bit harder to implement.<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/triangle_seg.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/triangle_seg-300x154.png" alt="" title="triangle_seg" width="300" height="154" class="aligncenter size-medium wp-image-4761" /></a></p>
<h2>References</h2>
<p>The info used in this tutorial is collected from:<br />
<a href="http://developer.android.com/">Android Developers</a><br />
<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/">OpenGL ES 1.1 Reference Pages</a></p>
<p>You can download the source for this tutorial here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/02/Tutorial_Part_V.zip'>Tutorial_Part_V</a><br />
You can also checkout the code from: <a href='http://code.google.com/p/opengl-es-tutorial-for-android/source/checkout'>code.google.com</a></p>
<p>Previous tutorial: <a href="http://blog.jayway.com/2010/01/14/opengl-es-tutorial-for-android-%E2%80%93-part-iv-adding-colors/">OpenGL ES Tutorial for Android – Part IV – Adding colors</a><br />
Next tutorial: <a href="http://blog.jayway.com/2010/12/30/opengl-es-tutorial-for-android-%E2%80%93-part-vi-textures/">OpenGL ES Tutorial for Android – Part VI – Textures<br />
</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/02/15/opengl-es-tutorial-for-android-%e2%80%93-part-v/feed/</wfw:commentRss>
		<slash:comments>71</slash:comments>
		</item>
		<item>
		<title>Continuos Integration for XCode projects</title>
		<link>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/</link>
		<comments>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 17:35:59 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[hudson]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4624</guid>
		<description><![CDATA[Continuos Integration is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://martinfowler.com/articles/continuousIntegration.html" title="Continuous Integration">Continuos Integration</a> is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you and your team will be notified right away.
</p>
<p>
This is the second part of the blog post I wrote about <a href="http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/">TDD in XCode</a>. Make sure you've followed that tutorial before continuing here, or at least have a project of your own with OCUnit tests ready.
</p>
<p>
The server which we'll use is called <a href="https://hudson.dev.java.net/" title="Hudson">Hudson</a> and is very popular in the Java community. It does not readily support XCode projects but it does allow shell commands, so we'll use that to make our Calculator project compatible. We also want to fetch new versions of the source code as soon as it's checked in. We'll be a bit fancy and use <a href="http://git-scm.com/" title="Git - Fast Version Control System">Git</a> as source control software.	Here's a summary of what we want to do:
</p>
<ol>
<li>Download and install the Hudson continuos integration server</li>
<li>Download, install and setup the Git source control software as well as the Git plugin for Hudson</li>
<li>Download and install a script that converts OCUnit test results to JUnit format</li>
<li>Setup a new job in Hudson that checks out our XCode project and builds and tests it</li>
<li>Set up a notification and try it out</li>
</ol>
<h2>Downloading and Installing Hudson</h2>
<p>
In order to keep the instructions in this tutorial simple, we will have the source code repository and the build server itself on localhost. In real life you'll probably want to setup a dedicated machine.</p>
<p>Head over to the <a href="https://hudson.dev.java.net/" title="Hudson">Hudson web site</a> and download your copy of the server. Follow their included installation instructions, it's quite simple. Once you have Hudson up and running you can visit <a href="http://localhots:8080">http://localhost:8080</a> to see the welcome screen. By the way, when you're ready to install Hudson on a real remote server I recommend running it as a Servlet inside <a href="http://tomcat.apache.org/" title="Apache Tomcat - Welcome!">Apache Tomcat</a> instead.
</p>
<h2>Downloading and Setting Up Git</h2>
<p>Next we want to install Git. There are several ways to install it. The simplest might be to use <a href="http://code.google.com/p/git-osx-installer/">the OS X installer</a>, but I personally prefer <a href="http://www.macports.org/" title="The MacPorts Project">MacPorts</a>. Either way, go ahead and install it and make sure that you can use the "git" command from Terminal.app when you're done.
</p>
<p>
In the Terminal, change directory to your XCode project folder and type:</p>
<pre class="brush:bash">
		git init
	</pre>
<p>You now have a working source code repository in your project folder. Neat. Before you continue create a text file called <em>.gitignore</em> and let it contain:</p>
<pre class="brush:plain">
		build/*
		*.pbxuser
		*.mode1v3
		.DS_Store
		test-reports/*
	</pre>
<p>	That's a listing of the files and folders that should not be version controlled, since they are temporary or just used for XCode. Feel free to add any other files that you think only should be present locally. Now add all files (that aren't ignored) using:</p>
<pre class="brush:bash">
		git add *
	</pre>
<p>	and finally commit them to a first version using:</p>
<pre class="brush:bash">
		git commit -m "Initial import"
	</pre>
</p>
<h2>Fetching the Script</h2>
<p>
We need to fetch one more thing, <a href="http://github.com/ciryon/OCUnit2JUnit/blob/master/ocunit2junit.rb">ocunit2junit.rb</a>, which is a little Ruby script that I wrote. Since you now have git, you can also download it using git (or <em>clone the repo</em>, which is the correct term). Change directory to /tmp and then type like this:</p>
<pre class="brush:bash">git clone git://github.com/ciryon/OCUnit2JUnit.git</pre>
<p>Copy the script from /tmp/OCUnit2JUnit/ anywhere, like to /usr/local/bin/. Make sure it's executable by typing <em>chmod +x ocunit2junit.rb</em>.</p>
<p>The script will parse output from xcodebuild (the console command for building your XCode project) and look for output from OCUnit. The test results (success, failure, time passed etc) will be saved in the "test-reports" folder in the same XML format that JUnit uses. This also happens to be a format that Hudson understands.
</p>
<h2>Setting Up Hudson</h2>
<p>
Now head back to your Hudson welcome screen. Select <em>Manage Hudson</em>, <em>Manage plugins</em> and check "Hudson GIT plugin" under <em>Available</em>. Hudson will automatically download and install the plugin. Afterwards just restart Hudson.
</p>
<p>
We're ready to create a job in Hudson for our project. From the main screen select "New job", Build a free-style software project and call it "Calculator". There are some settings which you should fill in:</p>
<ul>
<li>
			Select to use git as source code management tool. The URL should be the file path to your project, like:
<pre class="brush:bash">/Users/youruser/XCodeProjects/Calculator/</pre>
</li>
<li>
			Select to poll SCM with Schedule:
<pre class="brush:bash">* * * * *</pre>
<p>			That means it'll check every minute if there are changes. If you want to check less often, do that.
		</li>
<li>
			Add new build step and select to execute shell. Use this command (make sure to point to the version of the iPhone SDK you want to use):</p>
<pre class="brush:plain">xcodebuild -target "UnitTests" -sdk /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.2.sdk/ -configuration "Debug" | /usr/local/bin/ocunit2junit.rb</pre>
</li>
<li>
			Select to also publish a JUnit test result report and the Test report XMLs reside at
<pre class="brush:plain">test-reports/*.xml</pre>
</li>
</ul>
<h2>Trying it out</h2>
<p>This is the moment of truth. Try to change your CalculatorTest.m so that one of the test cases fail. Type:</p>
<pre class="brush:bash">
	git -a commit CalculatorTest.m "Broke the test, on purpose"
</pre>
<p>and see what happens. If all goes well, and you have entered everything correctly,  Hudson should automatically notice there's a new version available, build it and try to run the test suite. Check the results and how it reports the test failure. Nice, eh? Fix the error and commit the test class again to see how Hudson reacts.
</p>
<p>
There are many settings, plugins and cool things to try out in Hudson. Go into Manage Hudson-> Configure system and setup your email settings, to allow Hudson to send mail. Then go back to configure your Calculator job and at the bottom select E-mail Notification. Enter your own email address and see how it works after you commits a file that breaks the build. If you don't want a mail, you can get an instant message, or perhaps have the server play a loud annoying sound? Everyone in your team should be aware of when a build fails, so it can be fixed right away. This is one of the great advantages of having a continuos integration server.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Boosting Android performance using JNI</title>
		<link>http://blog.jayway.com/2010/01/25/boosting-android-performance-using-jni/</link>
		<comments>http://blog.jayway.com/2010/01/25/boosting-android-performance-using-jni/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 13:03:12 +0000</pubDate>
		<dc:creator>Mattias Rosberg</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4390</guid>
		<description><![CDATA[JNI or Java Native Interface is the interface between the Java code running in a JVM and the native code running outside the JVM. It works both ways, that is you can use JNI to call native code from your Java programs and to call Java code from your native code. The native code normally [...]]]></description>
			<content:encoded><![CDATA[<p>JNI or Java Native Interface is the interface between the Java code running in a JVM and the native code running outside the JVM. It works both ways, that is you can use JNI to call native code from your Java programs and to call Java code from your native code. The native code normally resides within a library (.so file) and is typically written in C/C++.</p>
<p>There's a few reasons when to use JNI in a Java program</p>
<ul>
<li><strong>Wrap lower level functionality</strong> - Classes in the Android Application Framework uses JNI to interface with the underlying platform and hardware like Camera, Sensors and GPS.</li>
<li><strong>Interface native legacy code</strong> - You might have some old legacy code written in C/C++ and you don't want to waste your time porting the code to Java. With JNI you can create an interface class in Java that exposes the functionality of your legacy code.</li>
<li><strong>Bypass performance bottlenecks</strong> - Execute heavy number crunching in native code and get rid of the overhead that the instruction interpretation in the JVM introduces.
</ul>
<p>On Android, in order to prevent fragmentation, we are only allowed to use the following libraries in our native code.</p>
<ul>
<li>libc (C library) headers</li>
<li>libm (math library) headers</li>
<li>JNI interface headers</li>
<li>libz (Zlib compression) headers</li>
<li>liblog (Android logging) header</li>
<li>OpenGL ES 1.1 (3D graphics library) headers (since 1.6)</li>
<li>A Minimal set of headers for C++ support</li>
</ul>
<p>In this blog I will demonstrate how to transform a time consuming Java method with a lot of number crunching into a native declared method where the real work is performed in native code. Here's the time consuming Java method</p>
<pre class="brush:java">
public double compare(int[] sourceData,int[] targetData, double targetError) {
  double error = 0.0D;
  for (int index = 0; index < targetData.length; index++) {
    int c1 = sourceData[index];
    int c2 = targetData[index];
    int b = (c1 >> 16 & 255) - (c2 >> 16 & 255);
    int g = (c1 >> 8 & 255) - (c2 >> 8 & 255);
    int r = (c1 & 255) - (c2 & 255);
    error += r * r + g * g + b * b;
    if (error > targetError)
      return error;
  }
  return error;
}
</pre>
<p>The <strong>sourceData</strong> and <strong>targetData</strong> arguments represents the pixels of two Bitmaps. In short the method calculates the sum of the square distance in color between two images, pixel by pixel. If we compare two 200x200 pixels images the <strong>for-loop</strong> will run 40000 times! This is a typical candidate for when to use JNI.</p>
<h3>What to do in Native</h3>
<p>You can use the <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/boilerplate.c">boilerplate.c</a> file as boilerplate code for all your native c functions. </p>
<h4>Implement the native function</h4>
<p>This is what the function will look like when written in C.</p>
<pre class="brush:c">
static jdouble compareNative(JNIEnv *env, jobject thiz, jintArray sourceArr,
                                                jintArray targetArr, jdouble targetError){
  jdouble error = 0.0;
  int index, c1, c2, b, g, r  = 0;
  jint *sarr, *tarr;

  sarr = (*env)->GetIntArrayElements(env, sourceArr, NULL);
  tarr = (*env)->GetIntArrayElements(env, targetArr, NULL);

  if (sarr == NULL || tarr == NULL) {
         return targetError; /* exception occurred */
  }

  int size = (*env)->GetArrayLength(env, sourceArr);

  for (index = 0; index < size; index++) {
    c1 = sarr[index];
    c2 = tarr[index];
    b = (c1 >> 16 & 255) - (c2 >> 16 & 255);
    g = (c1 >> 8 & 255) - (c2 >> 8 & 255);
    r = (c1 & 255) - (c2 & 255);
    error += r * r + g * g + b * b;
    if (error > targetError){
      (*env)->ReleaseIntArrayElements(env, sourceArr, sarr, 0);
      (*env)->ReleaseIntArrayElements(env, targetArr, tarr, 0);
      return error;
    }
  }
 (*env)->ReleaseIntArrayElements(env, sourceArr, sarr, 0);
 (*env)->ReleaseIntArrayElements(env, targetArr, tarr, 0);
 return error;
}
</pre>
<p>All native functions must have the JNIEnv (a reference to the virtual machine itself) and the jobject (a reference to the "this pointer" of the Java object where the native method call comes from) as the first two arguments. Then we can add our own arguments. For more information on how to write native code for JNI see the <a href="http://java.sun.com/docs/books/jni/">JNI Reference Documentation</a>.</p>
<h4>Register your native functions</h4>
<p>We need a way to make the virtual machine direct the calls to the native declared Java method to our native C function. This is done using the <strong>registerNatives</strong> function of the JNIEnv. If you use the boilerplate C code from above you only have to do two things.</p>
<ol>
<li>Set the classpath variable to the full class name of your Java class (including package name). Replace the dots with slashes.</li>
<li>For each native declared method in Java, insert a JNINativeMethod struct into the <strong>methods[]</strong> array.</li>
</ol>
<p>For our example it will look like this</p>
<pre class="brush:c">
static const char *classPathName = "com/jayway/MyComparator";

static JNINativeMethod methods[] = {
  // nameOfNativeMethod, methodSignature, methodPointer
  {"compare", "([I[ID)D", (void*)compareNative },
};
</pre>
<p>The first parameter is the name of the native declared Java method, the second is the signature of the native declared Java method and the last parameter is the function pointer to the C function to execute when the native declared Java function is executed.</p>
<p>The signature of a Java method can be determined using the <strong>javap</strong> tool from SUN's Java SDK or you can create it yourself using the following table, <a href="http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/method.html">Java VM Type Signatures</a>.</p>
<h4>Build using Android NDK</h4>
<p>To make things really simple when developing JNI code Google has released the <a href="http://developer.android.com/sdk/ndk/1.6_r1/index.html">Android Native Development Kit (NDK)</a>. It's easy to setup and use. Just setup a new project according to the NDK documentation and build your project. In short, you create a folder named <strong>jni</strong> in your Android Eclipse project. Here you put all the c-files together with an Android.mk file. In the Android.mk you specify which c-files to compile. In the <strong>Android NDK/apps</strong> folder you create a directory named after your project (perhaps my-app). In this directory you add an Application.mk file. In the Application.mk, set the APP_PROJECT_PATH to the path of your Eclipse project. To create the <strong>lib</strong> simply type <strong>make APP=my-app</strong> from the console in your <strong>Android NDK</strong> folder. If everything goes well you will see a <strong>libs</strong> folder in your Eclipse project.</p>
<h3>What to do in Java</h3>
<p>In order to transform our Java method into a native declared method simply add the word <strong>native</strong> in the method signature and remove the implementation of the method.</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">double</span> compare<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> sourceData, <span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> targetData,
			<span style="color: #993333;">double</span> targetError<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>To make sure that the virtual machine loads our library into memory and register our native functions we have to add the following code.</p>
<pre class="brush:java">
static{
  System.loadLibrary("comparejni");
}
</pre>
<p>This tells the virtual machine to load the library <strong>lib</strong>comparejni<strong>.so</strong> from the underlying operating system. The OnLoad function is executed on the library and our native functions gets registered with the virtual machine.</p>
<h3>The Result</h3>
<p>After some simple benchmarking I found that the native declared method executed about 2-3 times faster than the original method executing within Dalvik. For larger images the improvement might be even bigger since a call to a native declared method takes more time than calling a normal Java method. Eventually, when Dalvik supports JIT compilation, we would probably get the above performance boost for free without calling native functions. But bear in mind, most devices on the market today will never get an upgraded Dalvik with JIT.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/25/boosting-android-performance-using-jni/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Test Driven Development in XCode</title>
		<link>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/</link>
		<comments>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 08:35:26 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4301</guid>
		<description><![CDATA[Test Driven Development, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the Three Rules of TDD that dictate the following: You are not allowed to write any production code unless it is to make a failing [...]]]></description>
			<content:encoded><![CDATA[<p>
        <a href="http://en.wikipedia.org/wiki/Test-driven_development" title="Test-driven development - Wikipedia, the free encyclopedia">Test Driven Development</a>, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the <a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd" title="TheThreeRulesOfTdd">Three Rules of TDD</a> that dictate the following:</p>
<ol>
<li>You are not allowed to write any production code unless it is to make a failing unit test pass.</li>
<li>You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.</li>
<li>You are not allowed to write any more production code than is sufficient to pass the one failing unit test.</li>
</ol>
<p>That means that test cases are written before any production code. Not all tests are written up front, it's rather that a small test is written, then a small piece of production code is written that only allows that test to pass. This is repeated in <a href="http://www.agiledata.org/essays/tdd.html">many small iterations</a>: test, fail, code, pass, test, fail, code, pass...<br/><br />
Many people consider TDD to encourage clean code, simple architectures and a stable system that's actually testable. Plus, it's also fun! We've <a href="/tag/tdd/">previously written</a> about various aspects of TDD, but in this tutorial we'll focus on how it works for XCode projects, where you write apps for Mac and iPhone. We will create a simple XCode project, do some special configuration steps and then demonstrate how TDD can be used to write your app. We're going to use <a href="http://www.sente.ch/software/ocunit/">OCUnit</a> and its framework SenTestingKit, which nowadays is included with Apple's XCode tools.
</p>
<h2>Creating the Calculator project</h2>
<p>
Let's start by creating a new project in XCode. You can pick any template, since we aren't going to touch the generated code. I picked a Window-based iPhone project. Name the project <em>Calculator</em>. Select New Target from the Project menu. Under Cocoa select Unit test Bundle. Call it <em>UnitTests</em> (I've had problems with space in the target name so avoid that) and add it to the project. We now need to change some small settings for this target. Select the UnitTests target and hit Command-I for Info. Select the Build tab and locate <em>Other Linker Flags</em>. Replace <em>Cocoa</em> with <em>Foundation</em>. Also remove the entry for <em>GCC_PREFIX_HEADER</em>.
</p>
<p>
Now it's time to create your test suite. Create a new group in your project and call it "Test Classes". Add a new File to this group and make sure it's a Cocoa->Objective-C test case class. Name it <em>CalculatorTest.m</em>. Uncheck "Also create CalculatorTest.h" since we don't need a header file. Don't add it to the Calculator target, but check it to be included in UnitTests. Open CalculatorTest.m file and above the @implementation declaration add:</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{

}
@end</pre>
<p>This is just because we don't want a rather empty header file. All your test classes will look like this.</p>
<p>Following TDD, we should build right away.  First make sure that the active target is "UnitTets" and then press the "Build" button. This will not only do a normal build, but also perform some shell script magic and actually execute the  unit tests. Now the build fails of course, since Calculator.h can't be found.</p>
<p>So let's add a file which represents production code. Create a new empty Cocoa Touch Objective-C class called Calculator.m (also create the .h file), this is the class that we want to test. Don't forget to check that they should be included in both your targets. Notice that we mix Cocoa and Cocoa Touch, that's is fine - all code is executed on your Mac. Build again, and this time you'll see in the build log that everything built and the test suite was executed, but contained 0 test cases. Let's remedy that.
</p>
<h2>Writing test cases</h2>
<p>
Next we want to write our first test case. Open up CalculatorTest.m and add the following method:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int result = [calculator add:5 to:6];
}</pre>
<p>All methods that start with "test" will be recognized as being a test case, and automatically run when building the target. Try and build and you'll unsurprisingly get the erro "unrecognized selector sent to instance...". That's all good. Let's add the add method to our Calculator class. In Calculator.h add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b;</pre>
<p>Then in Calculator.m add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b
{
        return 0;
}</pre>
<p>That should be enough to let it compile and run, right? Try it out! You'll see that it indeed build and executes the tests.
</p>
<p>
        Now we change the test so that it actually checks that we get the expected value back. We want to "assert" that the returned value is what we expected. Change the test case to look like this:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>Build and you see that the test runs and fails since our calculator always returns 0 regardless of the input. Change the production code so that it returns a+b and rerun the test. Nice, we have a successful build and our test works! Notice the fast cycle of test, code, fix, rerun. The point of TDD is to write tests and production code in small iterations so that you always have something stable (= the tests pass). If you follow the rules of TDD you'll have a growing amount of test cases and you'll right away know when something breaks.
</p>
<p>
Let's write one more test. Now we want to add the functionality to allow one number to be divided by another. Start up like before with a new test case like this:</p>
<pre class="brush:objc">-(void)testDivide
{
        Calculator* calculator = [[Calculator alloc] init];
        float expected = 2.5;
        int result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>You see, this time we expect to get back a float. Add the corresponding divide method to Calculator.h and Calculator.m. If you need help see the full code listing at the end of this article. You might notice that just returning a/b gives you 2.0. Type cast the return value to (float)a/b and you'll be fine. Go ahead when you got it working.
</p>
<p>
What happens if you try to divide something with zero? Well, why not add a test case for this scenario? If you're into maths you know that the result of this operation is undefined. How do you expect something to be undefined? This is tricky. <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  Start off by just expecting any number and see what you get back. As you see, the float value "inf" is returned. It seems like Objective-C treats the zero as "a value approaching zero" and that will indeed result in infinity in a division. But, hey, that might not be what we want our calculator to do. Let's change the test case to expect an exception to be raised instead:</p>
<pre class="brush:objc">-(void)testDivideByZero
{
        Calculator* calculator = [[Calculator alloc] init];
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}</pre>
<p>Build and notice the error message when no exception was raised. Now change the production code to something like this:</p>
<pre class="brush:objc">-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}</pre>
<p>Rerun and smile as the test passes! There are many different variants of asserts you can do with SenTestingKit. Compare objects with STAssertEqualObjects. STAssertTrue to check that a returned boolean is true. Open up SentTestCase_Macros.h if you want to see what you can play around with. By the way. You might have tried using NSLog in your test cases (just to experiment). This is nothing you would do in real life, as you want all necessary information in the fail message and output nothing if the test passes. Anyway, since the tests are actually run using a separate shell script for the UnitTest target you won't see the log in your console as usual. Instead check the build log and click the "text" icon to the right for the "Run test suite" step.
</p>
<h2>Wrapping up</h2>
<p>
Finally, if you look at your test class you might notice that we're allocating a new Calculator for every test case, and we never release them. That's no good. Luckily there are setUp and tearDown methods that will be launched automatically before and after each test case. Change your implementation to look like this (this is the final listing):</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{
        Calculator* calculator;
}
@end

@implementation CalculatorTest

- (void) setUp
{
        calculator = [[Calculator alloc] init];
}

-(void)tearDown
{
        [calculator release];
}

-(void)testAdd
{
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}

-(void)testDivide
{
        float expected = 2.5;
        float result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %f, but it was %f",expected,result);
}

-(void)testDivideByZero
{
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}
@end</pre>
</p>
<p>
For completeness, here's the listing for Calculator.h:</p>
<pre class="brush:objc">#import <Foundation/Foundation.h>

@interface Calculator : NSObject {

}

-(int)add:(int)a to:(int)b;
-(float)divide:(int)a by:(int)b;

@end</pre>
<p>and for Calculator.m:</p>
<pre class="brush:objc">#import "Calculator.h"

@implementation Calculator

-(int)add:(int)a to:(int)b
{
        return a+b;
}

-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}

@end</pre>
<p>Next blog post we'll see how to automate the running of test cases on a build server called Hudson!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part IV &#8211; Adding colors</title>
		<link>http://blog.jayway.com/2010/01/14/opengl-es-tutorial-for-android-%e2%80%93-part-iv-adding-colors/</link>
		<comments>http://blog.jayway.com/2010/01/14/opengl-es-tutorial-for-android-%e2%80%93-part-iv-adding-colors/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 20:38:16 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[opengl es]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2587</guid>
		<description><![CDATA[Last tutorial was about transformations. This tutorial will be a short one. I'm going to talk about adding color to your mesh. I will continue with the source code from tutorial II. Adding color 3D models with no colors are pretty boring so let's add some color to it. In general colors need no explanation. [...]]]></description>
			<content:encoded><![CDATA[<p>Last tutorial was about transformations. This tutorial will be a short one. I'm going to talk about adding color to your mesh. I will continue with the source code from tutorial II.</p>
<h2>Adding color</h2>
<p>3D models with no colors are pretty boring so let's add some color to it. In general colors need no explanation. OpenGL ES uses a color model called RGBA ( Red, Green, Blue and Alpha ). The first three are self explained. The fourth is transparency, how solid the color should be. If you like to read more about colors go to: <a href="http://en.wikipedia.org/wiki/Rgb">RGB color model - Wikipedia, the free encyclopedia</a></p>
<p>You might be familiar with defining colors with hex (#FF00FF) or with decimals (255, 0, 255) we will use 0..1 where 0 map to 0 (#00) and 1 map against 255 (#FF). </p>
<p>The easiest way of coloring meshes is called vertex coloring and I am going to show you two different ways of doing that. Flat coloring that gives one solid color and smooth coloring that will blend colors specified for each vertex. Texturing is also a way of giving your mesh colors but it is not vertex coloring so I will show you how to do that in a later tutorial.</p>
<h3>Flat coloring</h3>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/FlatColoring.png" align="right" alt="Flat Coloring" title="Flat Coloring" width="100" height="100" class="size-full wp-image-4221" />Flat coloring is really easy just tell OpenGL ES what color to use when it is going to render. One thing to remember is that when you set the color OpenGL ES uses this color until you change the color. This means that if you have two different squares and you tell OpenGL ES to change the color right before the second square the first frame the two squares will have different color but the next rendered frame both squares will have the same color.</p>
<p>To tell OpenGL ES what color to work with you use this command:</p>
<pre>public abstract void <a  href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glColor4f(float, float, float, float)" style="text-decoration: underline">glColor4f</a>(float red, float green, float blue, float alpha)</pre>
<p>The default values are: red = 1, green = 1, blue = 1 and alpha = 1. Those values are white, and that's why all the squares we previous made has a white color.</p>
<p>Create a new class called FlatColoredSquare it should be identical to the Square class. Then in the FlatColoredSquare function draw, add this line:</p>
<pre>gl.<a  href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glColor4f(float, float, float, float)" style="text-decoration: underline">glColor4f</a>(0.5f, 0.5f, 1.0f, 1.0f); // 0x8080FFFF</pre>
<p><em>I usually add a comment like the one above ( // 0x8080FFFF ) because I am used to read that. It makes it easier for me when reviewing the code.</em></p>
<p>It should now look like this:</p>
<pre>public void draw(GL10 gl) {
        gl.<a  href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glColor4f(float, float, float, float)" style="text-decoration: underline">glColor4f</a>(0.5f, 0.5f, 1.0f, 1.0f);
        ...
</pre>
<p>Then change in the renderer so it uses the FlatColoredSquare instead of the Square.</p>
<pre>
public class OpenGLRenderer implements Renderer {
	private FlatColoredSquare flatSquare; // CHANGED

	public OpenGLRenderer() {
		// Initialize our square.
		flatSquare = new FlatColoredSquare(); // CHANGED
	}

        public void onDrawFrame(GL10 gl) {
                ...
		flatSquare.draw(gl); // Don't forget to change this one.
                ...
	}
</pre>
<p><em>Remember that anything rendered after you set a color uses the same color and that this spans over frames and will not be reset in-between.</em></p>
<p>If you compile and run the application you will see one big flat colored blue square.</p>
<p>Just to give place to the smooth colored square coming up we move the flat square up.</p>
<pre>
public void onDrawFrame(GL10 gl) {
	gl.glLoadIdentity();
	// Translates 7 units into the screen and 1.5 units up.
	gl.glTranslatef(0, 1.5f, -7);
        // Draw our flat square.
	flatSquare.draw(gl);
}
</pre>
<p><em>Notice that with flat coloring you don't need to tell OpenGL ES to turn it on or off. OpenGL ES uses flat coloring as a default way of coloring the meshes.</em></p>
<h3>Smooth coloring</h3>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/SmoothColoring.png" align="right" alt="Smooth Coloring" title="Smooth Coloring" width="100" height="100" class="size-full wp-image-4221" />Smooth coloring is gained when you give each vertex its own color. OpenGL ES will interpolate the colors between the vertices and you will gain a smooth coloring effect. Just as with the flat coloring you tell OpenGL ES what to work with and it will be used as long as you don't say anything else. </p>
<p>Create a new class called SmoothColoredSquare it should be identical to the Square class just as you did with the FlatColoredSquare. Modify the new class with this:</p>
<p>Define the colors you like your vertices to have.</p>
<pre>
public class SmoothColoredSquare {
        ...
        // The colors mapped to the vertices.
        float[] colors = {
                1f, 0f, 0f, 1f, // vertex 0 red
                0f, 1f, 0f, 1f, // vertex 1 green
                0f, 0f, 1f, 1f, // vertex 2 blue
                1f, 0f, 1f, 1f, // vertex 3 magenta
        };
        ...
</pre>
<p>The order of defining the colors are important since they map against the <em>vertices</em> so in this example above the first color (1f, 0f, 0f, 1f ) map against the top left vertex ( -1.0f,  1.0f, 0.0f ) the green against the bottom left vertex and the rest you can figure out. Hint: Look at the image above.</p>
<p>And put them in a buffer just as we did with the vertices and indices.</p>
<pre>
public SmoothColoredSquare() {
	...

	// float has 4 bytes, colors (RGBA) * 4 bytes
	ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
	cbb.order(ByteOrder.nativeOrder());
	colorBuffer = cbb.asFloatBuffer();
	colorBuffer.put(colors);
	colorBuffer.position(0);
	}
</pre>
<p>Don't forget to add colorBuffer as a variable to the class as well.</p>
<pre>
        // Our color buffer.
	private FloatBuffer colorBuffer;
</pre>
<p>We also need to enable the color buffer and tell openGL where it is.</p>
<pre>
public void draw(GL10 gl) {
        ...
	gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);

	// Enable the color array buffer to be used during rendering.
	gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // NEW LINE ADDED.
	// Point out the where the color buffer is.
	gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer); // NEW LINE ADDED.

	gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
				GL10.GL_UNSIGNED_SHORT, indexBuffer);
	...
        // Disable the color buffer.
	gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
        ...
	}
</pre>
<p><em>Don't forget to disable the use of the color array. If you don't disable the color array both squares will be smooth colored. Try it.</em></p>
<p>Let's use this new smooth square as well. Start by adding it to your renderer.</p>
<pre>
public class OpenGLRenderer implements Renderer {
	private FlatColoredSquare flatSquare;
	private SmoothColoredSquare smoothSquare; // NEW LINE ADDED.

	public OpenGLRenderer() {
		// Initialize our squares.
		flatSquare = new FlatColoredSquare();
		smoothSquare = new SmoothColoredSquare(); // NEW LINE ADDED.
	}
</pre>
<p>We need to move the square down a bit so they don't collide. </p>
<pre>
public void onDrawFrame(GL10 gl) {
	...
        // Translate to end up under the flat square.
	gl.glTranslatef(0, -3f, 0);
	// Draw our smooth square.
	smoothSquare.draw(gl);
}
</pre>
<p>Now if you compile and run the application you will see two squares, one solid blue and one smooth with different colors.</p>
<h2>References</h2>
<p>The info used in this tutorial is collected from:<br />
<a href="http://developer.android.com/">Android Developers</a><br />
<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/">OpenGL ES 1.1 Reference Pages</a></p>
<p>You can download the source for this tutorial here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/Tutorial_Part_IV.zip'>Tutorial_Part_IV</a><br />
You can also checkout the code from: <a href='http://code.google.com/p/opengl-es-tutorial-for-android/source/checkout'>code.google.com</a></p>
<p>Previous tutorial: <a href="http://blog.jayway.com/2010/01/01/opengl-es-tutorial-for-android-–-part-iii-–-transformations/">OpenGL ES Tutorial for Android – Part III – Transformations</a><br />
Next tutorial: <a href="http://blog.jayway.com/2010/02/15/opengl-es-tutorial-for-android-–-part-v/">OpenGL ES Tutorial for Android – Part V – More on Meshes</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/14/opengl-es-tutorial-for-android-%e2%80%93-part-iv-adding-colors/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part III – Transformations</title>
		<link>http://blog.jayway.com/2010/01/01/opengl-es-tutorial-for-android-%e2%80%93-part-iii-%e2%80%93-transformations/</link>
		<comments>http://blog.jayway.com/2010/01/01/opengl-es-tutorial-for-android-%e2%80%93-part-iii-%e2%80%93-transformations/#comments</comments>
		<pubDate>Fri, 01 Jan 2010 19:56:39 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[opengl es]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2643</guid>
		<description><![CDATA[Last tutorial was about building your polygons. This tutorial is all about transformations, how to move the polygons around. I will continue this tutorial from where the previous ended so you can use that source code or make a copy of it. I am not going to bore you with a lot of mathematics but [...]]]></description>
			<content:encoded><![CDATA[<p>Last tutorial was about building your polygons. This tutorial is all about transformations, how to move the polygons around. I will continue this tutorial from where the previous ended so you can use that source code or make a copy of it.</p>
<p>I am not going to bore you with a lot of mathematics but I believe it is important to know that when OpenGL render a mesh it multiplies all vertices with a matrix. All the transformations you do are about manipulating the vertices in different ways by modifying this matrix. You can think of the matrix as a paper and that you never move the pen before you start to draw. You always draw in the center. But by doing a translation on the matrix you are moving the paper and also the center. A rotation is like rotating the paper around the center. And a scale is a bit harder to visualize with the paper view but it is like changing the unit size regarding to how you translate your meshes. Usually you talk about transformations according to the mesh not the world, but it is still important to know about.</p>
<h2>Coordinate System</h2>
<table>
<tr>
<td valign="top">
      OpenGL uses a so called right-handed coordinate system. A system is called right-handed if you look from the positive end towards the origin of the axis the counter-clockwise rotation is considered to be a positive rotation.</p>
<p>When you have started up your view and haven't applied any transformations the axis are aligned like this: The x-axis goes from left to right, the y-axis comes from the bottom and goes up and the z-axis is moving from the back of the screen towards the front of the screen.
    </td>
<td>
        <img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/3DCoord.png" alt="Coordinate System" title="Coordinate System" width="200" height="200" class="size-full wp-image-3044" />
    </td>
</tr>
</table>
<h2>Translate</h2>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glTranslatef(float, float, float)" style="text-decoration: underline">glTranslatef</a> (float x, float y, float z) //<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glTranslate.xml" style="text-decoration: underline">OpenGL docs.</a></pre>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/2DCoord1.png" alt="Coordinate System" title="Coordinate System" width="200" height="200" class="size-full wp-image-3044" align="right"/>A translations added to the matrix makes the mesh appear as it has been moved. Translations are made along the axis and with no rotation added the axis are in there default state. Translation affects all the vertices in a polygon the same amount over the same axis. Translations are simply additions and subtractions to a current value. The image to the right shows a translation in 2 dimensions.<br />
The start point is {x:-2, y:1} we like to go to {x:1, y:3} so we add {x:3, y:2}. </p>
<p>A simple addition: {x:-2, y:1} + {x:3, y:2} = {x:-2 + 3, y:1 + 2} = {x:1, y:3}.</p>
<p>In 3 dimensions we do the same, if we are located at position: {x:1, y:1, z:0} and we like to move 3 units into the screen we add {x:0, y:0, z:-3} and end up at: {x:1, y:1, z:-3}. </p>
<p>In the last tutorial we moved the square 4 units into the screen just to be able to see the square. What we did was that we added {x:0, y:0, z:-4} to the current position. This is the code we used for the translation:</p>
<pre>
// Translates 4 units into the screen.
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glTranslatef(float, float, float)" style="text-decoration: underline">glTranslatef</a>(0, 0, -4); <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glTranslate.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<p><em>If you do several translations after each other the order of the movement is along the X, Y and Z axis, in that order. On translate the order isn't so important but when we do a rotation it's really important.</em></p>
<p>It can be quite tricky to remember how the axis are aligned. Fortunate there is a good trick to remember the direction of the axis. Hold your left hand like the photo below. The point on each finger represents the positive direction on one axis. Your thumb is y-axis, index finger is x-axis and your middle finger would represent the z-axis. When I first started with 3D programming I actually wrote the letters, x, y and z on my fingers <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/axis_a.jpg" alt="Help with the axis." title="Help with the axis." width="300" height="236" class="size-full wp-image-3113" /></center></p>
<h2>Rotate</h2>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(float angle, float x, float y, float z)//<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a></pre>
<table>
<tr>
<td valign="top">
       Rotating is what it sounds like. You add a rotation to the matrix making it appears like the mesh are rotated. With no translation before the rotation is around the origo. The x, y and z values defines the vector to rotate around. The angle value is the number of degrees to rotate.
    </td>
<td valign="top">
        <img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Rotate.png" alt="Coordinate System" title="Coordinate System" width="200" height="200" class="size-full wp-image-3044" />
    </td>
</tr>
</table>
<p>If you remember these three things you will manage rotation quite easy.</p>
<p><strong>1. The rotation value are in degrees.</strong><br />
Most frameworks and math functions on computers use radians but OpenGL use degrees.</p>
<p><strong>2. When doing several rotations the order are important. </strong><br />
If you like to restore a rotation you negate the angle or all the axis like this: glRotatef(angle, x, y, z) is restored with glRotatef(angle, -x, -y, -z) or glRotatef(-angle, x, y, z).</p>
<p>But if you do several rotations after each other like this:</p>
<pre>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, 1.0f, 0.0f, 0.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, 0.0f, 1.0f, 0.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, 0.0f, 0.0f, 1.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<p><center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/PositiveRotation.png" alt="gl.gRotatef(90f, 1.0f, 1.0f, 1.0f)" title="gl.gRotatef(90f, 1.0f, 1.0f, 1.0f)" class="size-full wp-image-3044" /></center></p>
<p>And want to restore the mesh to it's original position you can't just negate the angle like this:</p>
<pre>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, -1.0f, 0.0f, 0.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, 0.0f, -1.0f, 0.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, 0.0f, 0.0f, -1.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<p><center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/NegativeRotation.png" alt="gl.gRotatef(90f, -1.0f, -1.0f, -1.0f)" title="gl.gRotatef(90f, -1.0f, -1.0f, -1.0f)" class="size-full wp-image-3044" /></center></p>
<p>You have to revert the order of the rotations as well like this:</p>
<pre>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, 0.0f, 0.0f, -1.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, 0.0f, -1.0f, 0.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glRotatef(float, float, float, float)" style="text-decoration: underline">glRotatef</a>(90f, -1.0f, 0.0f, 0.0f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<p><em>The order of several rotations is important.</em></p>
<p><strong>3. If you look from the positive end towards the origin of the axis the positive rotation is counter-clockwise.</strong><br />
If you take a pencil in your hand, let the point be in the same direction as your thumb, as in the picture below, then aligns the pencil with the x-axis. Let the pencil's point be aligned with the positive direction of the axis.   Your other fingers will now point in the positive direction of the rotation over that axis.</p>
<p><center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/rotation_a.jpg" alt="Positive rotation." title="Positive rotation." width="300" height="200" class="size-full wp-image-3141" /></center></p>
<h2>Translate & Rotate</h2>
<p>Since both rotation and translations are made within each mesh own coordinate system it is important to remember that the order you do the translation and rotation are very important.</p>
<p>If you do a translation on the mesh first and then rotate it, the translation is made on the current state of the mesh coordinate system and then rotated at the new location.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/TranslateRotate.png" alt="Translate Rotate" title="Translate Rotate" width="485" height="144" class="size-full wp-image-3141" /></center><br />
If you first rotate and the move the mesh it will be moved accordingly to its own rotated coordinate system.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/RotateTranslate.png" alt="Translate Rotate" title="Translate Rotate" width="485" height="144" class="size-full wp-image-3141" /></center>  </p>
<h2>Scale</h2>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glScalef(float, float, float)" style="text-decoration: underline">glScalef</a> (float x, float y, float z) // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glScale.xml" style="text-decoration: underline">OpenGL docs.</a></pre>
<p>Scaling is just as it sounds and it is possible to scale over each axis separately. Scaling is the same as multiplying all vertexes with the same scalar. In the image below we scale with: gl.glScalef(2f, 2f, 2f). That means that we multiply all vertixes with 2.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Scale.png" alt="Scale." title="Scale." width="485"class="size-full wp-image-3141" ></center></p>
<h2>Translate & Scale</h2>
<p>The order of scaling and translating does matter. If you translate before scaling the transformation is intact. Like this example, first a translation of 2 units and then scale it by 0.5. </p>
<pre>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glTranslatef(float, float, float)" style="text-decoration: underline">glTranslatef</a>(2, 0, 0); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glTranslate.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glScalef(float, float, float)" style="text-decoration: underline">glScalef</a>(0.5f, 0.5f, 0.5f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glScale.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<p><center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/TranslateScale.png" alt="Translate scale." title="Translate scale." width="485" height="144" class="size-full wp-image-3141" /></center><br />
But if you scale before the translation you get a different result. Since you scale the mesh coordinate system then do the translation you will not move the mesh the same amount as you would before the scaling. So if you first scale with 0.5 and then do a translation of 2 units the result will appear as a translation of 1 unit.</p>
<pre>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glScalef(float, float, float)" style="text-decoration: underline">glScalef</a>(0.5f, 0.5f, 0.5f); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glScale.xml" style="text-decoration: underline">OpenGL docs.</a>
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glTranslatef(float, float, float)" style="text-decoration: underline">glTranslatef</a>(2, 0, 0); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glTranslate.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<p><center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/ScaleTranslate.png" alt="Scale translate." title="Scale translate." width="485" height="144" class="size-full wp-image-3141" /></center></p>
<h2>Load Identity, push and pop matrix</h2>
<p>When you translate, rotate or scaling you are not applying the transformation from the same preconditions, you are applying them to the previous transition. You need to be able to reset the position. </p>
<h3>glLoadIdentity</h3>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glLoadIdentity()" style="text-decoration: underline">glLoadIdentity</a>() // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glLoadIdentity.xml" style="text-decoration: underline">OpenGL docs.</a></pre>
<p>glLoadIdentity replaces the current matrix with the identity matrix. It is the same as  calling glLoadMatrix with the identity matrix:</p>
<pre>
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
</pre>
<p>There are situations where you don't want to reset the model matrix, you rather want to go back to how it was just before your latest transformation.</p>
<h3>glPushMatrix</h3>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glPushMatrix()" style="text-decoration: underline">glPushMatrix</a>() // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glPushMatrix.xml" style="text-decoration: underline">OpenGL docs.</a></pre>
<p>glPushMatrix makes a copy of the current matrix and put it on the stack. This means that when you do any kind of translations after glPushMatrix you are doing them on a copy.</p>
<h3>glPopMatrix</h3>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glPopMatrix()" style="text-decoration: underline">glPopMatrix</a>() // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glPopMatrix.xml" style="text-decoration: underline">OpenGL docs.</a></pre>
<p>To get back to the previous matrix you use the glPushMatrix command.</p>
<p>A good practice can be to have one glLoadIdentity in the begining of each frame and after that use glPushMatrix and glPopMatrix.</p>
<h2>Putting it all togetter</h2>
<p>So to make something with this new knowlege let us do 3 squares call them A, B and C. Scale them so that B is 50% smaller then A and C is 50% smaller then B. Then let A rotate counter-clockwise in the center of the screen. B should rotate clockwise around A and finaly C rotating clockwise around B and counter-clockwise in a high speed around it's own center.</p>
<pre>
public void onDrawFrame(GL10 gl) {
	// Clears the screen and depth buffer.
	gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
	// Replace the current matrix with the identity matrix
	gl.glLoadIdentity();
	// Translates 10 units into the screen.
	gl.glTranslatef(0, 0, -10); 

	// SQUARE A
	// Save the current matrix.
	gl.glPushMatrix();
	// Rotate square A counter-clockwise.
	gl.glRotatef(angle, 0, 0, 1);
	// Draw square A.
	square.draw(gl);
	// Restore the last matrix.
	gl.glPopMatrix();

	// SQUARE B
	// Save the current matrix
	gl.glPushMatrix();
	// Rotate square B before moving it, making it rotate around A.
	gl.glRotatef(-angle, 0, 0, 1);
	// Move square B.
	gl.glTranslatef(2, 0, 0);
	// Scale it to 50% of square A
	gl.glScalef(.5f, .5f, .5f);
	// Draw square B.
	square.draw(gl);			

	// SQUARE C
	// Save the current matrix
	gl.glPushMatrix();
	// Make the rotation around B
	gl.glRotatef(-angle, 0, 0, 1);
	gl.glTranslatef(2, 0, 0);
	// Scale it to 50% of square B
	gl.glScalef(.5f, .5f, .5f);
	// Rotate around it's own center.
	gl.glRotatef(angle*10, 0, 0, 1);
	// Draw square C.
	square.draw(gl);

	// Restore to the matrix as it was before C.
	gl.glPopMatrix();
	// Restore to the matrix as it was before B.
	gl.glPopMatrix();

	// Increse the angle.
	angle++;
}
</pre>
<p>And don't forget to add angel as a variable as well. Thanks Tim!</p>
<pre>
public class OpenGLRenderer implements Renderer {
	private Square square;
	private float angle; // Don't forget to add this.
        ...
</pre>
<h2>References</h2>
<p>The info used in this tutorial is collected from:<br />
<a href="http://developer.android.com/">Android Developers</a><br />
<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/">OpenGL ES 1.1 Reference Pages</a></p>
<p>You can download the source for this tutorial here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/Tutorial_Part_III.zip'>Tutorial_Part_III</a><br />
You can also checkout the code from: <a href='http://code.google.com/p/opengl-es-tutorial-for-android/source/checkout'>code.google.com</a></p>
<p>Previous tutorial: <a href="http://blog.jayway.com/2009/12/04/opengl-es-tutorial-for-android-–-part-ii-building-a-polygon/">OpenGL ES Tutorial for Android – Part II – Building a polygon</a><br />
Next tutorial: <a href="http://blog.jayway.com/2010/01/14/opengl-es-tutorial-for-android-%E2%80%93-part-iv-adding-colors/">OpenGL ES Tutorial for Android – Part IV – Adding colors</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/01/opengl-es-tutorial-for-android-%e2%80%93-part-iii-%e2%80%93-transformations/feed/</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part II &#8211; Building a polygon</title>
		<link>http://blog.jayway.com/2009/12/04/opengl-es-tutorial-for-android-%e2%80%93-part-ii-building-a-polygon/</link>
		<comments>http://blog.jayway.com/2009/12/04/opengl-es-tutorial-for-android-%e2%80%93-part-ii-building-a-polygon/#comments</comments>
		<pubDate>Fri, 04 Dec 2009 09:14:19 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[opengl es]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2357</guid>
		<description><![CDATA[Previous tutorial was all about setting up the GLSurfaceView. Be sure to read it beacuse it's a really importent one to be able to continue. Building a polygon In this tutorial we will render our first polygon. 3D models are built up with smaller elements (vertices, edges, faces, and polygons) which can be manipulated individually. [...]]]></description>
			<content:encoded><![CDATA[<p>Previous tutorial was all about setting up the GLSurfaceView. Be sure to <a href="http://blog.jayway.com/2009/12/03/opengl-es-tutorial-for-android-part-i/">read</a> it beacuse it's a really importent one to be able to continue.</p>
<h2>Building a polygon</h2>
<p>In this tutorial we will render our first polygon.</p>
<p>3D models are built up with smaller elements (vertices, edges, faces, and polygons) which can be manipulated individually.</p>
<h3>Vertex</h3>
<p>A vertex (vertices in plural) is the smallest building block of 3D model. A vertex is a point where two or more edges meet. In a 3D model a vertex can be shared between all connected edges, paces and polygons. A vertex can also be a represent for the position of a camera or a light source. You can see a vertex in the image below marked in yellow.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/vertex.png" alt="Vertex" /></center></p>
<table>
<tr>
<td>
   <img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/poly1.png" alt="Vertices for a square." title="Vertices for a square." width="202" height="205"  align="right"/></p>
<p>To define the vertices on android we define them as a float array that we put into a byte buffer to gain better performance. Look at the image to the right and the code below to match the vertices marked on the image to the code.
  </td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
</table>
<pre>
private float vertices[] = {
      -1.0f,  1.0f, 0.0f,  // 0, Top Left
      -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
       1.0f, -1.0f, 0.0f,  // 2, Bottom Right
       1.0f,  1.0f, 0.0f,  // 3, Top Right
};

// a float is 4 bytes, therefore we multiply the number if vertices with 4.
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
FloatBuffer vertexBuffer = vbb.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
</pre>
<p><em>Don't forget that a float is 4 bytes and to multiply it with the number of vertices to get the right size on the allocated buffer.</em> </p>
<p>OpenGL ES have a pipeline with functions to apply when you tell it to render. Most of these functions are not enabled by default so you have to remember to turn the ones you like to use on. You might also need to tell these functions what to work with. So in the case of our vertices we need to tell OpenGL ES that it’s okay to work with the vertex buffer we created we also need to tell where it is.</p>
<pre>
// Enabled the vertex buffer for writing and to be used during rendering.
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glEnableClientState(int)" style="text-decoration: underline">glEnableClientState</a>(GL10.GL_VERTEX_ARRAY);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glEnableClientState.xml" style="text-decoration: underline">OpenGL docs.</a>
// Specifies the location and data format of an array of vertex
// coordinates to use when rendering.
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glVertexPointer(int, int, int, java.nio.Buffer)" style="text-decoration: underline">glVertexPointer</a>(3, GL10.GL_FLOAT, 0, vertexBuffer); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glVertexPointer.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<p>When you are done with the buffer don't forget to disable it.</p>
<pre>
// Disable the vertices buffer.
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glDisableClientState(int)" style="text-decoration: underline">glDisableClientState</a>(GL10.GL_VERTEX_ARRAY);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glDisableClientState.xml" style="text-decoration: underline">OpenGL docs.</a>
</pre>
<h3>Edge</h3>
<p>Edge is a line between two vertices. They are border lines of faces and polygons. In a 3D model an edge can be shared between two adjacent faces or polygons. Transforming an edge affects all connected vertices, faces and polygons. In OpenGL ES you don't define the edges, you rather define the face by giving them the vertices that would build up the three edges. If you would like modify an edge you change the two vertices that makes the edge. You can see an edge in the image below marked in yellow.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/edge.png" alt="Edge" /></center></p>
<h3>Face</h3>
<p>Face is a triangle. Face is a surface between three corner vertices and three surrounding edges. Transforming a face affects all connected vertices, edges and polygons.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/face.png" alt="Face" /></center></p>
<h4>The order does matter.</h4>
<p>When winding up the faces it's important to do it in the right direction because the direction defines what side will be the front face and what side will be the back face. Why this is important is because to gain performance we don't want to draw both sides so we turn off the back face. So it's a good idea to use the same winding all over your project. It is possible to change what direction that defines the front face with glFrontFace.</p>
<pre> gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glFrontFace(int)" style="text-decoration: underline">glFrontFace</a>(GL10.GL_CCW); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glFrontFace.xml" style="text-decoration: underline">OpenGL docs</a></pre>
<p>To make OpenGL skip the faces that are turned into the screen you can use something called back-face culling. What is does is determines whether a polygon of a graphical object is visible by checking if the face is wind up in the right order.</p>
<pre> gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glEnable(int)" style="text-decoration: underline">glEnable</a>(GL10.GL_CULL_FACE); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glEnable.xml" style="text-decoration: underline">OpenGL docs</a></pre>
<p>It's ofcource possible to change what face side should be drawn or not.</p>
<pre> gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glCullFace(int)" style="text-decoration: underline">glCullFace</a>(GL10.GL_BACK); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glCullFace.xml" style="text-decoration: underline">OpenGL docs</a></pre>
<h3>Polygon</h3>
<p><center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/polygon.png" alt="Polygon" /></center></p>
<table>
<tr>
<td>
   <img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/poly2.png" alt="Indices for a square." title="Indices  for a square." width="202" height="205"  align="right"/></p>
<p>Time to wind the faces, remember we have decided to go with the default winding meaning counter-clockwise. Look at the image to the right and the code below to see how to wind up this square.
  </td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
</table>
<pre>
private short[] indices = { 0, 1, 2, 0, 2, 3 };
</pre>
<p>To gain some performance we also put this ones in a byte buffer.</p>
<pre>
// short is 2 bytes, therefore we multiply the number if vertices with 2.
ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
ibb.order(ByteOrder.nativeOrder());
ShortBuffer indexBuffer = ibb.asShortBuffer();
indexBuffer.put(indices);
indexBuffer.position(0);
</pre>
<p><em>Don't forget that a short is 2 bytes and to multiply it with the number of indices to get the right size on the allocated buffer.</em> </p>
<h3>Render</h3>
<p>Time to get something on the screen, there is two functions used to draw and we have to decide which one to use.</p>
<p>The two functions are:</p>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glDrawArrays(int, int, int)" style="text-decoration: underline">glDrawArrays</a>(int mode, int first, int count) // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glDrawArrays.xml" style="text-decoration: underline">OpenGL docs</a></pre>
<p>glDrawArrays draws the vertices in that order they are specified in the construction of our verticesBuffer.</p>
<pre>public abstract void <a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glDrawElements(int, int, int, java.nio.Buffer)" style="text-decoration: underline">glDrawElements</a>(int mode, int count, int type, // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glDrawElements.xml" style="text-decoration: underline">OpenGL docs</a>
                                    Buffer indices) </pre>
<p>glDrawElements need a little bit more to be able to draw. It needs to know the order which to draw the vertices, it needs the indicesBuffer.</p>
<p>Since we already created the indicesBuffer I'm guessing that you figured out that's the way we are going.</p>
<p>What is common for this functions is that they both need to know what it is they should draw, what primitives to render. Since there is some various ways to render this indices and some of them are good to know about for debugging reasons. I'll go through them all.</p>
<h3>What primitives to render</h3>
<h4>GL_POINTS</h4>
<p>Draws individual points on the screen.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/Gl_points.jpg" alt="Gl_points" title="Gl_points" width="200" height="140" class="aligncenter size-full wp-image-2392" /></center></p>
<h4>GL_LINE_STRIP</h4>
<p>Series of connected line segments.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/Gl_line_strip.jpg" alt="Gl_line_strip" title="Gl_line_strip" width="200" height="140" class="aligncenter size-full wp-image-2391" /></center></p>
<h4>GL_LINE_LOOP</h4>
<p>Same as above, with a segment added between last and first vertices.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/Gl_line_loop.jpg" alt="Gl_line_loop" title="Gl_line_loop" width="200" height="140" class="aligncenter size-full wp-image-2389" /></center></p>
<h4>GL_LINES</h4>
<p>Pairs of vertices interpreted as individual line segments.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/Gl_lines.jpg" alt="Gl_lines" title="Gl_lines" width="200" height="140" class="aligncenter size-full wp-image-2390" /></center></p>
<h4>GL_TRIANGLES</h4>
<p>Triples of vertices interpreted as triangles.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/Gl_triangles.jpg" alt="Gl_triangles" title="Gl_triangles" width="200" height="140" class="aligncenter size-full wp-image-2394" /></center></p>
<h4>GL_TRIANGLE_STRIP</h4>
<p>Draws a series of triangles (three-sided polygons) using vertices v0, v1, v2, then v2, v1, v3 (note the order), then v2, v3, v4, and so on. The ordering is to ensure that the triangles are all drawn with the same orientation so that the strip can correctly form part of a surface.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/Gl_triangle_strip.jpg" alt="Gl_triangle_strip" title="Gl_triangle_strip" width="200" height="140" class="aligncenter size-full wp-image-2395" /></center></p>
<h4>GL_TRIANGLE_FAN</h4>
<p>Same as GL_TRIANGLE_STRIP, except that the vertices are drawn v0, v1, v2, then v0, v2, v3, then v0, v3, v4, and so on.<br />
<center><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/11/Gl_triangle_fan.jpg" alt="Gl_triangle_fan" title="Gl_triangle_fan" width="200" height="140" class="aligncenter size-full wp-image-2393" /></center></p>
<p>I think the GL_TRIANGLES is the easiest to use so we go with that one for now.</p>
<h2>Putting it all togetter</h2>
<p>So let's putting our square together in a class.</p>
<pre>
package se.jayway.opengl.tutorial;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

public class Square {
	// Our vertices.
	private float vertices[] = {
		      -1.0f,  1.0f, 0.0f,  // 0, Top Left
		      -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
		       1.0f, -1.0f, 0.0f,  // 2, Bottom Right
		       1.0f,  1.0f, 0.0f,  // 3, Top Right
		};

	// The order we like to connect them.
	private short[] indices = { 0, 1, 2, 0, 2, 3 };

	// Our vertex buffer.
	private FloatBuffer vertexBuffer;

	// Our index buffer.
	private ShortBuffer indexBuffer;

	public Square() {
		// a float is 4 bytes, therefore we multiply the number if
		// vertices with 4.
		ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
		vbb.order(ByteOrder.nativeOrder());
		vertexBuffer = vbb.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);

		// short is 2 bytes, therefore we multiply the number if
		// vertices with 2.
		ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
		ibb.order(ByteOrder.nativeOrder());
		indexBuffer = ibb.asShortBuffer();
		indexBuffer.put(indices);
		indexBuffer.position(0);
	}

	/**
	 * This function draws our square on screen.
	 * @param gl
	 */
	public void draw(GL10 gl) {
		// Counter-clockwise winding.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glFrontFace(int)" style="text-decoration: underline">glFrontFace</a>(GL10.GL_CCW); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glFrontFace.xml" style="text-decoration: underline">OpenGL docs</a>
		// Enable face culling.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glEnable(int)" style="text-decoration: underline">glEnable</a>(GL10.GL_CULL_FACE); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glEnable.xml" style="text-decoration: underline">OpenGL docs</a>
		// What faces to remove with the face culling.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glCullFace(int)" style="text-decoration: underline">glCullFace</a>(GL10.GL_BACK); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glCullFace.xml" style="text-decoration: underline">OpenGL docs</a>

		// Enabled the vertices buffer for writing and to be used during
		// rendering.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glEnableClientState(int)" style="text-decoration: underline">glEnableClientState</a>(GL10.GL_VERTEX_ARRAY);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glEnableClientState.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Specifies the location and data format of an array of vertex
		// coordinates to use when rendering.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glVertexPointer(int, int, int, java.nio.Buffer)" style="text-decoration: underline">glVertexPointer</a>(3, GL10.GL_FLOAT, 0, // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glVertexPointer.xml" style="text-decoration: underline">OpenGL docs</a>
                                 vertexBuffer);

		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glDrawElements(int, int, int, java.nio.Buffer)" style="text-decoration: underline">glDrawElements</a>(GL10.GL_TRIANGLES, indices.length,// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glDrawElements.xml" style="text-decoration: underline">OpenGL docs</a>
				  GL10.GL_UNSIGNED_SHORT, indexBuffer);

		// Disable the vertices buffer.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glDisableClientState(int)" style="text-decoration: underline">glDisableClientState</a>(GL10.GL_VERTEX_ARRAY); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glDisableClientState.xml" style="text-decoration: underline">OpenGL docs</a>
		// Disable face culling.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glDisable(int)" style="text-decoration: underline">glDisable</a>(GL10.GL_CULL_FACE); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glDisable.xml" style="text-decoration: underline">OpenGL docs</a>
	}

}
</pre>
<p>We have to initialize our square in the OpenGLRenderer class.</p>
<pre>
// Initialize our square.
Square square = new Square();
</pre>
<p>And in the draw function call on the square to draw.</p>
<pre>
public void onDrawFrame(GL10 gl) {
		// Clears the screen and depth buffer.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glClear(int)" style="text-decoration: underline">glClear</a>(GL10.GL_COLOR_BUFFER_BIT | // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glClear.xml" style="text-decoration: underline">OpenGL docs.</a>
                           GL10.GL_DEPTH_BUFFER_BIT);

		// Draw our square.
		square.draw(gl); // ( NEW )
}
</pre>
<p>If you run the application now the screen is still black. Why? Because OpenGL ES render from where the current position is, that by default is at point: 0, 0, 0 the same position that the view port is located. And OpenGL ES don’t render the things that are too close to the view port. The solution to this is to move the draw position a few steps into the screen before rendering the square:</p>
<pre>
// Translates 4 units into the screen.
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glTranslatef(float, float, float)" style="text-decoration: underline">glTranslatef</a>(0, 0, -4); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glTranslate.xml" style="text-decoration: underline">OpenGL docs</a>
</pre>
<p>I will talk about the different transformations in the next tutorial.</p>
<p>Run the application again and you will see that the square is drawn but quickly moves further and further into the screen. OpenGL ES doesn’t reset the drawing point between the frames that you will have to do yourself:</p>
<pre>
// Replace the current matrix with the identity matrix
gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glLoadIdentity()" style="text-decoration: underline">glLoadIdentity</a>(); // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glLoadIdentity.xml" style="text-decoration: underline">OpenGL docs</a>
</pre>
<p>Now if you run the application you will see the square on a fixed position.</p>
<h2>References</h2>
<p>The info used in this tutorial is collected from:<br />
<a href="http://developer.android.com/">Android Developers</a><br />
<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/">OpenGL ES 1.1 Reference Pages</a></p>
<p>You can download the source for this tutorial here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Tutorial_Part_II.zip'>Tutorial_Part_II</a><br />
You can also checkout the code from: <a href='http://code.google.com/p/opengl-es-tutorial-for-android/source/checkout'>code.google.com</a></p>
<p>Previous tutorial: <a href="http://blog.jayway.com/2009/12/03/opengl-es-tutorial-for-android-part-i/">OpenGL ES Tutorial for Android – Part I – Setting up the view</a><br />
Next tutorial: <a href="http://blog.jayway.com/2010/01/01/opengl-es-tutorial-for-android-–-part-iii-–-transformations/">OpenGL ES Tutorial for Android – Part III – Transformations</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/04/opengl-es-tutorial-for-android-%e2%80%93-part-ii-building-a-polygon/feed/</wfw:commentRss>
		<slash:comments>62</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android &#8211; Part I &#8211; Setting up the view</title>
		<link>http://blog.jayway.com/2009/12/03/opengl-es-tutorial-for-android-part-i/</link>
		<comments>http://blog.jayway.com/2009/12/03/opengl-es-tutorial-for-android-part-i/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 09:25:12 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[opengl es]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2309</guid>
		<description><![CDATA[I'm going to write a couple of tutorials on using OpenGL ES on Android phones. The theory of OpenGL ES is the same on different devices so it should be quite easy to convert them to another platform. I can't always remember where I found particular info so I might not always be able to [...]]]></description>
			<content:encoded><![CDATA[<p>I'm going to write a couple of tutorials on using OpenGL ES on Android phones. The theory of OpenGL ES is the same on different devices so it should be quite easy to convert them to another platform.</p>
<p>I can't always remember where I found particular info so I might not always be able to give you the right reference. If you feel that I have borrowed stuff from you but have forgotten to add you as a reference, please e-mail me.</p>
<p>In the code examples I will have two different links for each function. The actual function will be linked to the android documentation and after that I will also link the OpenGL documentations. Like this:</p>
<pre>gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glClearColor(float, float, float, float)" style="text-decoration: underline">glClearColor</a>(0.0f, 0.0f, 0.0f, 0.5f);  // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glClearColor.xml" style="text-decoration: underline">OpenGL docs.</a></pre>
<p>So, let's start.</p>
<p>In this tutorial I will show you how to set up your OpenGL ES view that’s always a good place to start. </p>
<h2>Setting up an OpenGL ES View</h2>
<p>Setting up a OpenGL view has never been hard and on Android it is still easy. There really are only two things you need to get started.</p>
<h3>GLSurfaceView</h3>
<p>GLSurfaceView is a API class in Android 1.5 that helps you write OpenGL ES applications.</p>
<ul>
<li>Providing the glue code to connect OpenGL ES to the View system.</li>
<li>Providing the glue code to make OpenGL ES work with the Activity life-cycle.</li>
<li>Making it easy to choose an appropriate frame buffer pixel format.</li>
<li>Creating and managing a separate rendering thread to enable smooth animation.</li>
<li>Providing easy-to-use debugging tools for tracing OpenGL ES API calls and checking for errors.</li>
</ul>
<p>If you want to get going fast with your OpenGL ES application this is where you should start.</p>
<p>The only function you need to call on is: </p>
<pre>public void  setRenderer(GLSurfaceView.Renderer renderer)</pre>
<p>Read more at: <a href="http://developer.android.com/reference/android/opengl/GLSurfaceView.html">GLSurfaceView</a></p>
<h3>GLSurfaceView.Renderer</h3>
<p>GLSurfaceView.Renderer is a generic render interface. In your implementation of this renderer you should put all your calls to render a frame.<br />
There are three functions to implement:</p>
<pre>
// Called when the surface is created or recreated.
public void onSurfaceCreated(GL10 gl, EGLConfig config) 

// Called to draw the current frame.
public void onDrawFrame(GL10 gl)

// Called when the surface changed size.
public void onSurfaceChanged(GL10 gl, int width, int height)
</pre>
<h4>onSurfaceCreated</h4>
<p>Here it's a good thing to setup things that you don't change so often in the rendering cycle. Stuff like what color to clear the screen with, enabling z-buffer and so on.</p>
<h4>onDrawFrame</h4>
<p>Here is where the actual drawing take place.</p>
<h4>onSurfaceChanged</h4>
<p>If your device supports flipping between landscape and portrait you will get a call to this function when it happens. What you do here is setting upp the new ratio.<br />
Read more at: <a href="http://developer.android.com/reference/android/opengl/GLSurfaceView.Renderer.html">GLSurfaceView.Renderer</a></p>
<h2>Putting it together</h2>
<p>First we create our activity, we keep it clean and simple.</p>
<pre>
package se.jayway.opengl.tutorial;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;

public class TutorialPartI extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
 		GLSurfaceView view = new GLSurfaceView(this);
   		view.setRenderer(new OpenGLRenderer());
   		setContentView(view);
    }
}
</pre>
<p>Our renderer takes little bit more work to setup, look at it and I will explain the code a bit more. </p>
<pre>
package se.jayway.opengl.tutorial;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;

public class OpenGLRenderer implements Renderer {
	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.
         * microedition.khronos.opengles.GL10, javax.microedition.khronos.
         * egl.EGLConfig)
	 */
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// Set the background color to black ( rgba ).
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glClearColor(float, float, float, float)" style="text-decoration: underline">glClearColor</a>(0.0f, 0.0f, 0.0f, 0.5f);  // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glClearColor.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Enable Smooth Shading, default not really needed.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glShadeModel(int)" style="text-decoration: underline">glShadeModel</a>(GL10.GL_SMOOTH);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glShadeModel.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Depth buffer setup.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glClearDepthf(float)" style="text-decoration: underline">glClearDepthf</a>(1.0f);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glClearDepth.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Enables depth testing.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glEnable(int)" style="text-decoration: underline">glEnable</a>(GL10.GL_DEPTH_TEST);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glEnable.xml" style="text-decoration: underline">OpenGL docs.</a>
		// The type of depth testing to do.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glDepthFunc(int)" style="text-decoration: underline">glDepthFunc</a>(GL10.GL_LEQUAL);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glDepthFunc.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Really nice perspective calculations.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glHint(int, int)" style="text-decoration: underline">glHint</a>(GL10.GL_PERSPECTIVE_CORRECTION_HINT, // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glHint.xml" style="text-decoration: underline">OpenGL docs.</a>
                          GL10.GL_NICEST);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.
         * microedition.khronos.opengles.GL10)
	 */
	public void onDrawFrame(GL10 gl) {
		// Clears the screen and depth buffer.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glClear(int)" style="text-decoration: underline">glClear</a>(GL10.GL_COLOR_BUFFER_BIT | // <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glClear.xml" style="text-decoration: underline">OpenGL docs.</a>
                           GL10.GL_DEPTH_BUFFER_BIT);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.
         * microedition.khronos.opengles.GL10, int, int)
	 */
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// Sets the current view port to the new size.
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glViewport(int, int, int, int)" style="text-decoration: underline">glViewport</a>(0, 0, width, height);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glViewport.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Select the projection matrix
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glMatrixMode(int)" style="text-decoration: underline">glMatrixMode</a>(GL10.GL_PROJECTION);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glMatrixMode.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Reset the projection matrix
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glLoadIdentity()" style="text-decoration: underline">glLoadIdentity</a>();// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glLoadIdentity.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Calculate the aspect ratio of the window
		GLU.<a href="http://developer.android.com/reference/android/opengl/GLU.html#gluPerspective(javax.microedition.khronos.opengles.GL10, float, float, float, float)" style="text-decoration: underline">gluPerspective</a>(gl, 45.0f,
                                   (float) width / (float) height,
                                   0.1f, 100.0f);
		// Select the modelview matrix
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glMatrixMode(int)" style="text-decoration: underline">glMatrixMode</a>(GL10.GL_MODELVIEW);// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glMatrixMode.xml" style="text-decoration: underline">OpenGL docs.</a>
		// Reset the modelview matrix
		gl.<a href="http://developer.android.com/reference/javax/microedition/khronos/opengles/GL10.html#glLoadIdentity()" style="text-decoration: underline">glLoadIdentity</a>();// <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glLoadIdentity.xml" style="text-decoration: underline">OpenGL docs.</a>
	}
}
</pre>
<h2>Fullscreen</h2>
<p>Just add this lines in the OpenGLDemo class and you will get fullscreen.</p>
<pre>
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.<a href="http://developer.android.com/reference/android/app/Activity.html#requestWindowFeature(int)" style="text-decoration: underline">requestWindowFeature</a>(Window.FEATURE_NO_TITLE); // (NEW)
        getWindow().<a href="http://developer.android.com/reference/android/view/Window.html#setFlags(int, int)" style="text-decoration: underline">setFlags</a>(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN); // (NEW)
        ... // Previous code.
    }
</pre>
<p>This is pretty much all you need to get your view up and running. If you compile and run it you will see a nice black screen.</p>
<h2>References</h2>
<p>The info used in this tutorial is collected from:<br />
<a href="http://developer.android.com/">Android Developers</a><br />
<a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/">OpenGL ES 1.1 Reference Pages</a></p>
<p>You can download the source for this tutorial here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Tutorial_Part_I.zip'>Tutorial_Part_I.zip</a><br />
You can also checkout the code from: <a href='http://code.google.com/p/opengl-es-tutorial-for-android/source/checkout'>code.google.com</a></p>
<p>Next tutorial: <a href="http://blog.jayway.com/2009/12/04/opengl-es-tutorial-for-android-%E2%80%93-part-ii-building-a-polygon/">OpenGL ES Tutorial for Android – Part II – Building a polygon</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/12/03/opengl-es-tutorial-for-android-part-i/feed/</wfw:commentRss>
		<slash:comments>62</slash:comments>
		</item>
		<item>
		<title>UIToolbars in iPhone OS 2.x</title>
		<link>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/</link>
		<comments>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 16:39:42 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1293</guid>
		<description><![CDATA[The new release of iPhone OS 3.0 adds some nice API:s for managing a contextual toolbar. This is well needed as toolbars in the current iteration of iPhone OS is not only poorly documented, it is also quite hard to do right. So I will go over how to do toolbars the right way, for [...]]]></description>
			<content:encoded><![CDATA[<p>The new release of iPhone OS 3.0 adds some nice API:s for managing a contextual toolbar. This is well needed as toolbars in the current iteration of iPhone OS is not only poorly documented, it is also quite hard to do right. So I will go over how to do toolbars the right way, for all who want to implement them the old way before this summer, and for all who think they need to support older versions after then (Read my <a href="http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/">previous post</a> on why backward compatibility is not an issue for iPhone OS developers).</p>
<h3>The Problem</h3>
<p>The most intuitive way to create and use a <code>UIToolbar</code> is to add it manually for each of your view controllers. If your application is very simple this could be the right thing to do, but if our application uses a <code>UINavigationController</code> then it is the wrong way to do it.</p>
<p>If you look at the Mail application you will notice how the toolbar stays in place, and the items on the toolbar cross fades when you navigate the application hierarchy. You might also have noticed that the toolbar do not cross fade, but rather is pushed, if you add a toolbar to each of the view trees of your own view controllers. This is because your toolbar is then part of the wrong three hierarchy, as shown in this image.<br />
<div id="attachment_1294" class="wp-caption alignright" style="width: 490px"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/layout_wrong.png" alt="Screen estate as owned by different view controllers." title="layout_wrong" width="320" height="312" class="size-full wp-image-1294" /><p class="wp-caption-text">Screen estate as owned by different view controllers.</p></div></p>
<p>You will find a few solutions if you Goole on the topic, all of them that I have found are dead wrong. They tend to use <code>self.view.superview</code> on the view controller instance to slide the toolbar up one level in the hierarchy. It works, most of the time, but is an ugly hack that is not future proof.</p>
<h3>A Better Solution</h3>
<p>The reason the toolbar is pushed off screen is that the toolbar is owned by the navigation controller,as we saw in the image above, and a navigation controller pushes it's content. The view hierarchy we would like to have is instead something like this.<br />
<div id="attachment_1300" class="wp-caption alignright" style="width: 530px"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/layout_correct.png" alt="Screen estate as owned by different view controllers." title="layout_correct" width="341" height="320" class="size-full wp-image-1300" /><p class="wp-caption-text">Screen estate as owned by different view controllers.</p></div></p>
<p>In this setup the navigation controller can push the content, as it is intended to do, and the custom toolbar controller can manage a static <code>UIToolbar</code> with cross fades. Only problem is; this custom toolbar controller do not exist, and we must implement it on our own. Luckily not many lines of code is needed.</p>
<h3>Custom Toolbar Conroller Requirement</h3>
<p>The custom toolbar controller should be a subclass of <code>UIViewController</code>, that way it's fits nicely into the Cocoa Touch framework, and can nicely be fitted into any well written application.</p>
<p>The custom toolbar controller should manage a view consisting of a <code>UIToolbar</code> instance, and a view that is fetched from another view controller. This is modelled after how a <code>UINavigationController</code> manages a view that consists of a <code>UINavigationBar</code> and the view fetched from other view controllers. This way any well written view controller can be used with our custom toolbar controller.</p>
<p>Lastly our custom toolbar controller should implement the <code>UINavigationControllerDelegate</code> protocol, so that we can listen to events as view controllers are pushed and poped from the navigation stack, and update the toolbar with contextual toolbar items. Just as the navigation controller updates it's title by fetching the title property of the managed view controllers, so will our custom toolbar controller update the toolbar items by fetching the toolbarItems property if available.</p>
<h3>Toolbar Controller Interface</h3>
<p>The interface will be sparse, all we need is an initializer for creating a toolbar controller with another view controller providing the main content, and for sports two properties to access the content view controller, and the toolbar itself.</p>
<pre class="objc"><span style="color: #339900;">#import &lt;UIKit/UIKit.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> CWToolbarController : UIViewController &lt;UINavigationControllerDelegate&gt; <span style="color: #002200;">&#123;</span>
<span style="color: #0000ff;">@private</span>
    UIViewController* _contentViewController;
    UIToolbar* _toolbar;
<span style="color: #002200;">&#125;</span>
&nbsp;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> UIViewController* contentViewController;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> UIToolbar* toolbar;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithContentViewController:<span style="color: #002200;">&#40;</span>UIViewController*<span style="color: #002200;">&#41;</span>contentViewController;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Toolbar Controller Implementation</h3>
<p>The grunt work for implementing the toolbar controller do not need any further explanation.</p>
<pre class="objc"><span style="color: #339900;">#import &quot;CWToolbarController.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> CWToolbarController
&nbsp;
@synthesize contentViewController = _contentViewController;
@synthesize toolbar = _toolbar;
&nbsp;
- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithContentViewController:<span style="color: #002200;">&#40;</span>UIViewController*<span style="color: #002200;">&#41;</span>contentViewController;
<span style="color: #002200;">&#123;</span>
    self = <span style="color: #002200;">&#91;</span>super init<span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        _contentViewController = <span style="color: #002200;">&#91;</span>contentViewController retain<span style="color: #002200;">&#93;</span>;
        <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>_contentViewController isKindOfClass:<span style="color: #002200;">&#91;</span>UINavigationController <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span>UINavigationController*<span style="color: #002200;">&#41;</span>_contentViewController<span style="color: #002200;">&#41;</span>.delegate = self;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
	<span style="color: #0000ff;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>dealloc;
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>_contentViewController release<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>The first interesting code is to setup the view that is managed by our toolbar controller. This view have two subviews, a <code>UIToolbar</code>, and a view that we fetch from the content view controller we where given. We do this setup in the <code>loadView</code> method.</p>
<pre class="objc">- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>loadView;
<span style="color: #002200;">&#123;</span>
    UIView* contentView = _contentViewController.view;
    CGRect frame = contentView.frame;
    UIView* view = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame:frame<span style="color: #002200;">&#93;</span>;
&nbsp;
    frame = CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span>, frame.size.width, frame.size.height - <span style="color: #0000dd;">44</span>.0f<span style="color: #002200;">&#41;</span>;
    contentView.frame = frame;
    <span style="color: #002200;">&#91;</span>view addSubview:contentView<span style="color: #002200;">&#93;</span>;
&nbsp;
    frame = CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">0</span>.0f, frame.size.height, frame.size.width, <span style="color: #0000dd;">44</span>.0f<span style="color: #002200;">&#41;</span>;
    _toolbar = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIToolbar alloc<span style="color: #002200;">&#93;</span> initWithFrame:frame<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>view addSubview:_toolbar<span style="color: #002200;">&#93;</span>;
&nbsp;
    self.view = view;
    <span style="color: #002200;">&#91;</span>view release<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>_toolbar release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>This code reuses the screen setup already done by the content view controller, and re-layouts our subviews. It is a simple solution, and you will need a custom class for the root view with an overloaded <code>layoutSubviews</code> if you want to properly handle orientation changes. But I have left this out, as it is not within the scope of this post.</p>
<p>Next up we need to update the toolbar with contextual toolbar items, when our content changes. This is only supported if the content view controller is a <code>UINavigationController</code>, as can be seen in the initializer above. This could be made more flexible, but is also outside the scope of this post. We have set our toolbar controller to be the delegate for the content navigation view controller, so all we need to do is to respond to navigation events as they occur. </p>
<pre class="objc">- <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>navigationController:<span style="color: #002200;">&#40;</span>UINavigationController *<span style="color: #002200;">&#41;</span>navigationController
        willShowViewController:<span style="color: #002200;">&#40;</span>UIViewController *<span style="color: #002200;">&#41;</span>viewController
        animated:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>animated;
<span style="color: #002200;">&#123;</span>
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* items = <span style="color: #0000ff;">nil</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>viewController respondsToSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>toolbarItems<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        items = <span style="color: #002200;">&#91;</span>viewController performSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>toolbarItems<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#91;</span>_toolbar setItems:items animated:animated<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Conclusion</h3>
<p>As shown with this code, doing the correct way with Cocoa Touch almost always means doing it in the easiest way as well. The hard part is knowing what the correct way is. My hope is that this post can guide you in the right direction. Rule of thumb is to always try to follow the same pattern as similiar things in Cocoa, it might feel like it is harder to do, but at the end of the day you will end up with less code, with more features.</p>
<p>The code above for implementing the custom toolbar controller, is much less code than what is needed to write a small application to demonstrate it being used. I have therefor made a small demonstration application with this complete code. It is a tree of table views, where each item opens up a new table view tree with one less toolbar item. </p>
<p>The source code is released under BSD license, and you can <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/toolbarapp.zip">download it here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/uitoolbars-in-iphone-os-2x/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Simple Authentication Using Spring LDAP</title>
		<link>http://blog.jayway.com/2009/02/02/simple-authentication-using-spring-ldap/</link>
		<comments>http://blog.jayway.com/2009/02/02/simple-authentication-using-spring-ldap/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 20:00:46 +0000</pubDate>
		<dc:creator>Mattias Hellborg Arthursson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[1.3.0]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[bind]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[ldap]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring ldap]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=870</guid>
		<description><![CDATA[It's with great pleasure that we can now finally announce the final 1.3.0 version of Spring LDAP. It's been a while since we've made a major release, but there's quite a bit in this one to make up for it. Among the highlights of this release are the improvements in the authentication area, which is [...]]]></description>
			<content:encoded><![CDATA[<p>It's with great pleasure that we can now finally announce the final 1.3.0 version of <a href="http://www.springframework.org/ldap">Spring LDAP</a>. It's been a while since we've made a major release, but there's quite a bit in this one to make up for it. Among the highlights of this release are the improvements in the authentication area, which is the intended focus of this post.</p>
<h3>Simple LDAP Authentication</h3>
<p>One of the most requested pieces of functionality in Spring LDAP has been a means to perform simple authentication. We have previously hesitated to include this, not finding any logical place to put it. In this release however we got a couple of suggestions on suitable API additions that enabled us to attack this from a different angle, in the end resulting in explicit methods in LdapTemplate for this purpose.</p>
<h4>Background</h4>
<p>The problem with authentication in LDAP is that it normally requires two separate steps: First you need to find the principal to authenticate in the LDAP tree, typically performing an LDAP search based on e.g. a user name. A new LDAP connection will then be acquired, authenticating it using the Distinguished Name of the found entry (normally referred to as an 'LDAP Bind').</p>
<h5>Example</h5>
<p>Consider the LDAP tree below:<br />
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/02/ldaptree.gif" alt="Ldap Tree" title="Ldap Tree" width="303" height="276" class="size-full wp-image-871" /><br />
Let us say a user identifying himself as 'John Doe' is trying to log into our system. We would execute a search from the top of the LDAP tree using a search filter like <code>(&(objectclass=person)(cn=John Doe))</code>. The search would return one single entry, from which we would extract the absolute DN; <code>cn=John Doe, ou=company1, c=Sweden, dc=jayway, dc=se</code>. This DN would then be used for authenticating a new LDAP connection to the server, thus validating the password supplied by the user.</p>
<h4>New Spring LDAP Authentication API</h4>
<p>While the above has indeed been possible to do using previous versions of Spring LDAP, it has required quite a lot of work and resulted in rather messy code. Spring LDAP 1.3.0 adds a couple of methods to LdapTemplate, making the authentication procedure very straightforward:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> authenticate<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AName+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Name</span></a> base, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> filter, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password<span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> authenticate<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AName+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Name</span></a> base, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> filter, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password, AuthenticatedLdapEntryContextCallback callback<span style="color: #66cc66;">&#41;</span></pre>
<p>The first method performs exactly the procedure described above, returning <code>true</code> or <code>false</code> depending on the outcome. The second method goes one step further, allowing us to perform any operation on the authenticated LDAP connection. Focusing on the simplest case, a standard authentication method using Spring LDAP would look something like the following:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> login<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> username, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> password<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  AndFilter filter = <span style="color: #000000; font-weight: bold;">new</span> AndFilter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  filter.<span style="color: #006600;">and</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> EqualsFilter<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;objectclass&quot;</span>, <span style="color: #ff0000;">&quot;person&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">and</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> EqualsFilter<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;cn&quot;</span>, username<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #000000; font-weight: bold;">return</span> ldapTemplate.<span style="color: #006600;">authenticate</span><span style="color: #66cc66;">&#40;</span>DistinguishedName.<span style="color: #006600;">EMPTY_PATH</span>, filter.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, password<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>Simple, clean and to the point, especially compared to the mess that used to be required (won't linger on those nasty details here). Obviously however, using a Spring library we will be required to write a few lines of XML as well:</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.support.LdapContextSource&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;url&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap://url.to.ldap.server:389&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;userDn&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;uid=admin,ou=system&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;adminpassword&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.springframework.ldap.core.LdapTemplate&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;contextSource&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;myAuthenticator&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.example.MyAuthenticatingClass&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- Assuming constructor injection of LdapTemplate instance in your authentication class --&gt;</span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;ldapTemplate&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/bean<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>A couple of comments on the suggested solution:</p>
<ul>
<li>The search needs to return exactly one result entry. In the example above, if there would be more than one person entry in the tree with <code>cn</code> 'John Doe' (which would be perfectly legal according to schema regulations), the call to <code>authenticate</code> would fail.</li>
<li>In actual implementations the attribute to use for identification will likely be e.g. <code>uid</code> or <code>sAMAccountname</code> (in Active Directory). Both of these attributes have uniqueness enforced throughout the entire tree by the LDAP server.</li>
<li> The method only returns <code>true</code> or <code>false</code>; thus the actual reason for failing will not be visible to the caller. The reason will however be logged, which might be useful useful when tracking down problems with search filters and such.</li>
<li>A common reason for confusion in LDAP searches is the <code>base</code> parameter, which is used for pointing out where in the LDAP tree to start searching. Referring again to the potential problem where several users might have the same <code>cn</code>; in that case these entries would have to be located in different subtrees. The search could then be narrowed by specifying a different base DN to the <code>authenticate</code> method, e.g. <code>c=Sweden, dc=jayway, dc=com</code></li>
</ul>
<p><b>Note: </b>While the provided methods will handle the simple task of authentication for you it is likely that your actual security requirements go way past plain authentication (e.g. authorization, web integration, etc.). The realm of security is a very complex one, which is the reason you should carefully consider your actual requirements - if they appear to go beyond simple authentication you should definitely consider using <a href="http://www.springsecurity.org">Spring Security</a> instead. (Obviously, under the covers Spring LDAP would be used for the actual authentication anyway).</p>
<p>That said, for many systems the API provided with Spring LDAP will be quite sufficient.</p>
<h3>Other improvements in Spring LDAP 1.3.0</h3>
<p>As compared to the 1.2.1 version of Spring LDAP, 1.3.0 includes more than 50 fixes, varying from internal modifications and minor improvements to important bug fixes and significant functionality additions. The full list of modifications can be viewed in the <a href="http://static.springframework.org/spring-ldap/docs/1.3.x/changelog.txt">the changelog</a>.</p>
<h3>About Spring LDAP</h3>
<p>Spring LDAP is a Java library for simplifying LDAP operations, based on the pattern of Spring's JdbcTemplate. The framework relieves the user of common chores, such as looking up and closing contexts, looping through results, encoding/decoding values and filters, and more. The library is free, open source, and distributed under the Apache Licence version 2. </p>
<p>For more information on the Spring LDAP project, including downloads, maven usage, as well as project reference and API documentation, refer to its <a href="http://www.springsource.org/ldap">project home page</a> on springsource.org. Support and enhancement requests will be answered in the <a href="http://forum.springframework.org/forumdisplay.php?f=40">Spring LDAP Forum</a> at Spring Community Forums.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/02/02/simple-authentication-using-spring-ldap/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
		</item>
		<item>
		<title>Accelerometer and Vibration on the iPhone</title>
		<link>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/</link>
		<comments>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 07:48:47 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[accelerometer]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[oredev]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=464</guid>
		<description><![CDATA[Last friday I attended an excellent session at Øredev 2008, on Android by Mike Jennings from Google. At the end of the presentation Mike show the code for a simple application with a bouncing blue ball, controlled by the accelerometer. What stroke me was that the git of the application was 85 lines of code, [...]]]></description>
			<content:encoded><![CDATA[<p>Last friday I attended an excellent session at <a href="http://www.oredev.org">Øredev 2008</a>, on <a href="http://code.google.com/android/">Android</a> by Mike Jennings from Google. At the end of the presentation Mike show the code for a simple application with a bouncing blue ball, controlled by the accelerometer. What stroke me was that the git of the application was 85 lines of code, and Mike told us most of the physics and life cycle code was hidden away. I have never used the accelerometer on the iPhone, but my gut told me that 85 lines was allot of code.</p>
<p>So I took out my laptop during the next 60 minutes of Panel Debate, and wrote an iPhone app, and as I expected the code landed on 46 lines of code for the actual application logic, physics, grits and all. Or 112 lines of code if headers and boiler-plate should be counted as well.</p>
<p>This blog post will describe what I did, in a quite nice model-view-controller fashion <em>(Model and Controller is implemented in the same class)</em>.</p>
<ul>
<li>First of all I needed a view to display my bouncing ball on, I choose to subclass UIViewController to handle this view.</li>
<li>A standard UIView instance with a UIImageView sub-view for the ball is all I need for my view, this I setup using Interface Builder.</li>
<li>And the model/logic is handled by one CGPoint for the current location, and one CGPoint with the current delta movement of the ball.</li>
</ul>
<p>First the custom view controller sets up itself as the accelerometer delegate when awakening from it's nib-file.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>awakeFromNib;
<span style="color: #002200;">&#123;</span>
  self.location = CGPointMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">160</span>, <span style="color: #0000dd;">230</span><span style="color: #002200;">&#41;</span>;
  UIAccelerometer* accelerometer = <span style="color: #002200;">&#91;</span>UIAccelerometer sharedAccelerometer<span style="color: #002200;">&#93;</span>;
  accelerometer.updateInterval = <span style="color: #0000dd;">0.02</span>;
  accelerometer.delegate = self;
<span style="color: #002200;">&#125;</span></pre>
<p>Then comes a private function for the <em>quite faked physics</em>, it is responsible for detecting if a value with a given delta movement has hit a min or max edge. If it do hits an edge, it flips it's delta movement with some deceleration, and corrects it's value.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> inline <span style="color: #0000ff;">BOOL</span> bounce<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">float</span>* val, <span style="color: #0000ff;">float</span>* delta, <span style="color: #0000ff;">float</span> min, <span style="color: #0000ff;">float</span> max<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
<span style="color: #339900;">#define FLIP(val, c) (c - (val - c))</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>*val &lt; min || *val &gt; max<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    *delta = -<span style="color: #002200;">&#40;</span>*delta * <span style="color: #0000dd;">0.75</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">float</span> loc = *val &lt; min ? min : max;
    *val = FLIP<span style="color: #002200;">&#40;</span>*val, loc<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">return</span> YES;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> NO;
<span style="color: #002200;">&#125;</span></pre>
<p>And lastly the delegate method that is called by the accelerometer. Here we update the delta movement, and use the bounce-function to detect and compensate location+delta when the ball hits any edges. If an edge it hit, a vibration is also triggered.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>accelerometer:<span style="color: #002200;">&#40;</span>UIAccelerometer*<span style="color: #002200;">&#41;</span>accelerometer
       didAccelerate:<span style="color: #002200;">&#40;</span>UIAcceleration*<span style="color: #002200;">&#41;</span>acceleration;
<span style="color: #002200;">&#123;</span>
<span style="color: #339900;">#define CAP(val, max) (val &lt; -max ? -max : (val &gt; max ? max : val))</span>
  CGPoint delta = CGPointMake<span style="color: #002200;">&#40;</span>CAP<span style="color: #002200;">&#40;</span>self.delta.x + acceleration.x, <span style="color: #0000dd;">32</span><span style="color: #002200;">&#41;</span>,
                              CAP<span style="color: #002200;">&#40;</span>self.delta.y - acceleration.y, <span style="color: #0000dd;">32</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
  CGPoint location = CGPointMake<span style="color: #002200;">&#40;</span>self.location.x + delta.x,
                                 self.location.y + delta.y<span style="color: #002200;">&#41;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>bounce<span style="color: #002200;">&#40;</span>&amp;location.x, &amp;delta.x, <span style="color: #0000dd;">8</span>, self.view.bounds.size.width - <span style="color: #0000dd;">8</span> <span style="color: #002200;">&#41;</span> ||
      bounce<span style="color: #002200;">&#40;</span>&amp;location.y, &amp;delta.y, <span style="color: #0000dd;">8</span>, self.view.bounds.size.height - <span style="color: #0000dd;">8</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
  <span style="color: #002200;">&#123;</span>
      AudioServicesPlayAlertSound<span style="color: #002200;">&#40;</span>kSystemSoundID_Vibrate<span style="color: #002200;">&#41;</span>;
  <span style="color: #002200;">&#125;</span>
  self.delta = delta;
  self.location = location;
  self.ballView.center = self.location;
<span style="color: #002200;">&#125;</span></pre>
<p>In conclusion Cocoa Touch requires surprisingly little code for accessing and using the accelerometer and trigger a vibration. Triggering a vibration is literary done with a single line of code. The lines of code needed to setup and listen to the accelerometer can literary be counted on the fingers of one hand.</p>
<p>On the downside there is no finer control of the vibration, and if you like to have the rotation angles of the device instead of simple gravity forces of the x, y and z axis, then you must do the math for yourself. Simple enough, but it would had been nice to have to current rotations around each axis as well. </p>
<p>The full source code can be downloaded <a href="http://www.peylow.se/BouncyBall.zip">here</a>.</p>
<p>ps. I dare Mike Jennings to best this <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . ds.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

