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

<channel>
	<title>Android Wizard</title>
	<atom:link href="http://androidwizard.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://androidwizard.net</link>
	<description>Learn the Android Mobile Platform!</description>
	<lastBuildDate>Tue, 21 Jun 2011 04:46:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Mobclix DOESN&#8217;T Pay &#8211; Stay Away</title>
		<link>http://androidwizard.net/2011/06/mobclix-doesnt-pay-stay-away/</link>
		<comments>http://androidwizard.net/2011/06/mobclix-doesnt-pay-stay-away/#comments</comments>
		<pubDate>Tue, 21 Jun 2011 04:42:47 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[mobclix]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=647</guid>
		<description><![CDATA[If you&#8217;ve researched the ad placement networks for your Android applications and games you no doubt have encountered Mobclix. They offer better fill rates and higher payments by distributing your ads across several networks. This sounds great and in practice it seems to work well. I have several apps myself through Mobclix&#8217;s service. However, developer [...]]]></description>
			<content:encoded><![CDATA[<p><!--noadsense--><br />
If you&#8217;ve researched the ad placement networks for your Android applications and games you no doubt have encountered Mobclix. They offer better fill rates and higher payments by distributing your ads across several networks. This sounds great and in practice it seems to work well.</p>
<p>I have several apps myself through Mobclix&#8217;s service. However, developer beware. You may never receive you money, and you may be getting screwed on the exact amount you are supposed to receive.</p>
<p>First, the statistics may or may not be accurate. Mobclix is at the mercy of the ad networks they distribute. There has been several times since I&#8217;ve been a developer with them that they have went back and &#8216;adjusted&#8217; the payment amounts. What I mean by adjusted is that they have lowered the amount that my application earned. They have claimed several times in their blog that this is due to the ad networks disputing payments across their entire network. This would be fine if they gave you a detailed statistics panel that gave you an in depth breakdown of how much you were receiving per ad network and per app. However, their interface is generally a joke. If it feels like loading on that particular day then it only displays broad numbers with absolutely no breakdown at all.</p>
<p>So accidents happen. I can accept that. I can definitely accept that the technology may have flubbed once or twice causing thousands of users to report higher earnings then they were actually receiving, but what I <strong>CANNOT </strong>accept is late payment.</p>
<p>I&#8217;ve been with Mobclix for almost a year with my applications. It takes quite awhile to receive your first payment, since checks are sent out net 30 AFTER the ad network pays Mobclix. So according to Mobclix all payments come at net 90. In short it takes three months to receive that months payment. January advertising will come in May 15th. That is a long time to wait.</p>
<p><img src="http://androidwizard.net/wp-content/uploads/2011/06/money-man-219x300.jpg" alt="" title="money-man" width="219" height="300" class="alignleft size-medium wp-image-653" />So why is it that of the 11 months I have been with Mobclix I have had to personally e-mail and call them 6 of those months asking for my payment. Right now my payments are 3 months behind. Yes that&#8217;s right I haven&#8217;t received a payment in 3 months. I was supposed to receive <strong>3</strong>. <strong>They will never send a payment unless you bother them.</strong> Then sometimes they still won&#8217;t.</p>
<p>If you advertise with Mobclix in my humble opinion you are throwing your advertising money away. If you value your time at all then the amount of harassment and trouble you have to go through to get $1000 or $100 is not worth it.</p>
<p>If you have any questions or comments about Mobclix or my experience with them then please leave a comment!</p>
]]></content:encoded>
			<wfw:commentRss>http://androidwizard.net/2011/06/mobclix-doesnt-pay-stay-away/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spinner View &#124; Android Beginner Dev Tutorial</title>
		<link>http://androidwizard.net/2011/01/spinner-view-android-beginner-dev-tutorial/</link>
		<comments>http://androidwizard.net/2011/01/spinner-view-android-beginner-dev-tutorial/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 05:01:09 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[beginner]]></category>
		<category><![CDATA[spinner view]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=638</guid>
		<description><![CDATA[This is again another very simple tutorial on using a Spinner View provided by Android SDK. A spinner is supposed to be a view that displays one child at a time .]]></description>
			<content:encoded><![CDATA[<p>This example is very similar to the previous one on AutoCompleteTextView. </p>
<p>Jumping right into the code, here is the layout xml file:</p>
<pre class="brush: xml; title: ; notranslate">Spinner
android:id=&quot;@+id/Spinner01&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:drawSelectorOnTop = &quot;true&quot;&gt;&lt;/Spinner&gt;</pre>
<p>Nothing special. It just consists of one element.</p>
<p>Now in the main activity, I create an array of android books:</p>
<pre class="brush: java; title: ; notranslate">String[] androidBooks =
{
&quot;Hello, Android - Ed Burnette&quot;,
&quot;Professional Android 2 App Dev - Reto Meier&quot;,
&quot;Unlocking Android - Frank Ableson&quot;,
&quot;Android App Development - Blake Meike&quot;,
&quot;Pro Android 2 - Dave MacLean&quot;,
&quot;Beginning Android 2 - Mark Murphy&quot;,
&quot;Android Programming Tutorials - Mark Murphy&quot;,
&quot;Android Wireless App Development - Lauren Darcey&quot;,
&quot;Pro Android Games - Vladimir Silva&quot;,
};</pre>
<p>Then in the onCreate() method, I create an ArrayAdapter that I can pass to this Spinner as the data Source. </p>
<pre class="brush: java; title: ; notranslate">ArrayAdapter&lt;String&gt; adapter =
        new ArrayAdapter&lt;String&gt; (this,
        android.R.layout.simple_spinner_item,androidBooks);</pre>
<p>Then, I get a handle to the Spinner, and set the ArrayAdapter to it</p>
<pre class="brush: java; title: ; notranslate">sp = (Spinner)findViewById(R.id.Spinner01);
sp.setAdapter(adapter);</pre>
<p>Now, on selecting one of the items in the spinner, I want to be able to toast a message on the book that was selected. It is done as follows:</p>
<pre class="brush: java; title: ; notranslate">sp.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView&lt;?&gt; arg0, View arg1, int arg2, long arg3) {
        int item = sp.getSelectedItemPosition();
        Toast.makeText(getBaseContext(),
            &quot;You have selected the book: &quot; + androidBooks[item],
            Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView&lt;?&gt; arg0) {
    }
});</pre>
]]></content:encoded>
			<wfw:commentRss>http://androidwizard.net/2011/01/spinner-view-android-beginner-dev-tutorial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Easy Way to Test Android SDK Applications</title>
		<link>http://androidwizard.net/2011/01/the-easy-way-to-test-android-applications/</link>
		<comments>http://androidwizard.net/2011/01/the-easy-way-to-test-android-applications/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 10:28:13 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[hello world]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=558</guid>
		<description><![CDATA[I’m going to guess that most of you know what instrumentation is. In the event that you don&#8217;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&#8217;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; title: ; notranslate">public void testTextIsSaved() throws Exception {
   solo.clickOnText(&quot;Other&quot;);
   solo.clickOnButton(&quot;Edit&quot;);
   assertTrue(solo.searchText(&quot;Edit Window&quot;));
   solo.enterText(0, &quot;Some text for testing purposes&quot;)
   solo.clickOnButton(&quot;Save&quot;);
   assertTrue(solo.searchText(&quot;Changes have been made successfully&quot;));
   solo.clickOnButton(&quot;Ok&quot;);
   assertTrue(solo.searchText(&quot;Some text for testing purposes&quot;));
}</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://androidwizard.net/2011/01/the-easy-way-to-test-android-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Boosting Android SDK performance using JNI</title>
		<link>http://androidwizard.net/2011/01/boosting-android-performance-using-jni/</link>
		<comments>http://androidwizard.net/2011/01/boosting-android-performance-using-jni/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 10:23:16 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JNI]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=553</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 resides within a library (.so file) and is typically written in C/C++.]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a few reasons when to use JNI in a Java program</p>
<li>
Wrap lower level functionality &#8211; Classes in the Android Application Framework uses JNI to interface with the underlying platform and hardware like Camera, Sensors and GPS.	</li>
<li>Interface native legacy code &#8211; You might have some old legacy code written in C/C++ and you don&#8217;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>Bypass performance bottlenecks &#8211; Execute heavy number crunching in native code and get rid of the overhead that the instruction interpretation in the JVM introduces.</li>
<p>On Android, in order to prevent fragmentation, we are only allowed to use the following libraries in our native code.</p>
<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>
<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&#8217;s the time consuming Java method</p>
<pre class="brush: java; title: ; notranslate">public double compare(int[] sourceData,int[] targetData, double targetError) {
  double error = 0.0D;
  for (int index = 0; index &lt; targetData.length; index++) {
    int c1 = sourceData[index];
    int c2 = targetData[index];
    int b = (c1 &gt;&gt; 16 &amp; 255) - (c2 &gt;&gt; 16 &amp; 255);
    int g = (c1 &gt;&gt; 8 &amp; 255) - (c2 &gt;&gt; 8 &amp; 255);
    int r = (c1 &amp; 255) - (c2 &amp; 255);
    error += r * r + g * g + b * b;
    if (error &gt; targetError)
      return error;
  }
  return error;
}</pre>
<p>The sourceData and targetData 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 200&#215;200 pixels images the for-loop 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 boilerplate.c file as boilerplate code for all your native c functions.</p>
<p>Implement the native function<br />
This is what the function will look like when written in C.</p>
<pre class="brush: java; title: ; notranslate">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)-&gt;GetIntArrayElements(env, sourceArr, NULL);
  tarr = (*env)-&gt;GetIntArrayElements(env, targetArr, NULL);

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

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

  for (index = 0; index &lt; size; index++) {
    c1 = sarr[index];
    c2 = tarr[index];
    b = (c1 &gt;&gt; 16 &amp; 255) - (c2 &gt;&gt; 16 &amp; 255);
    g = (c1 &gt;&gt; 8 &amp; 255) - (c2 &gt;&gt; 8 &amp; 255);
    r = (c1 &amp; 255) - (c2 &amp; 255);
    error += r * r + g * g + b * b;
    if (error &gt; targetError){
      (*env)-&gt;ReleaseIntArrayElements(env, sourceArr, sarr, 0);
      (*env)-&gt;ReleaseIntArrayElements(env, targetArr, tarr, 0);
      return error;
    }
  }
 (*env)-&gt;ReleaseIntArrayElements(env, sourceArr, sarr, 0);
 (*env)-&gt;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 &#8220;this pointer&#8221; 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 JNI Reference Documentation.</p>
<p>Register your native functions<br />
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 registerNatives function of the JNIEnv. If you use the boilerplate C code from above you only have to do two things.</p>
<ol>
Set the classpath variable to the full class name of your Java class (including package name). Replace the dots with slashes.</ol>
<ol>
<p>For each native declared method in Java, insert a JNINativeMethod struct into the methods[] array.</ol>
<p>For our example it will look like this</p>
<pre class="brush: java; title: ; notranslate">static const char *classPathName = &quot;com/jayway/MyComparator&quot;;

static JNINativeMethod methods[] = {
  // nameOfNativeMethod, methodSignature, methodPointer
  {&quot;compare&quot;, &quot;([I[ID)D&quot;, (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 javap tool from SUN's Java SDK or you can create it yourself using the following table, Java VM Type Signatures.</p>
<p>Build using Android NDK<br />
To make things really simple when developing JNI code Google has released the Android Native Development Kit (NDK). It's easy to setup and use. Just setup a new project according to the NDK documentation and build your project. In short, you create a folder named jni in your Android Eclipse project. Here you put all the c-files together with an Android.mk file. In the Android.mk you specify which c-files to compile. In the Android NDK/apps folder you create a directory named after your project (perhaps my-app). In this directory you add an Application.mk file. In the Application.mk, set the APP_PROJECT_PATH to the path of your Eclipse project. To create the lib simply type make APP=my-app from the console in your Android NDK folder. If everything goes well you will see a libs folder in your Eclipse project.</p>
<h3>What to do in Java</h3>
<p>In order to transform our Java method into a native declared method simply add the word native in the method signature and remove the implementation of the method.</p>
<pre class="brush: java; title: ; notranslate">public native double compare(int[] sourceData, int[] targetData,
			double targetError);</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; title: ; notranslate">static{
  System.loadLibrary(&quot;comparejni&quot;);
}</pre>
<p>This tells the virtual machine to load the library libcomparejni.so 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://androidwizard.net/2011/01/boosting-android-performance-using-jni/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learn to Stop Worrying and Love the Singleton</title>
		<link>http://androidwizard.net/2011/01/learn-to-stop-worrying-and-love-the-singleton/</link>
		<comments>http://androidwizard.net/2011/01/learn-to-stop-worrying-and-love-the-singleton/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 10:07:00 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Phone Calls]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=547</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. This means that a mobile application must start in an instant, whereas starting and enterprise application may take as long as it takes.]]></description>
			<content:encoded><![CDATA[<p>Dependency injection and early validation is crucial for an enterprise application, and Spring 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 getSharedFoo(), not getInstance(). Let me show you using a example of an URL cache component:</p>
<pre class="brush: java; title: ; notranslate">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; title: ; notranslate">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 PowerMock, 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; title: ; notranslate">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; title: ; notranslate">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://androidwizard.net/2011/01/learn-to-stop-worrying-and-love-the-singleton/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part VI – Textures</title>
		<link>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-vi-%e2%80%93-textures/</link>
		<comments>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-vi-%e2%80%93-textures/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 09:51:36 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[opengl]]></category>
		<category><![CDATA[textures]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=533</guid>
		<description><![CDATA[Last tutorial we worked a bit more on meshes and we have also talked about adding colors to our mesh. The most common way of adding colors to your mesh is to add a texture. There is a couple of different steps involved with adding a texture to the mesh I will try to go through them all and explain the basics about them.]]></description>
			<content:encoded><![CDATA[<h3>Loading bitmaps</h3>
<p>First step would be to get a bitmap to generate a texture from. You can get hold of a bitmap in many different ways from downloading, generating or simply just load one from the resources. I&#8217;m going with the simplest one for this example witch is loading from the resources.</p>
<pre class="brush: java; title: ; notranslate">Bitmap bitmap = BitmapFactory.decodeResource(contect.getResources()
                                             R.drawable.icon);</pre>
<p>One other thing about textures is that some hardware requires that the height and width are in the power of 2 (1, 2, 4, 8, 16, 32, 64&#8230;). If you run a texture with a size of 30x30pixels on a hardware that don’t support it you will just get a white square (unless you change the default color).</p>
<h3>Generating a texture</h3>
<p>After we have loaded the bitmap we need to tell OpenGL to actually create the texture.</p>
<p>First thing we need to do is to let OpenGL generate some texture id&#8217;s that we will use as handles to the textures later on. In this example we will only have one texture.</p>
<pre class="brush: java; title: ; notranslate">// Create an int array with the number of textures we want,
// in this case 1.
int[] textures = new int[1];
// Tell OpenGL to generate textures.
gl.glGenTextures(1, textures, 0);</pre>
<p>With the same parameters you can delete the textures:</p>
<pre class="brush: java; title: ; notranslate">// Delete a texture.
gl.glDeleteTextures(1, textures, 0)</pre>
<p>Now when the texture id&#8217;s are generated we need to just like everything else tell OpenGL what to work with. With textures we use the command glBindTexture:</p>
<pre class="brush: java; title: ; notranslate">gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);</pre>
<p>From this point all commands we call on regarding textures will be applied on to your texture with the generated id.</p>
<pre class="brush: java; title: ; notranslate">glTexParameter</pre>
<p>There is a couple of parameters we need to set on the texture, the first one is to tell OpenGL what to do if the texture need to be shrunk or magnified to match the rendered image.<br />
If the texture is smaller it needs to be magnified that is done with the magnification function:</p>
<pre class="brush: java; title: ; notranslate">// Scale up if the texture if smaller.
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
                   GL10.GL_TEXTURE_MAG_FILTER,
                   GL10.GL_LINEAR);</pre>
<p>And how to scale if the texture needs to be scaled down using the minification function.</p>
<pre class="brush: java; title: ; notranslate">// scale linearly when image smalled than texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
                   GL10.GL_TEXTURE_MIN_FILTER,
                   GL10.GL_LINEAR);</pre>
<p>You need to pass an argument to these functions. I&#8217;m only going to show you two of them the rest you can investigate your self</p>
<p>If you want a crisp and clean rendering like this image you need to use the GL10.GL_NEAREST parameter.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/gl_nearest.png"><img class="aligncenter size-medium wp-image-534" title="gl_nearest" src="http://androidwizard.net/wp-content/uploads/2011/01/gl_nearest-300x300.png" alt="" width="300" height="300" /></a></p>
<p>If you rather want a blurred image you should use the GL10.GL_LINEAR parameter.<br />
<a href="http://androidwizard.net/wp-content/uploads/2011/01/gl_linear.png"><img class="aligncenter size-medium wp-image-535" title="gl_linear" src="http://androidwizard.net/wp-content/uploads/2011/01/gl_linear-300x300.png" alt="" width="300" height="300" /></a></p>
<h3>UV Mapping</h3>
<p>We will also need to tell OpenGL how to map this image onto the mesh this is done in two steps, fist we need to assign UV coordinates</p>
<p>UV mapping is the way we map the pixels on the bitmap to the vertices in our mesh. The UV coordinates are 0,0 in the upper left and 1,1 is the bottom right, like the left image below. The right image below illustrates how our plane is built. To get the texture mapped correctly we need to map the lower left part of the texture (0,1) to the lower left vertex (0) in our plane and we need to map the the bottom right (1,1) in the texture to the bottom right (1) to the bottom right in our plane and&#8230; you get the idea.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/blog_uv.png"><img class="aligncenter size-medium wp-image-536" title="blog_uv" src="http://androidwizard.net/wp-content/uploads/2011/01/blog_uv-300x156.png" alt="" width="300" height="156" /></a></p>
<p>We put this mapping into a float array like this:</p>
<pre class="brush: java; title: ; notranslate">float textureCoordinates[] = {0.0f, 1.0f,
                              1.0f, 1.0f,
                              0.0f, 0.0f,
                              1.0f, 0.0f };</pre>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/blog_uv2.jpg"><img class="aligncenter size-medium wp-image-537" title="blog_uv2" src="http://androidwizard.net/wp-content/uploads/2011/01/blog_uv2-300x156.jpg" alt="" width="300" height="156" /></a></p>
<p>If we instead used 0.5 instead of 1.0 like this:</p>
<pre class="brush: java; title: ; notranslate">float textureCoordinates[] = {0.0f, 0.5f,
                              0.5f, 0.5f,
                              0.0f, 0.0f,
                              0.5f, 0.0f };</pre>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/blog_uv3.jpg"><img class="aligncenter size-medium wp-image-538" title="blog_uv3" src="http://androidwizard.net/wp-content/uploads/2011/01/blog_uv3-300x156.jpg" alt="" width="300" height="156" /></a></p>
<p>The texture will be mapped so the plane will have the upper left part of it.<br />
Back to the glTexParameterf, if we go the other way and uses values higher then 1.0 like this:</p>
<pre class="brush: java; title: ; notranslate">float textureCoordinates[] = {0.0f, 2.0f,
                              2.0f, 2.0f,
                              0.0f, 0.0f,
                              2.0f, 0.0f };</pre>
<p>We actually tell OpenGL to use part of the texture that does not exist so we need to tell OpenGL what to do with the part that does not exist.</p>
<p>We use the glTexParameterf function to tell OpenGL what to do with the texture. By default OpenGL uses something called GL_REPEAT.</p>
<p><strong>GL_REPEAT</strong> means that OpenGL should repeat the texture beyond 1.0.<br />
<strong>GL_CLAMP_TO_EDGE</strong> means that OpenGL only will draw the image once and after that just repeat the last pixel line the rest of the image.</p>
<p>Since we are working with a 2D texture so we need to tell OpenGL what to do in two directions: GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T.</p>
<p>Below you see a chart with the 4 combinations of GL_REPEAT and GL_CLAMP_TO_EDGE.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/GL_REPEAT_GL_REPEAT.png"><img class="size-medium wp-image-539 alignnone" title="GL_REPEAT_GL_REPEAT" src="http://androidwizard.net/wp-content/uploads/2011/01/GL_REPEAT_GL_REPEAT-300x300.png" alt="" width="90" height="90" /></a><a href="http://androidwizard.net/wp-content/uploads/2011/01/GL_REPEAT_GL_CLAMP_TO_EDGE.png"><img class="alignright size-medium wp-image-540" title="GL_REPEAT_GL_CLAMP_TO_EDGE" src="http://androidwizard.net/wp-content/uploads/2011/01/GL_REPEAT_GL_CLAMP_TO_EDGE-300x300.png" alt="" width="90" height="90" /></div>
<div><a href="http://androidwizard.net/wp-content/uploads/2011/01/GL_CLAMP_TO_EDGE_GL_CLAMP_TO_EDGE.png"><img class="alignright size-medium wp-image-542" title="GL_CLAMP_TO_EDGE_GL_CLAMP_TO_EDGE" src="http://androidwizard.net/wp-content/uploads/2011/01/GL_CLAMP_TO_EDGE_GL_CLAMP_TO_EDGE-300x300.png" alt="" width="90" height="90" /></a></div>
<div><a href="http://androidwizard.net/wp-content/uploads/2011/01/GL_CLAMP_TO_EDGE_GL_REPEAT.png"><img class="size-medium wp-image-541 alignnone" title="GL_CLAMP_TO_EDGE_GL_REPEAT" src="http://androidwizard.net/wp-content/uploads/2011/01/GL_CLAMP_TO_EDGE_GL_REPEAT-300x300.png" alt="" width="90" height="90" /></a></div>
<p>This is how we use the glTexParameterf function:</p>
<div style="clear:both;"></div>
<pre class="brush: java; title: ; notranslate">gl.glTexParameterf(GL10.GL_TEXTURE_2D,
                   GL10.GL_TEXTURE_WRAP_S,
                   GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
                   GL10.GL_TEXTURE_WRAP_T,
                   GL10.GL_REPEAT);</pre>
<p>The last thing we need to do is to bind the bitmap we loaded to the texture id we created.</p>
<pre class="brush: java; title: ; notranslate">GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);</pre>
<h3>Using the texture</h3>
<p>To be able to use the texture we need just like with everything else create a byte buffer with the UV coordinates:</p>
<pre class="brush: java; title: ; notranslate">FloatBuffer byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
textureBuffer = byteBuf.asFloatBuffer();
textureBuffer.put(textureCoordinates);
textureBuffer.position(0);</pre>
<h3>Rendering</h3>
<pre class="brush: java; title: ; notranslate">// Telling OpenGL to enable textures.
gl.glEnable(GL10.GL_TEXTURE_2D);
// Tell OpenGL where our texture is located.
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
// Tell OpenGL to enable the use of UV coordinates.
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Telling OpenGL where our UV coordinates are.
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

// ... here goes the rendering of the mesh ...

// Disable the use of UV coordinates.
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Disable the use of textures.
gl.glDisable(GL10.GL_TEXTURE_2D);</pre>
<h3>Putting it all together</h3>
<p>I&#8217;m using a modified version of the code from the previous tutorial. The different is mostly that I renamed some variables and functions and added more comments and all code is now under Apache License. To make the code easier to understand I removed the previous plane and added a new easier one called SimplePlane.</p>
<h3>Updating the Mesh class</h3>
<p>The first thing we need to do is to update the Mesh class (se.jayway.opengl.tutorial.mesh.Mesh). We need to add the functionality to load and render a texture.</p>
<p>We need to be able to set and store the UV coordinates.</p>
<pre class="brush: java; title: ; notranslate">// Our UV texture buffer.
private FloatBuffer mTextureBuffer;

/**
 * Set the texture coordinates.
 *
 * @param textureCoords
 */
protected void setTextureCoordinates(float[] textureCoords) {
	// float is 4 bytes, therefore we multiply the number if
        // vertices with 4.
	ByteBuffer byteBuf = ByteBuffer.allocateDirect(
                                           textureCoords.length * 4);
	byteBuf.order(ByteOrder.nativeOrder());
	mTextureBuffer = byteBuf.asFloatBuffer();
	mTextureBuffer.put(textureCoords);
	mTextureBuffer.position(0);
}</pre>
<p>We also need to add functions to set the bitmap and create the texture.</p>
<pre class="brush: java; title: ; notranslate">// Our texture id.
private int mTextureId = -1;

// The bitmap we want to load as a texture.
private Bitmap mBitmap;

/**
 * Set the bitmap to load into a texture.
 *
 * @param bitmap
 */
public void loadBitmap(Bitmap bitmap) {
	this.mBitmap = bitmap;
	mShouldLoadTexture = true;
}

/**
 * Loads the texture.
 *
 * @param gl
 */
private void loadGLTexture(GL10 gl) {
	// Generate one texture pointer...
	int[] textures = new int[1];
	gl.glGenTextures(1, textures, 0);
	mTextureId = textures[0];

	// ...and bind it to our array
	gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);

	// Create Nearest Filtered Texture
	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
			GL10.GL_LINEAR);
	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
			GL10.GL_LINEAR);

	// Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
			GL10.GL_CLAMP_TO_EDGE);
	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
			GL10.GL_REPEAT);

	// Use the Android GLUtils to specify a two-dimensional texture image
	// from our bitmap
	GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
}</pre>
<p>And finally we need to add the call to the texture loading and to actually tell OpenGL to render with this texture. I removed some code so the page would not be so long but you will find the code complete in the attached zip file.</p>
<pre class="brush: java; title: ; notranslate">// Indicates if we need to load the texture.
private boolean mShouldLoadTexture = false;

/**
 * Render the mesh.
 *
 * @param gl
 *            the OpenGL context to render to.
 */
public void draw(GL10 gl) {
	...

	// Smooth color
	if (mColorBuffer != null) {
		// Enable the color array buffer to be used during rendering.
		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
		gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer);
	}

	if (mShouldLoadTexture) {
		loadGLTexture(gl);
		mShouldLoadTexture = false;
	}
	if (mTextureId != -1 &amp;&amp; mTextureBuffer != null) {
		gl.glEnable(GL10.GL_TEXTURE_2D);
		// Enable the texture state
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

		// Point to our buffers
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
	}

	gl.glTranslatef(x, y, z);

	...

	// Point out the where the color buffer is.
	gl.glDrawElements(GL10.GL_TRIANGLES, mNumOfIndices,
			GL10.GL_UNSIGNED_SHORT, mIndicesBuffer);

	...

	if (mTextureId != -1 &amp;&amp; mTextureBuffer != null) {
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
	}

	...

}</pre>
<h3>Creating the SimplePlane class</h3>
<p>We also need to create the SimplePlane.java. The code is pretty simple and self-explaining if you have read my previous tutorials. The new element is the textureCoordinates variable.</p>
<pre class="brush: java; title: ; notranslate">package se.jayway.opengl.tutorial.mesh;

/**
 * SimplePlane is a setup class for Mesh that creates a plane mesh.
 *
 * @author Per-Erik Bergman (per-erik.bergman@jayway.com)
 *
 */
public class SimplePlane extends Mesh {
	/**
	 * Create a plane with a default with and height of 1 unit.
	 */
	public SimplePlane() {
		this(1, 1);
	}

	/**
	 * Create a plane.
	 *
	 * @param width
	 *            the width of the plane.
	 * @param height
	 *            the height of the plane.
	 */
	public SimplePlane(float width, float height) {
		// Mapping coordinates for the vertices
		float textureCoordinates[] = { 0.0f, 2.0f, //
				2.0f, 2.0f, //
				0.0f, 0.0f, //
				2.0f, 0.0f, //
		};

		short[] indices = new short[] { 0, 1, 2, 1, 3, 2 };

                float[] vertices = new float[] { -0.5f, -0.5f, 0.0f,
                                                  0.5f, -0.5f, 0.0f,
                                                 -0.5f,  0.5f, 0.0f,
                                                  0.5f, 0.5f, 0.0f };

		setIndices(indices);
		setVertices(vertices);
		setTextureCoordinates(textureCoordinates);</pre>
<p>You can download the source for this tutorial here: <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/12/Tutorial_Part_VI.zip">Tutorial_Part_VI</a></p>
]]></content:encoded>
			<wfw:commentRss>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-vi-%e2%80%93-textures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part V – More on Meshes</title>
		<link>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-v-%e2%80%93-more-on-meshes/</link>
		<comments>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-v-%e2%80%93-more-on-meshes/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 09:15:40 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[meshes]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=524</guid>
		<description><![CDATA[I have a feeling that some of you have tried my tutorials and then thought &#8220;This is a 3D tutorial, but why is everything in 2D?&#8221;. 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 &#8220;This is a 3D tutorial, but why is everything in 2D?&#8221;. 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>
<h3>Design</h3>
<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://androidwizard.net/wp-content/uploads/2011/01/composite.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/composite-300x109.png" alt="" title="composite" width="300" height="109" class="aligncenter size-medium wp-image-525" /></a></p>
<p>Let&#8217;s start making out pattern.</p>
<h3>Mesh</h3>
<p>It&#8217;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="brush: java; title: ; notranslate">package se.jayway.opengl.tutorial.mesh;
public class Mesh {

}</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="brush: java; title: ; notranslate"> // Our vertex buffer.
    private FloatBuffer verticesBuffer = null;

    // Our index buffer.
    private ShortBuffer indicesBuffer = null;

    // The number of indices.
    private int numOfIndices = -1;

    // Flat Color
    private float[] rgba = new float[]{1.0f, 1.0f, 1.0f, 1.0f};

    // Smooth Colors
    private FloatBuffer colorBuffer = null;

    public void draw(GL10 gl) {
        // Counter-clockwise winding.
	gl.glFrontFace(GL10.GL_CCW);
	// Enable face culling.
	gl.glEnable(GL10.GL_CULL_FACE);
	// What faces to remove with the face culling.
	gl.glCullFace(GL10.GL_BACK);
	// Enabled the vertices buffer for writing and to be used during
	// rendering.
	gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
	// Specifies the location and data format of an array of vertex
	// coordinates to use when rendering.
	gl.glVertexPointer(3, GL10.GL_FLOAT, 0, verticesBuffer);
        // Set flat color
        gl.glColor4f(rgba[0], rgba[1], rgba[2], rgba[3]);
        // Smooth color
        if ( colorBuffer != null ) {
            // Enable the color array buffer to be used during rendering.
            gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
            // Point out the where the color buffer is.
            gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);
        }
	gl.glDrawElements(GL10.GL_TRIANGLES, numOfIndices,
		GL10.GL_UNSIGNED_SHORT, indicesBuffer);
	// Disable the vertices buffer.
	gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
	// Disable face culling.
	gl.glDisable(GL10.GL_CULL_FACE);
    }</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="brush: java; title: ; notranslate"> protected void setVertices(float[] vertices) {
	// 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());
	verticesBuffer = vbb.asFloatBuffer();
	verticesBuffer.put(vertices);
	verticesBuffer.position(0);
    }

    protected void setIndices(short[] indices) {
	// short is 2 bytes, therefore we multiply the number if
	// vertices with 2.
	ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
	ibb.order(ByteOrder.nativeOrder());
	indicesBuffer = ibb.asShortBuffer();
	indicesBuffer.put(indices);
	indicesBuffer.position(0);
	numOfIndices = indices.length;
    }

    protected void setColor(float red, float green, float blue, float alpha) {
        // Setting the flat color.
        rgba[0] = red;
        rgba[1] = green;
        rgba[2] = blue;
        rgba[3] = alpha;
    }

    protected void setColors(float[] colors) {
	// float has 4 bytes.
	ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
	cbb.order(ByteOrder.nativeOrder());
	colorBuffer = cbb.asFloatBuffer();
	colorBuffer.put(colors);
	colorBuffer.position(0);</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="brush: java; title: ; notranslate"> // Translate params.
    public float x = 0;
    public float y = 0;
    public float z = 0;

    // Rotate params.
    public float rx = 0;
    public float ry = 0;
    public float rz = 0;</pre>
<p>And use them in the draw function add this lines just before the gl.glDrawElements call.</p>
<pre class="brush: java; title: ; notranslate">gl.glTranslatef(x, y, z);
    gl.glRotatef(rx, 1, 0, 0);
    gl.glRotatef(ry, 0, 1, 0);
    gl.glRotatef(rz, 0, 0, 1);</pre>
<h3>Plane</h3>
<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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/terminology_1.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/terminology_1.png" alt="" title="terminology_1" width="260" height="252" class="alignleft size-full wp-image-526" /></a></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 />
<a href="http://androidwizard.net/wp-content/uploads/2011/01/terminology_2.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/terminology_2.png" alt="" title="terminology_2" width="260" height="252" class="alignleft size-full wp-image-527" /></a></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&#8217;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>
<div style="clear:both"></div>
<p>For an easy and quick setup:</p>
<pre class="brush: java; title: ; notranslate">// Gives you a plane that is 1 unit wide and 1 unit high with just one segment over width and height.
public Plane()</pre>
<p>An easy one just to change the size:</p>
<pre class="brush: java; title: ; notranslate"> // Let you decide the size of the plane but still only one segment.
public Plane(float width, float height)</pre>
<p>And finally one for setting up the plane with different segments:</p>
<pre class="brush: java; title: ; notranslate">// For alla your settings.
public Plane(float width, float height, int widthSegments, int heightSegments)</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:</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/plane-300x133.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/plane-300x133.png" alt="" title="plane-300x133" width="300" height="133" class="alignleft size-full wp-image-528" /></a></p>
<div style="clear:both"></div>
<p>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="brush: java; title: ; notranslate">package se.jayway.opengl.tutorial.mesh;

public class Plane extends Mesh {

    public Plane() {
	this(1, 1, 1, 1);
    }

    public Plane(float width, float height) {
	this(width, height, 1, 1);
    }

    public Plane(float width, float height, int widthSegments,
		int heightSegments) {
	float[] vertices = new float[(widthSegments + 1) * (heightSegments + 1)
			* 3];
	short[] indices = new short[(widthSegments + 1) * (heightSegments + 1)
			* 6];

	float xOffset = width / -2;
	float yOffset = height / -2;
	float xWidth = width / (widthSegments);
	float yHeight = height / (heightSegments);
	int currentVertex = 0;
	int currentIndex = 0;
	short w = (short) (widthSegments + 1);
	for (int y = 0; y &lt; heightSegments + 1; y++) {
            for (int x = 0; x &lt; widthSegments + 1; x++) {
	        vertices[currentVertex] = xOffset + x * xWidth;
		vertices[currentVertex + 1] = yOffset + y * yHeight;
		vertices[currentVertex + 2] = 0;
		currentVertex += 3;

		int n = y * (widthSegments + 1) + x;

		if (y &lt; heightSegments &amp;&amp; x &lt; widthSegments) {
		    // Face one
		    indices[currentIndex] = (short) n;
		    indices[currentIndex + 1] = (short) (n + 1);
		    indices[currentIndex + 2] = (short) (n + w);
		    // Face two
		    indices[currentIndex + 3] = (short) (n + 1);
		    indices[currentIndex + 4] = (short) (n + 1 + w);
		    indices[currentIndex + 5] = (short) (n + 1 + w - 1);

		    currentIndex += 6;
		}
	    }
	}

	setIndices(indices);
	setVertices(vertices);
    }
}</pre>
<h3>Cube</h3>
<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="brush: java; title: ; notranslate">public Cube(float width, float height, float depth)</pre>
<p>And since I&#8217;m not doing this with any segments the constructor will be quite easy.</p>
<pre class="brush: java; title: ; notranslate">package se.jayway.opengl.tutorial.mesh;

public class Cube extends Mesh {
    public Cube(float width, float height, float depth) {
        width  /= 2;
        height /= 2;
        depth  /= 2;

        float vertices[] = { -width, -height, -depth, // 0
                              width, -height, -depth, // 1
                              width,  height, -depth, // 2
                             -width,  height, -depth, // 3
                             -width, -height,  depth, // 4
                              width, -height,  depth, // 5
                              width,  height,  depth, // 6
                             -width,  height,  depth, // 7
        };

        short indices[] = { 0, 4, 5,
                            0, 5, 1,
                            1, 5, 6,
                            1, 6, 2,
                            2, 6, 7,
                            2, 7, 3,
                            3, 7, 4,
                            3, 4, 0,
                            4, 7, 6,
                            4, 6, 5,
                            3, 0, 1,
                            3, 1, 2, };

        setIndices(indices);
        setVertices(vertices);
    }
}</pre>
<p>If you like to make it with segments the constructor could look like this:</p>
<pre class="brush: java; title: ; notranslate">public Cube(float width, float height, float depth,
                 int widthSegments, int heightSegments, int depthSegments)</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&#8230;</p>
<pre class="brush: java; title: ; notranslate">public OpenGLRenderer() {
    // Initialize our cube.
    cube = new Cube(1, 1, 1);
    cube.rx = 45;
    cube.ry = 45;
}</pre>
<p>&#8230; and render it.</p>
<pre class="brush: java; title: ; notranslate">public void onDrawFrame(GL10 gl) {
    ...
    // Draw our cube.
    cube.draw(gl);
}</pre>
<h3>Group</h3>
<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&#8217;s children. You can see the implementation of a simple group here:</p>
<pre class="brush: java; title: ; notranslate">package se.jayway.opengl.tutorial.mesh;

import java.util.Vector;

import javax.microedition.khronos.opengles.GL10;

public class Group extends Mesh {
    private Vector&lt;Mesh&gt; children = new Vector&lt;Mesh&gt;();

    @Override
    public void draw(GL10 gl) {
        int size = children.size();
        for( int i = 0; i &lt; size; i++)
            children.get(i).draw(gl);
    }

    public void add(int location, Mesh object) {
        children.add(location, object);
    }

    public boolean add(Mesh object) {
        return children.add(object);
    }

    public void clear() {
        children.clear();
    }

    public Mesh get(int location) {
        return children.get(location);
    }

    public Mesh remove(int location) {
        return children.remove(location);
    }

    public boolean remove(Object object) {
        return children.remove(object);
    }

    public int size() {
        return children.size();
    }
}</pre>
<p>Make the renderer work with a group as a root node and add your cube to it.</p>
<pre class="brush: java; title: ; notranslate">Group group = new Group();
Cube cube = new Cube(1, 1, 1);
cube.rx = 45;
cube.ry = 45;
group.add(cube);
root = group;</pre>
<p>And draw our scene:</p>
<pre class="brush: java; title: ; notranslate">public void onDrawFrame(GL10 gl) {
    ...
    // Draw our scene.
    root.draw(gl);
}</pre>
<h3>Suggestions</h3>
<p>It&#8217;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&#8217;t have any meshes from the graphic people when you start coding so it&#8217;s really good to have some meshes to work with as place holders. I&#8217;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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/cpc-300x109.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/cpc-300x109.png" alt="" title="cpc-300x109" width="300" height="109" class="alignleft size-full wp-image-529" /></a></p>
<div style="clear:both"></div>
<pre class="brush: java; title: ; notranslate">public Cone(float baseRadius, float topRadius, float height, int numberOfSides)</pre>
<h3>Pyramid</h3>
<pre class="brush: java; title: ; notranslate">public class Pyramid extends Cone {
    public Pyramid(float baseRadius, float height)  {
        super(baseRadius, 0, height, 4);
    }
}</pre>
<h3>Cylinder</h3>
<pre class="brush: java; title: ; notranslate">public class Cylinder extends Cone {
    public Cylinder(float radius, float height)  {
        super(radius, radius, height, 16);
    }
}</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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/triangle_seg-300x154.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/triangle_seg-300x154.png" alt="" title="triangle_seg-300x154" width="300" height="154" class="alignleft size-full wp-image-530" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-v-%e2%80%93-more-on-meshes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part IV – Adding colors</title>
		<link>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-iv-%e2%80%93-adding-colors/</link>
		<comments>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-iv-%e2%80%93-adding-colors/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 07:23:39 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[adding colors]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=512</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.]]></description>
			<content:encoded><![CDATA[<h3>Adding color</h3>
<p>3D models with no colors are pretty boring so let&#8217;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: RGB color model &#8211; Wikipedia, the free encyclopedia</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><a href="http://androidwizard.net/wp-content/uploads/2011/01/FlatColoring.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/FlatColoring.png" alt="" title="FlatColoring" width="90" height="90" class="alignright size-full wp-image-514" /></a><br />
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 class="brush: java; title: ; notranslate">public abstract void glColor4f(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&#8217;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 class="brush: java; title: ; notranslate">gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); // 0x8080FFFF</pre>
<p>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.</p>
<p>It should now look like this:</p>
<pre class="brush: java; title: ; notranslate">public void draw(GL10 gl) {
        gl.glColor4f(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 class="brush: java; title: ; notranslate">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>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.</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 class="brush: java; title: ; notranslate">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>Notice that with flat coloring you don&#8217;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.</p>
<h3>Smooth Coloring</h3>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/SmoothColoring.png"><img src="http://androidwizard.net/wp-content/uploads/2011/01/SmoothColoring.png" alt="" title="SmoothColoring" width="90" height="90" class="alignright size-full wp-image-519" /></a><br />
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&#8217;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 class="brush: java; title: ; notranslate">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 vertices 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 class="brush: java; title: ; notranslate">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&#8217;t forget to add colorBuffer as a variable to the class as well.</p>
<pre class="brush: java; title: ; notranslate"> // Our color buffer.
	private FloatBuffer colorBuffer;</pre>
<p>We also need to enable the color buffer and tell openGL where it is.</p>
<pre class="brush: java; title: ; notranslate">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>Don&#8217;t forget to disable the use of the color array. If you don&#8217;t disable the color array both squares will be smooth colored. Try it.</p>
<p>Let&#8217;s use this new smooth square as well. Start by adding it to your renderer.</p>
<pre class="brush: java; title: ; notranslate">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&#8217;t collide.</p>
<pre class="brush: java; title: ; notranslate">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>
]]></content:encoded>
			<wfw:commentRss>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-iv-%e2%80%93-adding-colors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part III – Transformations</title>
		<link>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-iii-%e2%80%93-transformations/</link>
		<comments>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-iii-%e2%80%93-transformations/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 07:02:51 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[android]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=486</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.]]></description>
			<content:encoded><![CDATA[<h3>Coordinate System</h3>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/3DCoord.png"><img class="alignright size-full wp-image-490" title="3DCoord" src="http://androidwizard.net/wp-content/uploads/2011/01/3DCoord.png" alt="" width="230" height="234" /></a><br />
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&#8217;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. </p>
<h3>Translate</h3>
<pre class="brush: java; title: ; notranslate">public abstract void glTranslatef (float x, float y, float z) //OpenGL docs.</pre>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/2DCoord1.png"><img class="alignright size-full wp-image-491" title="2DCoord1" src="http://androidwizard.net/wp-content/uploads/2011/01/2DCoord1.png" alt="" width="192" height="193" /></a></p>
<p>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. 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 class="brush: java; title: ; notranslate">// Translates 4 units into the screen.
gl.glTranslatef(0, 0, -4); OpenGL docs.</pre>
<p>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&#8217;t so important but when we do a rotation it&#8217;s really important.</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<br />
<a href="http://androidwizard.net/wp-content/uploads/2011/01/axis_a.jpg"><img class="aligncenter size-full wp-image-493" title="axis_a" src="http://androidwizard.net/wp-content/uploads/2011/01/axis_a.jpg" alt="" width="300" height="236" /></a></p>
<h3>Rotate</h3>
<pre class="brush: java; title: ; notranslate">public abstract void glRotatef(float angle, float x, float y, float z)//OpenGL docs.</pre>
<p>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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/Rotate.png"><img class="alignright size-full wp-image-494" title="Rotate" src="http://androidwizard.net/wp-content/uploads/2011/01/Rotate.png" alt="" width="288" height="288" /></a></p>
<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 class="brush: java; title: ; notranslate"> 1=&quot;1.0f,&quot; 2=&quot;0.0f,&quot; 3=&quot;0.0f);&quot; 4=&quot;//&quot; 5=&quot;OpenGL&quot; 6=&quot;docs.&quot; 7=&quot;gl.glRotatef(90f,&quot; 8=&quot;0.0f,&quot; 9=&quot;1.0f,&quot; 10=&quot;0.0f);&quot; 11=&quot;//&quot; 12=&quot;OpenGL&quot; 13=&quot;docs.&quot; 14=&quot;gl.glRotatef(90f,&quot; 15=&quot;0.0f,&quot; 16=&quot;0.0f,&quot; 17=&quot;1.0f);&quot; 18=&quot;//&quot; 19=&quot;OpenGL&quot; 20=&quot;docs.&quot; language=&quot;[gl.glRotatef(90f,&quot;</pre>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/PositiveRotation.png"><img class="aligncenter size-medium wp-image-495" title="PositiveRotation" src="http://androidwizard.net/wp-content/uploads/2011/01/PositiveRotation-300x80.png" alt="" width="300" height="80" /></a></p>
<p>And want to restore the mesh to it's original position you can't just negate the angle like this:</p>
<pre class="brush: java; title: ; notranslate">gl.glRotatef(90f, -1.0f, 0.0f, 0.0f); // OpenGL docs.
gl.glRotatef(90f, 0.0f, -1.0f, 0.0f); // OpenGL docs.
gl.glRotatef(90f, 0.0f, 0.0f, -1.0f); // OpenGL docs.</pre>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/PositiveRotation1.png"><img class="aligncenter size-medium wp-image-496" title="PositiveRotation" src="http://androidwizard.net/wp-content/uploads/2011/01/PositiveRotation1-300x80.png" alt="" width="300" height="80" /></a></p>
<p>You have to revert the order of the rotations as well like this:</p>
<pre class="brush: java; title: ; notranslate">gl.glRotatef(90f, 0.0f, 0.0f, -1.0f); // OpenGL docs.
gl.glRotatef(90f, 0.0f, -1.0f, 0.0f); // OpenGL docs.
gl.glRotatef(90f, -1.0f, 0.0f, 0.0f); // OpenGL docs.</pre>
<p>The order of several rotations is important.</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><a href="http://androidwizard.net/wp-content/uploads/2011/01/rotation_a.jpg"><img class="aligncenter size-full wp-image-497" title="rotation_a" src="http://androidwizard.net/wp-content/uploads/2011/01/rotation_a.jpg" alt="" width="300" height="200" /></a></p>
<h3>Translate &amp; Rotate</h3>
<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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/TranslateRotate.png"><img class="aligncenter size-medium wp-image-498" title="TranslateRotate" src="http://androidwizard.net/wp-content/uploads/2011/01/TranslateRotate-300x89.png" alt="" width="300" height="89" /></a></p>
<p>If you first rotate and the move the mesh it will be moved accordingly to its own rotated coordinate system.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/RotateTranslate.png"><img class="aligncenter size-medium wp-image-499" title="RotateTranslate" src="http://androidwizard.net/wp-content/uploads/2011/01/RotateTranslate-300x89.png" alt="" width="300" height="89" /></a></p>
<h3>Scale</h3>
<pre class="brush: java; title: ; notranslate">public abstract void glScalef (float x, float y, float z) // OpenGL docs.</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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/Scale.png"><img class="aligncenter size-medium wp-image-500" title="Scale" src="http://androidwizard.net/wp-content/uploads/2011/01/Scale-300x138.png" alt="" width="300" height="138" /></a></p>
<h3>Translate &amp; Scale</h3>
<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 class="brush: java; title: ; notranslate">gl.glTranslatef(2, 0, 0); // OpenGL docs.
gl.glScalef(0.5f, 0.5f, 0.5f); // OpenGL docs.</pre>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/TranslateScale.png"><img class="aligncenter size-medium wp-image-501" title="TranslateScale" src="http://androidwizard.net/wp-content/uploads/2011/01/TranslateScale-300x89.png" alt="" width="300" height="89" /></a></p>
<p>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 class="brush: java; title: ; notranslate">gl.glScalef(0.5f, 0.5f, 0.5f); // OpenGL docs.
gl.glTranslatef(2, 0, 0); // OpenGL docs.</pre>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/ScaleTranslate.png"><img class="aligncenter size-medium wp-image-502" title="ScaleTranslate" src="http://androidwizard.net/wp-content/uploads/2011/01/ScaleTranslate-300x89.png" alt="" width="300" height="89" /></a></p>
<h3>Load Identity, push and pop matrix</h3>
<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 class="brush: java; title: ; notranslate">
glLoadIdentity replaces the current matrix with the identity matrix. It is the same as calling glLoadMatrix with the identity matrix:

11 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1</pre>
<p>There are situations where you don&#8217;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 class="brush: java; title: ; notranslate">public abstract void glPushMatrix() // OpenGL docs.</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 class="brush: java; title: ; notranslate">public abstract void glPopMatrix() // OpenGL docs.</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>
<h3>Putting it all togetter</h3>
<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&#8217;s own center.</p>
<pre class="brush: java; title: ; notranslate">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&#8217;t forget to add angel as a variable as well.</p>
<pre class="brush: java; title: ; notranslate">public class OpenGLRenderer implements Renderer {
private Square square;
private float angle; // Don't forget to add this.</pre>
]]></content:encoded>
			<wfw:commentRss>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-iii-%e2%80%93-transformations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenGL ES Tutorial for Android – Part II – Building a polygon</title>
		<link>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-ii-%e2%80%93-building-a-polygon/</link>
		<comments>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-ii-%e2%80%93-building-a-polygon/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 04:43:29 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[3d games]]></category>
		<category><![CDATA[opengl]]></category>
		<category><![CDATA[polygon]]></category>

		<guid isPermaLink="false">http://androidwizard.net/?p=448</guid>
		<description><![CDATA[Previous tutorial was all about setting up the GLSurfaceView. Be sure to read it because it's a really important one to be able to continue.]]></description>
			<content:encoded><![CDATA[<h3>Building a polygon</h3>
<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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/vertex.png"><img class="aligncenter size-medium wp-image-451" title="vertex" src="http://androidwizard.net/wp-content/uploads/2011/01/vertex-300x175.png" alt="" width="300" height="175" /></a></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.</p>
<div style="float: right;"><a href="http://androidwizard.net/wp-content/uploads/2011/01/poly11.png"><img class="alignright size-medium wp-image-453" title="poly1" src="http://androidwizard.net/wp-content/uploads/2011/01/poly11-295x300.png" alt="" width="295" height="300" /></a></div>
<div style="clear:both"></div>
<pre class="brush: java; title: ; notranslate">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>Don&#8217;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.</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 class="brush: java; title: ; notranslate">// Enabled the vertex buffer for writing and to be used during rendering.
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);// OpenGL docs.
// Specifies the location and data format of an array of vertex
// coordinates to use when rendering.
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer); // OpenGL docs.</pre>
<p>When you are done with the buffer don&#8217;t forget to disable it.</p>
<pre class="brush: java; title: ; notranslate">// Disable the vertices buffer.
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);// OpenGL docs.</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&#8217;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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/edge.png"><img class="aligncenter size-medium wp-image-454" title="edge" src="http://androidwizard.net/wp-content/uploads/2011/01/edge-300x175.png" alt="" width="300" height="175" /></a></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 />
<a href="http://androidwizard.net/wp-content/uploads/2011/01/face.png"><img class="aligncenter size-medium wp-image-455" title="face" src="http://androidwizard.net/wp-content/uploads/2011/01/face-300x175.png" alt="" width="300" height="175" /></a></p>
<p>The order does matter.<br />
When winding up the faces it&#8217;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&#8217;t want to draw both sides so we turn off the back face. So it&#8217;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 class="brush: java; title: ; notranslate"> gl.glFrontFace(GL10.GL_CCW); // OpenGL docs</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 class="brush: java; title: ; notranslate"> gl.glEnable(GL10.GL_CULL_FACE); // OpenGL docs</pre>
<p>It&#8217;s of cource possible to change what face side should be drawn or not.</p>
<pre class="brush: java; title: ; notranslate">gl.glCullFace(GL10.GL_BACK); // OpenGL docs</pre>
<h3>Polygon</h3>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/polygon.png"><img class="aligncenter size-medium wp-image-456" title="polygon" src="http://androidwizard.net/wp-content/uploads/2011/01/polygon-300x175.png" alt="" width="300" height="175" /></a></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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/poly2.png"><img class="alignright size-medium wp-image-457" title="poly2" src="http://androidwizard.net/wp-content/uploads/2011/01/poly2-295x300.png" alt="" width="295" height="300" /></a></p>
<div style="clear:both">
<pre class="brush: java; title: ; notranslate">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 class="brush: java; title: ; notranslate">// 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>
</div>
<p>Don&#8217;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.</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 class="brush: java; title: ; notranslate">public abstract void glDrawArrays(int mode, int first, int count) // OpenGL docs</pre>
<p>glDrawArrays draws the vertices in that order they are specified in the construction of our verticesBuffer.</p>
<pre class="brush: java; title: ; notranslate">public abstract void glDrawElements(int mode, int count, int type, // OpenGL docs
                                    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&#8217;m guessing that you figured out that&#8217;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&#8217;ll go through them all.</p>
<div style="text-align: left;">
<h4>What primitives to render</h4>
<h3>GL_POINTS</h3>
<p>Draws individual points on the screen.                                                                                       </p>
<p><img class="size-full wp-image-458 alignnone" title="Gl_points" src="http://androidwizard.net/wp-content/uploads/2011/01/Gl_points.jpg" alt="" width="200" height="140" /></p>
<h3>GL_LINE_STRIP</h3>
<p>Series of connected line segments.<a href="http://androidwizard.net/wp-content/uploads/2011/01/Gl_line_strip.jpg"></p>
<div style="clear:both"> <img class="size-full wp-image-459" title="Gl_line_strip" src="http://androidwizard.net/wp-content/uploads/2011/01/Gl_line_strip.jpg" alt="" width="200" height="140" /></a></div>
</div>
<h3>GL_LINE_LOOP</h3>
<p>Same as above, with a segment added between last and first vertices.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/Gl_line_loop.jpg"><img class="alignnone size-full wp-image-460" title="Gl_line_loop" src="http://androidwizard.net/wp-content/uploads/2011/01/Gl_line_loop.jpg" alt="" width="200" height="140" /></a></p>
<h3>GL_LINES</h3>
<p>Pairs of vertices interpreted as individual line segments.<br />
<a href="http://androidwizard.net/wp-content/uploads/2011/01/Gl_lines.jpg"><img class="alignnone size-full wp-image-461" title="Gl_lines" src="http://androidwizard.net/wp-content/uploads/2011/01/Gl_lines.jpg" alt="" width="200" height="140" /></a></p>
<h3>GL_TRIANGLES</h3>
<p>Triples of vertices interpreted as triangles.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/Gl_triangles.jpg"><img class="alignnone size-full wp-image-462" title="Gl_triangles" src="http://androidwizard.net/wp-content/uploads/2011/01/Gl_triangles.jpg" alt="" width="200" height="140" /></a></p>
<h3>GL_TRIANGLE_STRIP</h3>
<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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/Gl_triangle_strip.jpg"><img class="alignnone size-full wp-image-463" title="Gl_triangle_strip" src="http://androidwizard.net/wp-content/uploads/2011/01/Gl_triangle_strip.jpg" alt="" width="200" height="140" /></a></p>
<h3>GL_TRIANGLE_FAN</h3>
<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.</p>
<p><a href="http://androidwizard.net/wp-content/uploads/2011/01/Gl_triangle_fan.jpg"><img class="alignnone size-full wp-image-464" title="Gl_triangle_fan" src="http://androidwizard.net/wp-content/uploads/2011/01/Gl_triangle_fan.jpg" alt="" width="200" height="140" /></a></p>
<p>I think the GL_TRIANGLES is the easiest to use so we go with that one for now.</p>
<h3>Putting it all togetter</h3>
<p>So let&#8217;s putting our square together in a class.</p>
<pre class="brush: java; title: ; notranslate">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.glFrontFace(GL10.GL_CCW); // OpenGL docs
		// Enable face culling.
		gl.glEnable(GL10.GL_CULL_FACE); // OpenGL docs
		// What faces to remove with the face culling.
		gl.glCullFace(GL10.GL_BACK); // OpenGL docs

		// Enabled the vertices buffer for writing and to be used during
		// rendering.
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);// OpenGL docs.
		// Specifies the location and data format of an array of vertex
		// coordinates to use when rendering.
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, // OpenGL docs
                                 vertexBuffer);

		gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,// OpenGL docs
				  GL10.GL_UNSIGNED_SHORT, indexBuffer);

		// Disable the vertices buffer.
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // OpenGL docs
		// Disable face culling.
		gl.glDisable(GL10.GL_CULL_FACE); // OpenGL docs
	}

}</pre>
<p>We have to initialize our square in the OpenGLRenderer class.</p>
<pre class="brush: java; title: ; notranslate">// Initialize our square.
Square square = new Square();</pre>
<p>And in the draw function call on the square to draw.</p>
<pre class="brush: java; title: ; notranslate">public void onDrawFrame(GL10 gl) {
		// Clears the screen and depth buffer.
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | // OpenGL docs.
                           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 class="brush: java; title: ; notranslate">// Translates 4 units into the screen.
gl.glTranslatef(0, 0, -4); // OpenGL docs</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 class="brush: java; title: ; notranslate">
// Replace the current matrix with the identity matrix
gl.glLoadIdentity(); // OpenGL docs</pre>
<p>Now if you run the application you will see the square on a fixed position.</p>
]]></content:encoded>
			<wfw:commentRss>http://androidwizard.net/2011/01/opengl-es-tutorial-for-android-%e2%80%93-part-ii-%e2%80%93-building-a-polygon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

