<?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; Per-Erik Bergman</title>
	<atom:link href="http://blog.jayway.com/author/pererikbergman/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 28 Jan 2012 15:53:55 +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 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>A behavioral scene graph</title>
		<link>http://blog.jayway.com/2011/01/12/a-behavioral-scene-graph/</link>
		<comments>http://blog.jayway.com/2011/01/12/a-behavioral-scene-graph/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 15:00:44 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Tips & Tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6241</guid>
		<description><![CDATA[This will be an overview of that I think is the coolest scene graph philosophy ever. It will reduce the code and make your graphical framework more dynamic and easier to maintain. It is preferred that you know a bit about regular scene graphs to better grasp the idea since this is not a post [...]]]></description>
			<content:encoded><![CDATA[<p>This will be an overview of that I think is the coolest scene graph philosophy ever. It will reduce the code and make your graphical framework more dynamic and easier to maintain. It is preferred that you know a bit about regular scene graphs to better grasp the idea since this is not a post about scene graph in general.</p>
<h2>Node tree</h2>
<p>The basic structure of a scene graph is a basic node tree. The biggest difference is that the node in a scene graph will have more properties. How ever I will not go into details about this since it is a basic abstract data type. Although I will give you a really quick overview so that you will see the difference between a regular scene graph and a behavioral scene graph.</p>
<p><center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/01/node.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/01/node.png" alt="" title="node" width="173" height="165" class="alignright size-full wp-image-7040" /></a></center></p>
<h3>Data</h3>
<p>The regular node has a data object attached to it. I think this data is the perfect place to store the data to be rendered. I usually uses the name entity instead of data so we change that. So now we got this:</p>
<p><center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/01/node_entity.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/01/node_entity.png" alt="" title="node_entity" width="411" height="165" class="alignright size-full wp-image-7045" /></a></center></p>
<p>The graph is still intact with just one single node type, what we change is the entity. Different entities can be light, camera, animations or any other type that you usually find in a scene graph.</p>
<p>I also like to add another property to the node called behavior.</p>
<h3>Behavior</h3>
<p>This is where it gets cool. A behaviour is attached to the node just as a data object but the behavior also have access to the node and it's properties.<br />
<center><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/01/node_entity_behaviour.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/01/node_entity_behaviour.png" alt="" title="node_entity_behaviour" width="365" height="379" class="alignright size-full wp-image-7048" /></a></center></p>
<p>Before the rendering we usually have a call to update the logic this update call should be rerouted to the behavior. Meaning that we do not add any specific logic to the node we add it to a behaviour attached to the node. This make it easy to change during runtime. </p>
<h3>Example 1:</h3>
<p>Say we have a behaviour that is an animation it can animate the node by accessing it’s properties. This way we get an easy way of animating a node. It is also really easy to reuse and attache to other nodes.</p>
<h3>Example 2:</h3>
<p>Let us make a button. We create an implementation of the behaviour that have functions like: onClick, onLongClick, onRelease and so on. This functions could trigger different animations depending on the desired behaviour on our button.</p>
<h3>Example 3:</h3>
<p>If we have a behaviour that strives to put the children of the node in a certain way by animating them in a nice ease-in-ease-out tween from their current position towards their preferred position.</p>
<p>And we implement a behaviour to have the preferred positions mapping against a grid like layout. This will make the nodes in a nice way be animated into a grid layout.</p>
<p>If we then make an implementation that have the preferred positions arranged as in a circle and at any given time set this behaviour to be the acting behaviour on our node. This will make all the child nodes change their preferred positions and start moving towards the new preferred positions.</p>
<h3>Example 4:</h3>
<p>Let us step it up one more time. Say we create an adapter node similar to the adapter view in android and give the node a default set of 5 children. We then make an implementation that arrange the children of our node into a list and makes it scrollable and to exchange the children as they fall in and out of the visible range of the list. </p>
<p>Make an other behaviour that also uses an adapter node and make this one display the child nodes as a roller index and swap the behaviours. Now when we change the behaviour we get a cool animation between two different list layouts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/01/12/a-behavioral-scene-graph/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>Thoughts on creating a framework</title>
		<link>http://blog.jayway.com/2010/09/02/thoughts-on-creating-a-framework/</link>
		<comments>http://blog.jayway.com/2010/09/02/thoughts-on-creating-a-framework/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 06:10:58 +0000</pubDate>
		<dc:creator>Per-Erik Bergman</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Tips & Tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6242</guid>
		<description><![CDATA[I have been developing frameworks for different applications mostly games for over 10 years. Over this time I have made some really bad decisions and wrong turns, fortunately I have learned and gained some knowledge that always made my next framework a bit better. Design patterns One of my first lessons was that I don’t [...]]]></description>
			<content:encoded><![CDATA[<p>I have been developing frameworks for different applications mostly games for over 10 years. Over this time I have made some really bad decisions and wrong turns, fortunately I have learned and gained some knowledge that always made my next framework a bit better.</p>
<h2>Design patterns</h2>
<p>One of my first lessons was that I don’t have to reinvent stuff over and over again. That there was people that actually have solved my problems before. So I started to learn design patterns. This really made a big difference. I had a problem that I outlined and then I looked for design patterns within my problem and if there was minor adjustments to my solution to make it in to a design pattern I made them. This actually helped me a lot later on in the project with problems I did not know about until later on.</p>
<h2>Singletons, one of my biggest mistakes</h2>
<p>I started to use singletons quite frequently and ended up with stiff frameworks that worked fine for a specific project but was often not that flexible to be able to be called a framework.</p>
<p>Later on I learned that a provider that gives me the same instance of that class that I earlier made as a singleton works fine. Some programmers like to put this provider within the same class and some don't. I want to be able to change the implementation of this "singleton"-workaround so I don't believe that the construction of a class like this should be within the class it self.</p>
<h2>Performance</h2>
<p>I started to make bigger and more complex frameworks and started to loose performance. Most of my framework is about graphic programming and are in need of good performance. It is a great difference between optimization and optimization. There are two major optimization types. </p>
<p><strong>1.</strong> Heavy functions like sinus, co-sinus. This ones you can wait with to optimize just because they are often just function calls.</p>
<p><strong>2.</strong> The other optimization are more in an architecturally way. For example if you have a lot of if-else/switches and logic with in a render loop. This ones are much more difficult to solve later on. This ones should be solved at the moment you notice them because this ones often affect other parts as well.</p>
<p>The second one I had to learn the hard way. I have made several frameworks thinking: <em>“I can fix that later.”</em> To remove this "known" performance issues it will be so much easier later on to optimize when using a profiler.</p>
<h2>User friendly</h2>
<p>In the beginning most of the framework was made for me to work with. But later when other people started to work with my frameworks I realized one of my biggest mistake ever. My frameworks was not so user friendly, not at all in fact some of them was so unfriendly that they was useless to any one other then me.</p>
<p>I found two ways of fixing the usability.</p>
<p><strong>1.</strong> Actually make the API easier, this is the most obvious one. This one made me start making changes and adding functionality that made my frameworks start to grow and become big monsters. That I had problems maintaining.</p>
<p>I figured out that by keeping my frameworks small and compact with good APIs made them easier to maintain</p>
<p><strong>2.</strong> A good API is necessary but not all we need. It should still be easy for users to work with so I started to make help classes. I made a help library that gave the user functions to create stuff with my framework in an easy way. </p>
<p><strong>One example: </strong><br />
In the framework we have a class representing a mesh (a 3D representation of geometry) to render to the screen. Should the framework care about what that mesh looks like or represents? I don’t think so. So a classes called a box, plane, sphere or cone are not really usefully to the framework only to the user of the framework. So I moved the constructions on this classes to a help library. The user tells a factory to create a sphere with some settings and the factory creates an mesh.</p>
<p>So my thoughts are what?<br />
<em> - Your problem is probably already solved on someway and they have probably tested it more then you will be able to. Use that!</em></p>
<p><em> - Performance, there is something called premature optimization but there is also something called mature optimization that need to be fixed asap.</em></p>
<p><em> - User friendly, if you write a framework that other should use it is your responsibility to make it user friendly. If you get the developer to like your framework, then you are in a good position.</em></p>
<p>Don't forget that if you are making a framework with no real project to test it on you are trying to solve problems that you make up as you go.  Try to develop of a framework within a real live project, then you get real problems and will get a better framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/09/02/thoughts-on-creating-a-framework/feed/</wfw:commentRss>
		<slash:comments>3</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>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>
	</channel>
</rss>

