Basic Display

The Display object in LWJGL provides access to operations that control how the OpenGL rendering will be displayed. The first step in most games is to configure and create the display. Until the display is created there is no OpenGL context and hence no GL resources (textures, display lists, vbos etc) can be created.

Initialisation

The first step in creating the Display is determine the display mode you're going to use to render your game or scene. As luck would have it the Display object allows you to list all the available display modes and hence select the one that most closely matches the display mode you require, like this:

// in this case we only care about the dimensions of the screen, we're aiming
// for an 800x600 display.
int targetWidth = 800;
int targetHeight = 600;
 
DisplayMode chosenMode = null;
 
try {
     DisplayMode[] modes = Display.getAvailableDisplayModes();
 
     for (int i=0;i<modes.length;i++) {
          if ((modes[i].getWidth() == targetWidth) && (modes[i].getHeight() == targetHeight)) {
               chosenMode = modes[i];
               break;
          }
     }
} catch (LWJGLException e) {     
     Sys.alert("Error", "Unable to determine display modes.");
     System.exit(0);
}
 
// at this point if we have no mode there was no appropriate, let the user know 
// and give up
if (chosenMode == null) {
     Sys.alert("Error", "Unable to find appropriate display mode.");
     System.exit(0);
}

After this we go on to actually create the display and finally perform any OpenGL initialisation we want to,

try {
    Display.setDisplayMode(chosenMode);
    Display.setTitle("An example title");
    Display.create();
} catch (LWJGLException e) {
    Sys.alert("Unable to create display.");
    System.exit(0);
}
 
// go on to do any initialisation of OpenGL here, for example loading textures
// or setting up basic global settings 
GL11.glClearColor(0,0,0,0);

Rendering Loop

Having got the display visible its time to render into it. Here we loop round, performing some game logic, rendering using OpenGL then telling the display it needs to redraw. It works like this:

boolean gameRunning = true;
float pos = 0;
 
while (gameRunning) {
     // perform game logic updates here
     pos += 0.01f;    
 
     // render using OpenGL 
     GL11.glBegin(GL11.GL_QUADS);
          GL11.glVertex3f(0,0,pos);
          GL11.glVertex3f(1,0,pos);
          GL11.glVertex3f(1,1,pos);
          GL11.glVertex3f(0,1,pos);
     GL11.glEnd();
 
     // now tell the screen to update
     Display.update();
 
     // finally check if the user has requested that the display be 
     // shutdown
     if (Display.isCloseRequested()) {
           gameRunning = false;
           Display.destroy();
           System.exit(0);
     }
}
 
lwjgl/tutorials/display/basicdisplay.txt · Last modified: 2007/07/07 00:38 (external edit)
 
Recent changes RSS feed Creative Commons License Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki