Tutorial 01 :
Setting up your Java Environment with GL4Java

Tutorial Download Section


Welcome to my first Tutorial !

This tutorial will show you how to install Gl4java in your Java environment.
After this, I will explain you how to create an empty OpenGl scene in a Java application.

For beginner, it is better to go to next tutorial and use the JOGL-JSR231 OpenGl API.
 

I use and modify the basic OpenGl loader created by Jeff Kirby and Darren Hodges and updated by Ron Sullivan.
 

First, you have to install Java. Go to Sun's site and download the Java SDK (Software Development Kit).
Install Java 1.5 (also known as 5.0) or later.

Run the installation and add the environment variable PATH :
(My installation is here : C:\Java\jdk1.5.0_05)
This environment variable is used by your system to know where Java is installed and to know in which folder he should search Java utilities like java, javac ...
 

Go to the System Properties (properties of "Poste de Travail", "work station" or something like that in English). In the Advanced tab, click on the Environment variable button.

Create a new environment variable named PATH.
His value is something like that (depends on your installation folder) :
    C:\Java\jdk1.5.0_05\bin;C:\Java\jdk1.5.0_05\jre\bin

If PATH already exist, add at the the begining (; is a path separator) :
    C:\Java\jdk1.5.0_05\bin;C:\Java\jdk1.5.0_05\jre\bin;
 

Open the file :
    C:/autoexec.bat
Into this file, add a line like:
    SET PATH=C:\Java\jdk1.5.0_05\bin;C:\Java\jdk1.5.0_05\jre\bin

Remark : You need to reboot your machine to takes this in account.
 

Copy these command line on a terminal (console) :
    setenv PATH /home/java/jdk1.5.0_05/bin:/home/java/jdk1.5.0_05/jre/bin
or
    export PATH=/home/java/jdk1.5.0_05/bin:/home/java/jdk1.5.0_05/jre/bin
 

Go to Gl4java page at http://www.jausoft.com/gl4java.php and download Gl4java.
The archives downloaded must contain these jar :
    png.jar
    gl4java.jar
    gl4java-glffonts.jar
    gl4java-glutfonts.jar
and these libraries (Windows):     or     for Linux :
    GL4JavaJauGljJNI14.dll                GL4JavaJauGljJNI14.so

WARNING :
Gl4java development has been stopped since a lot of time. Now, Gl4java site (www.jausoft.com) is CLOSED, older version can be obtained at : http://gl4java.sourceforge.net/.
I encourage you to use JOGL (JSR231). Tutorial 02 introduce this OpenGL API.

Copy all jars in the folder :
    C:\Java\jdk1.5.0_05\jre\lib\ext          //Windows
    /home/java/jdk1.5.0_05/jre/lib/ext       //Linux
and the library in :
    C:\Java\jdk1.5.0_05\jre\bin              //Windows
    /home/java/j2sdk1.4.2_04/jre/lib/i386    //Linux

Note :
For people who have difficulties to find gl4java => Go to next tutorial and use Jogl !
 

This first program load a frame with an empty OpenGl scene (ie black screen).
This is the base code for an OpenGl animated scene.
In the Tutorial 3, I will introduce a more complicated base code but I encouraged you to use this for the beginning (the simpliest).

For people new in OpenGl, this could be hard to understand all of the code by the first reading. By learning OpenGL and looking at the following tutorials, it should be easier to understand.
Don't be discouraged !

This tutorial is composed of two classes : one for loading the frame (or an applet), the other for the OpenGl scene.
 

An animated OpenGl scene can be created in a GLAnimCanvas component (included in GL4Java API) :
    gl4java.awt.GLAnimCanvas
This class extends java.awt.Component (more precisely extends gl4java.awt.GLCanvas and java.awt.Canvas).

First, we have to create a frame, I used to use swing components, so let start with a JFrame (this also works with AWT gui).
Tutorial1 class is an instance of GLAnimCanvs, it can be added into our frame.
The OpenGl animation is starten with the call start.

org.jouvieje.gl4java.container.FrameContainer

package org.jouvieje.gl4java.Container;

import java.awt.*;
import javax.swing.*;

import org.jouvieje.gl4java.tutorials.Tutorial1;

//Gl4java import
import gl4java.awt.GLAnimCanvas;


public class FrameContainer extends JFrame
{
    GLAnimCanvas glScene = null;
   
    public FrameContainer(String titre)
    {
        super(titre);
       
        getContentPane().setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setSize(640, 480);
        setLocationRelativeTo(null);     //position the frame in the screen center
       
        /**
         * Creates our scene and add it in the frame
         */

        glScene = new Tutorial1(getSize().width, getSize().height);
        getContentPane().add(glScene, BorderLayout.CENTER);

       
        start();
    }
   
    public void start()
    {
        //start the OpenGl scene
        glScene.start();
       
        //attempt to get the focus of the canvas
        glScene.requestFocus();
    }
   
    public void stop()
    {
        //stop the OpenGl scene
        glScene.stop();
    }
   
    public void destroy()
    {
        //stop the OpenGl scene and destroy it
        glScene.stop();
        glScene.cvsDispose();
    }
}


We can also load an OpenGl scene in an Applet (JApplet here).
This can be done with this similar code :

org.jouvieje.gl4java.Container.AppletContainer

package org.jouvieje.gl4java.Container;

import java.awt.*;
import javax.swing.JApplet;

import org.jouvieje.gl4java.tutorials.Tutorial1;

import gl4java.awt.GLAnimCanvas;

public class AppletContainer extends JApplet
{
    //our scene
    GLAnimCanvas glScene = null;
   
    /*
     * Initialisation of the Applet
     */

    public void init()
    {
        //creates a layout to add our scene in the center an fit to the Applet
        setLayout(new BorderLayout());
        setSize(640, 480);
       
        /*
         * Create our OpenGl scene and add it in the applet
         */

        glScene = new Tutorial1(getSize().width, getSize().height);
        //add it to the applet
        add(glScene, BorderLayout.CENTER);
    }
   
    /*
     * Start of the applet
     */

    public void start()
    {
        //start the OpenGl scene
        glScene.start();
       
        //attempt to get the focus of the scene
        glScene.requestFocus();
    }
   
    /*
     * Stop of the applet
     */

    public void stop()
    {
        //stop the OpenGl animation
        glScene.stop();
    }
   
    /*
     * Destruction of the Applet
     */

    public void destroy()
    {
        //stop the OpenGl scene and destroy it
        glScene.stop();
        glScene.cvsDispose();
    }
}


Now the container is created, we will create our basic OpenGl scene.
This scene will just clear the background to black.


There are 3 importants methods to declare : reshape, init and display.

   the reshape method : called at each resize event (generally when the frame is resized).
This method defines the Viewport and the Viewing Volume. These two properties are relative to how the scene is drawn into the screen.
This method will be explicated in more details in the Lesson 1 & Lesson 2.

   the init method : this method initialise all you need. You can put in it the initialisation of your data like importing texture, initialise OpenGl properties ...
Called one time at the initilization.

   the display method : this method is the drawing loop (loop for animation). It calls drawGlScene in which we will add the drawing code for the OpenGl scene.


To have access to the OpenGl methods, we mainly use two objects of the GLAnimCanvas instance :
    gl  (GLFunc)  : provides access to OpenGl functionality and graphics card extension.
    glu (GLUFunc) : provides access to OpenGl utility library routine.
This two objects will be used for the initialisation, drawing ...

Here is the commented code :

org.jouvieje.gl4java.tutorials.Tutorial1

package oorg.jouvieje.gl4java.tutorials;

import java.awt.event.*;

import gl4java.awt.GLAnimCanvas;

public class Tutorial1 extends GLAnimCanvas implements KeyListener, MouseMotionListener
{
    //contain the key pressed
    private boolean[] keys = new boolean[256];
   
    private float zOffset = -5.0f;
   
    public Tutorial1(int w, int h)
    {
        super(w, h);
       
        /*
         * Register events listener
         *
         * Remember, the MouseListener does not be added (it is already added
         * in GLAnimCanvas)
         */

        this.addKeyListener(this);
        this.addMouseMotionListener(this);
       
        //seemed to be essential to get any performance
        setAnimateFps(60);
    }
   
    /****************************
     *    The reshape method    *
     ****************************************************************************
     * This method is called at each resize event of the OpenGl component.      *
     *                                                                          *
     * It resize the Viewport of the scene and set the Viewing Volume           *
     ****************************************************************************/

    public void reshape(int width, int height)
    {
        /*
         * First, we use two objects of GLAnimCanvas : gl ad glu
         * - gl provides access to OpenGl functionality and graphics card extension
         * - glu provides access to OpenGl utility library routine
         */

        System.out.println("Width : "+width+" Height: "+height);
        if(height <= 0)
            height = 1;
       
        /*
         * Set the current Viewport region
         * The Viewport is the region of the window in which the scene is drawn
         *
         * Here: all the space
         */

        gl.glViewport(0, 0, width, height);
       
        /*
         * Select the Projection matrix stack.
         * This matrix contain the information related to how the scene is drawn on the
         * screen.
         * Here, we begin to reset it and set the Viewing Volume
         * The viewing volume defines a 3D space in which the scene is drawn
         * (see the Tutorial 19 for more details on the Viewing Volume)
         */

        gl.glMatrixMode(GL_PROJECTION);                             //Select the Projection matrix
        gl.glLoadIdentity();                                        //Reset the current matrix
        glu.gluPerspective(45.0f, width / height, 0.1f, 1000.0f);   //set the Viewing Volume
       
        /*
         * Select the Modelview matrix stack.
         * This matrix contains the differents transformations like the translation, rotation,
         * scale...
         * We only reset the matrix.
         *
         * In the drawing methods, the current matrix is the last selected. So the matrix is
         * the Modelview matrix.
         */

        gl.glMatrixMode(GL_MODELVIEW);    //select The Modelview Matrix
        gl.glLoadIdentity();              //set the ModalView matrix to identity
    }
   
    //Call just before that the GL-Context is create
    public void preInit()
    {
        //Double buffered drawing enabled
        doubleBuffer = true;
        //I DON'T KNOW WHAT IS STEREOVIEW !!!
        stereoView = false;
    }
   
    /*************************
     *    The init method    *
     ***********************************************************
     * This is called just after the GL-Context is create      *
     *                                                         *
     * This method is used to :                                *
     * - activate some modes like texture, light ...           *
     * - affect value to properties                            *
     * - import testures, load your data ...                   *
     ***********************************************************/

    public void init()
    {
        /*
         * Enables the Smooth color shading mode to create graduate color
         * The effect can be shown on the Pyramid of the Tutorial 04
         */

        gl.glShadeModel(GL_SMOOTH);
        /*
         * Defines the clearing color in RGB mode (Red Green Blue)
         * This color is the background color of the scene.
         * Components must be a float number in the interval [0,1]
         * Here: R=0, G=0, B=0 so the color is black
         * (r=1, G=1, B=1 is the white color)
         *
         * Rem: the last value is the Alpha components (also called RGBA).
         * We should show its effects in the Blending tutorial (09)
         */

        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
       
        /*
         * The Depth buffer
         * This buffer keeps tracks the depth of each points of the scene.
         * This buffer, when an object is drawn, tests if the object
         * is behind or in front of the objects already drawn.
         * GL_LEQUAL test if the current object to be drawn is closer
         * or as the same distance than
         */

        gl.glClearDepth(1.0);             //Enable Clearing of the Depth buffer
        gl.glDepthFunc(GL_LEQUAL);        //Type of Depth test
        gl.glEnable(GL_DEPTH_TEST);       //Enable Depth Testing
       
        //Define the correction done to the perspective calculation (perspective looks a it better)
        gl.glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    }
   
    /*******************************
     *    Draw the OpenGl scene    *
     *******************************************************************
     * Here we place all the code related to the drawing of the scene. *
     * This method is called by the drawing loop (the display method)  *
     *******************************************************************/

    public void drawGlScene()
    {
        /*
         * We begin to clear the color and the depth buffer and reset the view.
         * After, we translate the repere axis to the back. This is used to view
         * the scene : Remember to call something like that !
         */

        gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);    //Clear the buffers
        gl.glLoadIdentity();                                      //Reset the view
        gl.glTranslatef(0.0f, 0.0f, zOffset);                     //Translate the scene backwards
       
        /***********************
         * THE DRAWING IS HERE *
         ********************************************
         * We will see that in futur tutoriaux.     *
         ********************************************/

       
        processEvents();
    }
   
    /**********************
     *    Display loop    *
     *******************************************************************
     * This method is the drawing loop, it calls                       *
     *******************************************************************/

    public void display()
    {
        if(!glj.gljMakeCurrent())    //Ensure GL is initialised correctly
        return;
       
        //draw the scene
        drawGlScene();
       
        /*
         * Swap buffers
         * By using double-buffering, the scene is entirely drawn in a buffer
         * out of the screen. After the drawing is finish, the buffers are
         * permutated to print the scene instantly in the screen.
         */

        glj.gljSwap();
        glj.gljCheckGL();       //Check for errors
        glj.gljFree();          //release GL
    }
   
                /*The events*/
   
    /****************************
     *    Process the events    *
     *******************************************************************
     * Put here all the events related to a key or a mouse pressed.   *
     *******************************************************************/

    public void processEvents()
    {
        /*
         * Put here all related OpenGl effects of the events
         *
         * How put the events here:
         * Just because if you would call an OpenGl method in on of
         * the key or mouse method, it do not work !
         *
         * Ex: in the Tutorial 04, the call: gl.glShadeModel(...)
         * could not be placed on an event method.
         */

    }
   
                /*Key events*/
   
    public void keyReleased(KeyEvent ke)
    {
        switch(ke.getKeyCode())
        {
            //close the application with the escape key
            case KeyEvent.VK_ESCAPE: System.exit(0); break;
        }
    }
    public void keyPressed(KeyEvent ke){}
    public void keyTyped(KeyEvent ke){}
   
                /*Mouse events*/
   
    public void mouseEntered(MouseEvent me)
    {
        if(me.getComponent().equals(this))
            requestFocus();
    }
    public void mouseExited(MouseEvent me){}
    public void mouseClicked(MouseEvent me){}
    public void mousePressed(MouseEvent me){}
    public void mouseReleased(MouseEvent me){}
   
    public void mouseMoved(MouseEvent me){}
    public void mouseDragged(MouseEvent me){}
}

 

To run the application, just execute one of these files:
    Tutorial01.jar                 (run the frame)
    runFrame-Gl4java.bat           (run the frame)
    runApplet-Gl4java.bat          (run the applet in a frame)
    Tutorial01-Gl4java.html        (run the applet)

If it fails, your environment may not be well installed !
If a windows is loaded with a black background, OpenGl is well installed. You can go to next tutorials.
 


If you've got any remarks on this tutorial, please let me know to improve it.
Thanks in advance for your feedback.
 

Back

Next turorial

Copyright © 2004-2012 Jérôme Jouvie - All rights reserved. http://jerome.jouvie.free.fr/