<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Jayway Team Blog » Android</title>
	
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Thu, 01 Apr 2010 08:41:54 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jayway/posts/android" /><feedburner:info uri="jayway/posts/android" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:browserFriendly></feedburner:browserFriendly><item>
		<title>OpenGL ES Tutorial for Android – Part V – 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></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=""></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>12</slash:comments>
		</item>
		<item>
		<title>The easy way to test Android applications</title>
		<link>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/</link>
		<comments>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 09:44:44 +0000</pubDate>
		<dc:creator>Renas Reda</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4536</guid>
		<description><![CDATA[I’m going to guess that most of you know what instrumentation is. In the event that you don't, instrumentation is a feature in which specific monitoring of the interactions between an application and the system is made possible. Instrumentation also makes it possible to write test cases that interact with the application. The problem with [...]]]></description>
			<content:encoded><![CDATA[<p>I’m going to guess that most of you know what instrumentation is. In the event that you don't, instrumentation is a feature in which specific monitoring of the interactions between an application and the system is made possible. Instrumentation also makes it possible to write test cases that interact with the application. The problem with instrumentation, however, is that it is incredibly hard to write solid test cases for applications bigger than the typical “Hello World!” application. A tremendous amount of technical details must be taken into account in order to write a good test case. Often, developers quickly realize that it will take almost as long to write a comprehensive test case as it took to write the whole application. I, myself, came to recognize the very same thing when I first started looking into how to use instrumentation tests with the android application project that I’m currently working on.</p>
<p>I soon came to understand that I would not be able to take advantage of all the wonderful possibilities that instrumentation offers. The reason for that is quite simple; the application that we are in the process of developing is not only extensive but also complicated with multiple activities, self-defined intents, and hundreds of views that also include scrollable lists. It would not make sense for me to spend a month writing one single test case that would only take 20 seconds to test manually. That is how Robotium-Solo was born. I needed a test framework that would help me write good and powerful test cases that emulated real users. The test case should be able to do what a real user does: click on anything that is clickable, look for irregularities, automatically move from activity to activity, etc. More importantly, I should not have to spend more than 10 minutes writing a test case that involves more then one activity.</p>
<p>With the help of Robotium-Solo a test case spanning over multiple activities could look like this:</p>
<pre class="brush:java">public void testTextIsSaved() throws Exception {
   solo.clickOnText("Other");
   solo.clickOnButton("Edit");
   assertTrue(solo.searchText("Edit Window"));
   solo.enterText(0, "Some text for testing purposes")
   solo.clickOnButton("Save");
   assertTrue(solo.searchText("Changes have been made successfully"));
   solo.clickOnButton("Ok");
   assertTrue(solo.searchText("Some text for testing purposes"));
}
</pre>
<p>As you can see, I don’t have to specify any technical details or tell Robotium-Solo where to look for something, such as scrolling down a list when needed. It handles the above and more all on its own.</p>
<p>If you are interested in writing test cases of similar nature have a look at http://www.robotium.org. It makes writing powerful test cases a breeze.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/28/the-easy-way-to-test-android-applications-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Boosting Android performance using JNI</title>
		<link>http://blog.jayway.com/2010/01/25/boosting-android-performance-using-jni/</link>
		<comments>http://blog.jayway.com/2010/01/25/boosting-android-performance-using-jni/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 13:03:12 +0000</pubDate>
		<dc:creator>Mattias Rosberg</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4390</guid>
		<description><![CDATA[JNI or Java Native Interface is the interface between the Java code running in a JVM and the native code running outside the JVM. It works both ways, that is you can use JNI to call native code from your Java programs and to call Java code from your native code. The native code normally [...]]]></description>
			<content:encoded><![CDATA[<p>JNI or Java Native Interface is the interface between the Java code running in a JVM and the native code running outside the JVM. It works both ways, that is you can use JNI to call native code from your Java programs and to call Java code from your native code. The native code normally resides within a library (.so file) and is typically written in C/C++.</p>
<p>There's a few reasons when to use JNI in a Java program</p>
<ul>
<li><strong>Wrap lower level functionality</strong> - Classes in the Android Application Framework uses JNI to interface with the underlying platform and hardware like Camera, Sensors and GPS.</li>
<li><strong>Interface native legacy code</strong> - You might have some old legacy code written in C/C++ and you don't want to waste your time porting the code to Java. With JNI you can create an interface class in Java that exposes the functionality of your legacy code.</li>
<li><strong>Bypass performance bottlenecks</strong> - Execute heavy number crunching in native code and get rid of the overhead that the instruction interpretation in the JVM introduces.
</ul>
<p>On Android, in order to prevent fragmentation, we are only allowed to use the following libraries in our native code.</p>
<ul>
<li>libc (C library) headers</li>
<li>libm (math library) headers</li>
<li>JNI interface headers</li>
<li>libz (Zlib compression) headers</li>
<li>liblog (Android logging) header</li>
<li>OpenGL ES 1.1 (3D graphics library) headers (since 1.6)</li>
<li>A Minimal set of headers for C++ support</li>
</ul>
<p>In this blog I will demonstrate how to transform a time consuming Java method with a lot of number crunching into a native declared method where the real work is performed in native code. Here's the time consuming Java method</p>
<pre class="brush:java">
public double compare(int[] sourceData,int[] targetData, double targetError) {
  double error = 0.0D;
  for (int index = 0; index < targetData.length; index++) {
    int c1 = sourceData[index];
    int c2 = targetData[index];
    int b = (c1 >> 16 & 255) - (c2 >> 16 & 255);
    int g = (c1 >> 8 & 255) - (c2 >> 8 & 255);
    int r = (c1 & 255) - (c2 & 255);
    error += r * r + g * g + b * b;
    if (error > targetError)
      return error;
  }
  return error;
}
</pre>
<p>The <strong>sourceData</strong> and <strong>targetData</strong> arguments represents the pixels of two Bitmaps. In short the method calculates the sum of the square distance in color between two images, pixel by pixel. If we compare two 200x200 pixels images the <strong>for-loop</strong> will run 40000 times! This is a typical candidate for when to use JNI.</p>
<h3>What to do in Native</h3>
<p>You can use the <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/01/boilerplate.c">boilerplate.c</a> file as boilerplate code for all your native c functions. </p>
<h4>Implement the native function</h4>
<p>This is what the function will look like when written in C.</p>
<pre class="brush:c">
static jdouble compareNative(JNIEnv *env, jobject thiz, jintArray sourceArr,
                                                jintArray targetArr, jdouble targetError){
  jdouble error = 0.0;
  int index, c1, c2, b, g, r  = 0;
  jint *sarr, *tarr;

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

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

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

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

static JNINativeMethod methods[] = {
  // nameOfNativeMethod, methodSignature, methodPointer
  {"compare", "([I[ID)D", (void*)compareNative },
};
</pre>
<p>The first parameter is the name of the native declared Java method, the second is the signature of the native declared Java method and the last parameter is the function pointer to the C function to execute when the native declared Java function is executed.</p>
<p>The signature of a Java method can be determined using the <strong>javap</strong> tool from SUN's Java SDK or you can create it yourself using the following table, <a href="http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/method.html">Java VM Type Signatures</a>.</p>
<h4>Build using Android NDK</h4>
<p>To make things really simple when developing JNI code Google has released the <a href="http://developer.android.com/sdk/ndk/1.6_r1/index.html">Android Native Development Kit (NDK)</a>. It's easy to setup and use. Just setup a new project according to the NDK documentation and build your project. The resulting <strong>libs</strong> folder should be included into your Android project.</p>
<h3>What to do in Java</h3>
<p>In order to transform our Java method into a native declared method simply add the word <strong>native</strong> in the method signature and remove the implementation of the method.</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">double</span> compare<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> sourceData, <span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> targetData,
			<span style="color: #993333;">double</span> targetError<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>To make sure that the virtual machine loads our library into memory and register our native functions we have to add the following code.</p>
<pre class="brush:java">
static{
  System.loadLibrary("comparejni");
}
</pre>
<p>This tells the virtual machine to load the library <strong>lib</strong>comparejni<strong>.so</strong> from the underlying operating system. The OnLoad function is executed on the library and our native functions gets registered with the virtual machine.</p>
<h3>The Result</h3>
<p>After some simple benchmarking I found that the native declared method executed about 2-3 times faster than the original method executing within Dalvik. For larger images the improvement might be even bigger since a call to a native declared method takes more time than calling a normal Java method. Eventually, when Dalvik supports JIT compilation, we would probably get the above performance boost for free without calling native functions. But bear in mind, most devices on the market today will never get an upgraded Dalvik with JIT.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/25/boosting-android-performance-using-jni/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Learn to Stop Worrying and Love the Singleton</title>
		<link>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/</link>
		<comments>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 13:00:10 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[spring ldap]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4273</guid>
		<description><![CDATA[Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. [...]]]></description>
			<content:encoded><![CDATA[<p>Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. This means that a mobile application must start in an instant, whereas starting and enterprise application may take as long as it takes. </p>
<p>Dependency injection and early validation is crucial for an enterprise application, and <a href="http://www.springsource.org/">Spring</a> is a boon in this regard. But do not fool yourself, Spring is good, but it is not a universal cure. Especially not in mobile space where startup times, low memory consumption, and avoiding interfaces are virtues.</p>
<p>The bottleneck in an enterprise application is most probably the database, spending a few extra milliseconds here and there seldom matters. On much less performant mobile device those clock cycles are not only time the user has to spend waiting, it will drain the battery. A simple thing as using an interface instead of an abstract superclass will perform at least twice as slow. Even passing an extra argument in the constructors a few nestings deep will have an impact.</p>
<h3>Lazy Singeltons by Choice</h3>
<p>Class loading in Java is lazy, the Java VM will not load classes until they are referenced. Odds are that the user will not trigger a full coverage of all classes in your app for a short time running mobile app. If the user just checks for incoming messages and quits, then every class involved in composing messages do not need to be loaded. Early dependency injection breaks this, as all classes will be referenced at startup. Most components will be initialized in vain, as they are never actually used.</p>
<p>So what we should do in mobile application is to work more like the Java VM, and less like Spring. If possible do not create a component until it is requested. The best way to do this is using a singleton pattern. Not a normal enforced singleton pattern, but rather a singleton by choice. Let the constructor be public, trust your users, and name the getter <code>getSharedFoo()</code>, not <code>getInstance()</code>. Let me show you using a example of an URL cache component:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  public URLCache() {
    // More code...
  }
  // Allot more code here...

}</pre>
<p>Using this shared URL cache component from our imaginary HTTP provider would then be super easy, but not mandatory:</p>
<pre class="brush:java">public class HTTPProvider {

  public InputStream inputStreamForURL(String url) {
    URLCache cache = URLCache.getSharedURLCache();
    // Use the cache...
  }

}</pre>
<p>The big win here is that if the code path of this run of the application never tries to open an input stream then the URL cache never has to be created. Saving several hundred milliseconds of reading cache indexes, validation, etc.</p>
<h3>But What About Testing?</h3>
<p>Are not singletons bad for unit tests and mocking components? They used to be. These days we have <a href="http://www.powermock.org/">PowerMock</a>, you really should use it. Turns out that not even PowerMock is really required, if we just change our singleton pattern very slightly, and allows the outside to set the shared component as well:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static void setSharedURLCache(URLCache cache) {
    synchronized (URLCache.class) {
      sharedCache = cache;
    }
  }

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  // Allot more code here...

}</pre>
<p>This small addition allows us for setup up our own mock cache in the setup of our unit tests. With something as simple as this:</p>
<pre class="brush:java">public class SomeTest extends TestCase {

  public void setUp() {
    URLCache.setSharedURLCache(new NoOpURLCache());
  }

  public void testRemoteResource() {
    assertNotNull(HTTPProvider.getSharedHTTPProvider().inputStreamForURL(TEST_URL));
  }
}</pre>
<p>It also allows us for explicitly override a singleton if our application has special needs, perhaps a more aggressive cache on a low bandwidth mobile data connection, or special implementation on a buggy Java ME platform. But most importantly for the normal case it will not waste time creating the component until it is actually needed, vastly improving the user experience for your mobile users.</p>
<h3>Take Aways</h3>
<p>Do not fear singletons, it is a great way of lazy creations that will greatly improve startup times and memory consumption on mobile applications.</p>
<p>Avoid using interfaces, they are at least twice as slow as classes, and can not have static methods for acquiring the lazy created components.</p>
<p>Do not enforce the singleton pattern, always use singleton by choice. To allow for testing and easy implementation of special cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part IV – 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. OpenGL ES [...]]]></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></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>7</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 I [...]]]></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></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>10</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part II – 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.
Vertex
A vertex (vertices in [...]]]></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/glDrawElements.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></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>14</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part I – 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 give [...]]]></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></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>8</slash:comments>
		</item>
		<item>
		<title>Getting Android SDK working on Ubuntu 64</title>
		<link>http://blog.jayway.com/2009/10/21/getting-android-sdk-working-on-ubuntu-64/</link>
		<comments>http://blog.jayway.com/2009/10/21/getting-android-sdk-working-on-ubuntu-64/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 20:22:34 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2110</guid>
		<description><![CDATA[Today I was trying to setup the Android SDK (version 1.6_r1)  on the 64 bit version of Ubuntu 9.04 (Jaunty Jackalope). After having installed the ADT Eclipse plugin and pointed out the Android SDK directory in the settings I immediately ran into the following error: 

Failed to get the adb version: Cannot run program [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was trying to setup the Android SDK (version <a href="http://developer.android.com/sdk/download.html?v=android-sdk-linux_x86-1.6_r1.tgz">1.6_r1</a>)  on the 64 bit version of Ubuntu 9.04 (Jaunty Jackalope). After having installed the <a href="http://dl.google.com/android/ADT-0.9.3.zip">ADT</a> Eclipse plugin and pointed out the Android SDK directory in the settings I immediately ran into the following error: </p>
<pre>
Failed to get the adb version: Cannot run program "/home/johan/devtools/android/android-sdk-linux_x86-1.6_r1/tools/adb": java.io.IOException: error=2, No such file or directory
</pre>
<p>I opened the terminal and tried to manually run an Android executable but even here it said that the file couldn't be found! The problem seemed to be that the Android executables requires 32 bit libraries that are not available in Ubuntu 64 by default. To solve this I downloaded the execellent <a href="http://frozenfox.freehostia.com/cappy/getlibs-all.deb">getlibs</a> application which is a utility for automatically resolving dependencies for 32-bit programs on a 64 bit system. So I went into <code>platforms/android-1.6/tools</code> in the Android SDK installation folder and executed:</p>
<pre class="bash">&nbsp;
getlibs aapt
&nbsp;</pre>
<p>which installed and upgraded the following libraries:</p>
<pre class="bash">&nbsp;
The following NEW packages will be installed:
  ia32-libs lib32asound2 lib32gcc1 lib32ncurses5 lib32stdc+<span style="color: #000000;">+6</span> lib32z1
  libc6-i386
The following packages will be upgraded:
  libc6 libc6-dev
&nbsp;</pre>
<p>After this was done I went back into Eclipse, did a project clean and refresh and after that I was able to start the Android emulator successfully. Hopefully this may help someone who's in the same situation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/21/getting-android-sdk-working-on-ubuntu-64/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The BROWSABLE category revealed</title>
		<link>http://blog.jayway.com/2009/09/24/the-browsable-category-revealed/</link>
		<comments>http://blog.jayway.com/2009/09/24/the-browsable-category-revealed/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 08:58:56 +0000</pubDate>
		<dc:creator>Mattias Rosberg</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1932</guid>
		<description><![CDATA[Assume that you on your desktop computer browse to a web page with the following page source

Clicking on the first link you expect your browser to start a new tab and navigate to the url that was specified in the href. If you click on the second link you would expect that the browser opens [...]]]></description>
			<content:encoded><![CDATA[<p>Assume that you on your desktop computer browse to a web page with the following page source</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/shit.png" alt="shit" title="shit" width="417" height="102" class="aligncenter size-full wp-image-1940" /></p>
<p>Clicking on the first link you expect your browser to start a new tab and navigate to the url that was specified in the href. If you click on the second link you would expect that the browser opens up your favourite email client. The third link would probably just give you an error message since the browser has no idea how to react on a link like <b>foo://my.test.com</b></p>
<p>On Android we can control how the device should react when the user clicks on a link in the web browser, or more specific control which Activity should be started. Every time the user clicks on a link the browser sends an intent to the platform with the following content.<br />
<code><br />
action = android.intent.action.VIEW<br />
category = android.intent.category.BROWSABLE<br />
data = the text from the href tag<br />
</code><br />
If we navigate to a web page with the following page source on our Andoid device we could expect a few interesting things to happen when we click on the links.</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/shit2.png" alt="shit2" title="shit2" width="414" height="106" class="aligncenter size-full wp-image-1941" /></p>
<p>The first link will generate an intent with the following information<br />
<code><br />
action = android.intent.action.VIEW<br />
category = android.intent.category.BROWSABLE<br />
data = "tel:123456"<br />
</code><br />
This will start the Dialer application and preset the phone number to 123456.</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/device.png" alt="device" title="device" width="320" height="480" class="aligncenter size-full wp-image-1955" /></p>
<p>Clicking on the second link will not surprisingly open up the email client in your device with a preset receiver address. What about clicking on the third link? Well, by default it would just return a <strong>"page not available"</strong> error message in the browser. The intent sent from the browser will look like this<br />
<code><br />
action = android.intent.action.VIEW<br />
category = android.intent.category.BROWSABLE<br />
data = "foo://my.test.com"<br />
</code><br />
This means that if we install an Activity with the following IntentFilter</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/09/intentfilter.png" alt="intentfilter" title="intentfilter" width="524" height="110" class="aligncenter size-full wp-image-1962" /></p>
<p>this Activity will start when the user clicks on the third link. Pretty cool, isn't it?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/09/24/the-browsable-category-revealed/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
