Monday, 9 December 2013

Using multiple FBOs in OpenGL ES 2

I wrote previously about using FBOs in OpenGL ES 2. However, sometimes rendering to a single framebuffer is not enough. You may want to process the texture yet again before displaying it on the screen. Doing this is as easy as creating a new FBO and rendering to it. The code is almost identical to the previous one, except it uses two framebuffer objects. Here I'm using a blur shader (taken from here if I remember well):

FBO

Saturday, 7 December 2013

Java: How it works (part 1)

Keywords: JVM, classpath, classloader

I always wanted to know how I get from a bunch of .java files (that include a main method somewhere) to a program that does something. For the rest of the discussion, let's assume we are working with the following file:

A simple class

Firstly, all the .java files need to be compiled into .class files in order to be used by the JVM. In other words, the JVM has no idea and doesn't care about Java; it only cares about the instructions in a .class file. This means that, if you know what you're doing, you can even make your own compiler, along with a language that gets compiled to valid .class files. Actually there are already a number of JVM languages.

Now that you compiled your code successfully, you need to run it. java MySimpleClass starts a new JVM that will attempt to run your program by first using what is called a classloader. What the classloader does is try to find and load the contents of .class files in order to translate those contents into Java classes and interfaces. This process is called loading. The next step is called linking and it consists of adding the aforementioned classes and interfaces to the JVM run state. Next is class initialization, which consists of initializing the static members of the class and includes running static initialization blocks. Initialization will be covered more thoroughly in part 2.

Once these steps are done, the JVM is be ready to call main and run your code. :) Note that you may be able to execute code before main through static initialization blocks. Also, a very useful command is javap. It disassembles the contents of a .class file into a readable format, which could help understand at a deeper level what really happens in the JVM. Type
javap -v MySimpleClass.class 
in the terminal and have a look.

In part 2 I am going to look at a more complex example and talk a bit more about initialization and when it occurs. :)

Thursday, 14 November 2013

Framebuffer objects in OpenGL ES 2

Maybe fully understanding framebuffer objects (FBO) is indeed difficult, as it says on the OpenGL page dedicated to the topic. But writing a basic example is quite straightforward. It almost made me bang my head on the desk though, but it was only because of a very silly mistake. Make sure you first check your FloatBuffers & IndexBuffers before worrying about what might have went wrong with your FBO.

I assume you're here because you're looking for a very basic example of how to use FBO. That's exactly what you're going to find.

Although I am far from understanding the topic, here are some basic thoughts that helped me make some initial steps:
1. The default framebuffer is your screen. This is what you use in general.
2. However, in certain situations, you may choose to first draw your stuff to an "imaginary" screen that has its own framebuffer. To set up this imaginary screen, you need to create a FBO.
3. Draw whatever you want to your custom FBO. This results in a texture. When you're done and you want to display things on your screen, switch to the default framebuffer.
4. Render the above texture just as any other texture. You need an additional program for this in which you may add whatever nice effects you want to the resulted texture.

These very simple points, no matter how primitive (or even slightly inaccurate), helped me make some progress on the topic. Let's see some code now.
FBO

Btw, you may want to use static imports in order to avoid writing GLES20 whenever you use OpenGL ES 2 methods/fields.

LE: I thought I should also include the shaders I'm using above. The basic shaders:

Basic shaders

And the texture shaders:
Basic texture shaders

Tuesday, 29 October 2013

Chained method invocation in Java

Although I've seen it quite a few times in C# (particularly when using lists) and in OpenGL ES 2 (when creating FloatBuffers), I have only recently looked into it. Here's an example of method chaining:

Method chaining example


What's happening is probably self explanatory: a new Student object is created and some of its fields are being set. The alternative is the less nice, yet more common, I guess

Method chaining alternative

Implementing method chaining is very straightforward: rather than returning void in your setters, you return an instance of the current object like this:

Method chaining alternative

Apart from slightly increasing readability, there are no general advantages to method chaining. In fact, this approach could become annoying when trying to debug that particular line where you chained your methods.

An interesting fact is that it was proposed that in Java 7 void methods implicitly return the current object, but this didn't make it into the language. Chaining will, however, be used quite often with Java 8 collections.

More on the topic & related:
Method chaining on Wikipedia
Fluent interface on Wikipedia
Fluent interfaces and Method Chaining in C#

Thursday, 17 October 2013

Static imports

After working with OpenGL, I got tired of writing "GLES20" every single I want to use an OpenGL method. Luckily, there's a solution to that: static imports. You have to import opengl like this:

Static import

What that does is to import all the static members of a particular class - in our case, GLES20. Here's how our code looks without and with static imports:

Static imports

Static imports should be used, however, with care, since they may make the code unreadable. Oracle recommends using them "very sparingly".

Tuesday, 15 October 2013

Initializing fields in Java

I only recently found out that the topic of initializing class and instance fields is not as small as I thought. I wish I was thoroughly introduced to this from the early beginning. Let's have a look at it.

The most straightforward way to initialize a field, whether static or not, is to simply assign it some value. There may be times, however, when the value of your field needs some extra steps to compute. There are three approaches here: firstly, you can initialize the field in the constructor; secondly, you can compute the field value in a method that then returns that value to the field, like below:

Field initialization

And thirdly, the cool -yet possibly confusing- approach: (static) initialization blocks! The following is a valid Java program:
Initialization blocks

All of the methods and blocks described above are executed before the constructor (the blocks are actually added to the top of all the constructors), with static field initialization running before instance field initialization. The below code will illustrate the order in which initialization occurs:
Field initialization

With output:
Field initialization

You can find out more on the topic from Oracle's article. And, although not quite on the same topic, this is where I first saw static blocks: What is called before main?

One last thing to mention: if you don't initialize your fields, they will be assigned a default value (depending on type), with the exception of final fields, which need to be initialized by the coder.

Monday, 14 October 2013

My top OpenGL ES 2 mistakes

I've been learning OpenGL ES 2 for the past month or so and made a lot of annoying mistakes. Here are my top ones. I suspect many beginners went through at least a few of them. Btw, I'm coding on/for Android.

1. Attempting to compile an OpenGL program from the (renderer's) constructor

This happened to me A LOT. What I was doing was to set up my program and handles in the constructor. The right place to do that is in onSurfaceCreated. Make sure you keep that in mind, because, if I remember well, the errors you get are rather cryptic or misleading for the beginner.

2. Forgetting to call glUseProgram()

This one was really annoying, especially when I was convinced that my code was right. Obviously nothing would be drawn on the screen. In order to avoid this, I call glUseProgram() right after my program compiled successfully or, if I use multiple shaders, right at the top of each shader-dedicated draw method.

3. Implicit casting of int operands to float.

One of the "milder" ones, but still annoying. However, it's now second nature to type, for example, 1.0 instead of 1 when I work with floats.

And now probably the most serious and time wasting of them:

4. Poor error identification

Yep. When something crashed or went wrong, I wasted a lot of time trying to find the bug using only at times very cryptic messages from logcat rather than learn how to find and print the error that occurred. Luckily, GLU.gluErrorString() and GLES20.glGetShaderInfoLog() are available.

Lastly, a recommendation. It may seem ironic, but I learned A LOT about OpenGL and graphics in general from the OpenGL ES Programming Guide for iOS. It's a lot more comprehensive than Android's guide.

Saturday, 4 May 2013

Using AndEngine in Intellij IDEA

I've never really liked Eclipse and I normally code with Intellij IDEA, which, btw, has built-in support for Android development.

If you want to use AndEngine in Intellij IDEA, you first have to download the AndEngine source. So

git clone https://github.com/nicolasgramlich/AndEngine 

Now create a new Android project in Intellij, call it whatever you want. Here's the important part:
go to Project Structure (CTRL + ALT + SHIFT + S or File -> Project Structure),

then go to Modules,

hit the green plus -> Import Module,

then select the AndEngine folder from where you downloaded it.

Hit OK, Next, Finish or whatever you may encounter in that particular dialog box, but don't close the Project Structure dialog yet!

Now you should have AndEngine in the Modules list in your dialog. Expand it (click the small arrow just before "AndEngine") and click the Android item that appeared. Make sure "Library Module" is ticked.

Now select the module of your project and in the Dependencies tab, hit the green plus on the far right. Select Module Dependency and from there, AndEngine. Hit OK.

On the left side, in Facets, make sure AndEngine is listed and (click it) "Library Module" is ticked.

Happy coding :)

PS: AndEngine has quite a few "extensions". If you want to run the AndEngine examples, you will need to repeat the steps above for all the dependencies.

LE: These steps also work for Rajawali, a great 3D OpenGL library for Android. :)

Tuesday, 16 April 2013

newo shortcut (live template) in Intellij Idea

What I missed from Netbeans when I moved to Intellij Idea was the "newo" shortcut. Basically, "newo" + TAB will expand to

Object object = new Object();

allowing you to change the type and the variable name. Pretty useful when using long type names. I was not aware of anything similar in Intellij Idea, so I implemented it myself (this works in Intellij Idea 12.1.1):

First, go to Settings (CTRL+ALT+S or File -> Settings) and select "Live Templates" from the list on the left.

Add a new template (ALT + INSERT or hit the green "+" button on the right.

Type "newo" in the abbreviation box and whatever you want in the description. Then type

$TYPE$ $NAME$ = new $TYPE$();

In the template text. Those are live template variables that have to be defined and we'll do so by clicking Edit Variables. For $TYPES$ type typeOfVariable("java.lang.Object") in the Expression column and use "Object" as Default value. For $NAME$ just type suggestVariableName() in the Expression column, hit OK and you're done. :)

Monday, 18 February 2013

Dragging and dropping shapes in Java

Here's my basic drag and drop implementation in a little over 100 lines of code. What you'll need (to do):

First, the list of shapes. Here's a very simple class that acts as a square. All it has are its x and y coordinates, getters & setters for them and then a method that draws the shape.

Square

Now let's think about how the drag and drop works. What do you actually do? Whell, you press your mouse button to select your shape. Then you drag the shape where you want it to be. Then you release the mouse button when you are done dragging to deselect the shape. That's exactly the role our above overriden methods will have: select - move - deselect.

We'll keep a field, selected (of type Square) that knows which shape is selected - if any. mouseReleased will always set it to null. This is the easiest method.

mousePressed isn't much harder though - here we want to know which shape was selected. To do that, we save the coordinates where the button was pressed and check whether any of the shapes in our list resides at those coordinates. If yes, assign our selected field the value of the respective shape. If none of the shapes is in that area, the selected will stay null.

Finally, mouseDragged. If no shape was selected, then it's easy: just return. If we did select a shape, then we need to update its coordinates. As we drag the mouse on the screen, the shape beneath it needs to, well, stay beneath it. For this we are going to take our pointer's coordinates and assign them to our shape. In Java, squares (rectangles) are drawn from the top left corner, so I adjusted my new coordinates for the shape so that its center will always be where the mouse is pointing. Then, of course, we repaint.

Here's the full code:
MyPanel

Finally, put the panel in an applet or frame and there you go.

Saturday, 9 February 2013

Unboxing and autoboxing in Java

I think this is one of the small Java features that don't get that much attention. But it's still nice nonetheless.

Autoboxing means converting from a primitive type to the corresponding wrapper class. Like below (note how much better the code looks when you're adding a new element to an ArrayList):

Autoboxing
Unboxing is the opposite: converting from a wrapper class to a primitive type. Here are a few examples (this one was a bit more interesting :D ):

Unboxing
Here's the article from the Java tutorials.

Friday, 1 February 2013

RSA in/and Python

I'm writing a very basic application that uses the principles behind RSA encryption to send data. Code is here on Bitbucket. Obviously released under my favourite license, WTFPL.

I need to generalize it so that it can be used on different machines, randomly generate the public key instead of using hard coded numbers, accept the message as command line argument and so on. But I probably won't bother much with this, since my main goal was to experiment with the brilliant mathematics behind RSA encryption. Here's the Wikipedia section.

It took me quite some time to accept that RSA relies on some of the most basic number theoretic properties. This is its brilliancy. Here is an example. What you might also find brilliant is the way you can break this brilliant algorithm using a quantum computer. I may write some time about Shor's Algorithm on my Quantum Blog.

Oh, and the other cool thing about this application is Python. First, it's not Java. I had enough of it. Then, well it seems very friendly to mathematical code. And to pseudocode too. In fact, whenever I have to write pseudocode, I use Python syntax - or something very close to it. 

Sunday, 27 January 2013

Planet Hunters (700 stars)

I have just classified my 700th star on Planet Hunters. It took a little over a month to reach this number. I think practice and patience have been the two most important things that made me feel a lot more confident now when I mark transit that I was when I started contributing. Dips aren't always clean and smooth like the ones in the tutorials or in some of the examples. Most of them are very subtle, especially when you're dealing with Earth-sized planets or with Giants with irregular pulsations.

Classify, classify and then classify again! That's how you'll get used to it, that's how you'll learn. It's a bit frustrating at the beginning and you may make a lot of mistakes, like marking an eclipsing binary or a pulsation. But practice is everything.

I compiled a list of useful links for planet hunting:
Examples of quiet stars
Examples of variable stars
Examples of pulsators
Eclipsing binaries
Kianjin's planetary calculator
Transit shapes
Identifying transits in Irregular Pulsating Giants
Explanation of transits
Examples of transits
Huge collection of transits